diff --git a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/PreRegistrationApplication.java b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/PreRegistrationApplication.java index 9a3240e7046..849e25be586 100644 --- a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/PreRegistrationApplication.java +++ b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/PreRegistrationApplication.java @@ -22,4 +22,4 @@ public class PreRegistrationApplication { public static void main(String[] args) { SpringApplication.run(PreRegistrationApplication.class, args); } -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/config/ApplicationEventListerner.java b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/config/ApplicationEventListerner.java index 3d462920795..29e4f804b95 100644 --- a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/config/ApplicationEventListerner.java +++ b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/config/ApplicationEventListerner.java @@ -11,6 +11,10 @@ import io.mosip.preregistration.application.service.LoginService; import io.mosip.preregistration.core.config.LoggerConfiguration; +import static io.mosip.preregistration.application.constant.PreRegLoginConstant.LOGGER_SESSIONID; +import static io.mosip.preregistration.application.constant.PreRegLoginConstant.LOGGER_IDTYPE; +import static io.mosip.preregistration.application.constant.PreRegLoginConstant.LOGGER_ID; + @Configuration public class ApplicationEventListerner { @@ -27,15 +31,14 @@ public class ApplicationEventListerner { @EventListener(ApplicationStartedEvent.class) public void applicationStartedEvent() { - log.info("sessionId", "idType", "id", "In applicationStartedEvent method of ApplicationEventListerner"); - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In applicationStartedEvent method of ApplicationEventListerner"); + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In applicationStartedEvent method of ApplicationEventListerner login service setupLoginService method called"); demographicService.setup(); - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In applicationStartedEvent method of ApplicationEventListerner demographic Service setup() method is called"); documentService.setup(); - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In applicationStartedEvent method of ApplicationEventListerner documentService setup() method is called"); } - } diff --git a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/constant/PreRegLoginConstant.java b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/constant/PreRegLoginConstant.java index e451b989cd5..e51d5ff3759 100644 --- a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/constant/PreRegLoginConstant.java +++ b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/constant/PreRegLoginConstant.java @@ -1,7 +1,14 @@ package io.mosip.preregistration.application.constant; public class PreRegLoginConstant { + private PreRegLoginConstant() { + throw new IllegalStateException("PreRegLoginConstant class"); + } + public static final String LOGGER_SESSIONID = "PRE-REGISTRATION"; + public static final String LOGGER_IDTYPE = "APPLICATION SERVICE"; + public static final String LOGGER_ID = ""; + public static final String OTP_SMS_TEMPLATE = "pre.reg.login.otp.sms.template"; public static final String OTP_SUBJECT_TEMPLATE = "pre.reg.login.otp.mail.subject.template"; public static final String OTP_CONTENT_TEMPLATE = "pre.reg.login.otp.mail.content.template"; diff --git a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/controller/DemographicController.java b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/controller/DemographicController.java index b2a76adb82c..a9a0f97cab4 100644 --- a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/controller/DemographicController.java +++ b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/controller/DemographicController.java @@ -49,6 +49,10 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; +import static io.mosip.preregistration.application.constant.PreRegLoginConstant.LOGGER_SESSIONID; +import static io.mosip.preregistration.application.constant.PreRegLoginConstant.LOGGER_IDTYPE; +import static io.mosip.preregistration.application.constant.PreRegLoginConstant.LOGGER_ID; + /** * This class provides different API's to perform operations on * pre-registration. @@ -115,7 +119,7 @@ public void initBinder(WebDataBinder binder) { public ResponseEntity> addPreRegDemographicData( @Validated @RequestBody(required = true) MainRequestDTO jsonObject, @ApiParam(hidden = true) Errors errors) { - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In pre-registration controller for add preregistration with json object" + jsonObject); requestValidator.validateId(CREATE, jsonObject.getId(), errors); DataValidationUtil.validate(errors, CREATE); @@ -145,7 +149,7 @@ public ResponseEntity> updatePreRe @Validated @RequestBody(required = true) MainRequestDTO jsonObject, @ApiParam(hidden = true) Errors errors) { String userId = preRegistrationService.authUserDetails().getUserId(); - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In pre-registration controller for Update preregistration with json object" + jsonObject); requestValidator.validateId(UPDATE, jsonObject.getId(), errors); DataValidationUtil.validate(errors, UPDATE); @@ -170,7 +174,7 @@ public ResponseEntity> updatePreRe @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public ResponseEntity> getPreRegDemographicData( @PathVariable("preRegistrationId") String preRegistraionId) { - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In pre-registration controller for fetching all demographic data with preregistrationId" + preRegistraionId); return ResponseEntity.status(HttpStatus.OK).body(preRegistrationService.getDemographicData(preRegistraionId)); @@ -198,7 +202,7 @@ public ResponseEntity> updatePreRegApplicationStatus( @PathVariable("preRegistrationId") String preRegId, @RequestParam(value = "statusCode", required = true) String status) { String userId = preRegistrationService.authUserDetails().getUserId(); - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In pre-registration controller for fetching all demographic data with preRegId " + preRegId + " and status " + status); return ResponseEntity.status(HttpStatus.OK) @@ -225,7 +229,7 @@ public ResponseEntity> updatePreRegApplicationStatus( public ResponseEntity> getAllPreRegApplications(HttpServletRequest res, @RequestParam(value = "pageIndex", required = false) String pageIdx) { String userId = preRegistrationService.authUserDetails().getUserId(); - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In pre-registration controller for fetching all applications with userId "); return ResponseEntity.status(HttpStatus.OK) .body(preRegistrationService.getAllApplicationDetails(userId, pageIdx)); @@ -250,7 +254,7 @@ public ResponseEntity> getAllPreRegAppli public ResponseEntity> getPreRegApplicationStatus( @PathVariable("preRegistrationId") String preId) { String userId = preRegistrationService.authUserDetails().getUserId(); - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In pre-registration controller for fetching all applicationStatus with preId " + preId); return ResponseEntity.status(HttpStatus.OK).body(preRegistrationService.getApplicationStatus(preId, userId)); } @@ -274,7 +278,7 @@ public ResponseEntity> getPreRegApplic public ResponseEntity> deletePreRegApplication( @PathVariable("preRegistrationId") String preId) { String userId = preRegistrationService.authUserDetails().getUserId(); - log.info("sessionId", "idType", "id", + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In pre-registration controller for deletion of individual with preId " + preId); return ResponseEntity.status(HttpStatus.OK).body(preRegistrationService.deleteIndividual(preId, userId)); @@ -309,9 +313,8 @@ public ResponseEntity>> getUpdatedDateTimeBy @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public ResponseEntity> getPreRegDemographicAndDocumentData( @PathVariable("preregistrationId") String preregistrationId) { - log.info("In demographic controller to getFullPreRegApplication {}", preregistrationId); + log.info(LOGGER_SESSIONID, LOGGER_IDTYPE, LOGGER_ID, "In demographic controller to getFullPreRegApplication " + preregistrationId); return ResponseEntity.status(HttpStatus.OK) .body(preRegistrationService.getPregistrationInfo(preregistrationId)); } - } diff --git a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/DemographicService.java b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/DemographicService.java index 0e5a9d733ed..9a87396f57b 100644 --- a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/DemographicService.java +++ b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/DemographicService.java @@ -4,7 +4,6 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; -import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -19,7 +18,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; -import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; @@ -43,8 +41,6 @@ import io.mosip.kernel.core.util.JsonUtils; import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.preregistration.application.code.DemographicRequestCodes; -import io.mosip.preregistration.application.dto.ApplicantTypeRequestDTO; -import io.mosip.preregistration.application.dto.ApplicantValidDocumentDto; import io.mosip.preregistration.application.dto.ApplicationInfoMetadataDTO; import io.mosip.preregistration.application.dto.DeletePreRegistartionDTO; import io.mosip.preregistration.application.dto.DemographicCreateResponseDTO; @@ -53,7 +49,6 @@ import io.mosip.preregistration.application.dto.DemographicUpdateResponseDTO; import io.mosip.preregistration.application.dto.DemographicViewDTO; import io.mosip.preregistration.application.dto.IdSchemaDto; -import io.mosip.preregistration.application.dto.SchemaResponseDto; import io.mosip.preregistration.application.errorcodes.ApplicationErrorCodes; import io.mosip.preregistration.application.errorcodes.ApplicationErrorMessages; import io.mosip.preregistration.application.errorcodes.DemographicErrorCodes; @@ -61,11 +56,11 @@ import io.mosip.preregistration.application.exception.BookingDeletionFailedException; import io.mosip.preregistration.application.exception.DemographicServiceException; import io.mosip.preregistration.application.exception.DocumentNotFoundException; -import io.mosip.preregistration.application.exception.RecordFailedToUpdateException; import io.mosip.preregistration.application.exception.RecordNotFoundException; import io.mosip.preregistration.application.exception.RecordNotFoundForPreIdsException; import io.mosip.preregistration.application.exception.util.DemographicExceptionCatcher; import io.mosip.preregistration.application.repository.DemographicRepository; +import io.mosip.preregistration.application.service.util.CommonServiceUtil; import io.mosip.preregistration.application.service.util.DemographicServiceUtil; import io.mosip.preregistration.core.code.AuditLogVariables; import io.mosip.preregistration.core.code.BookingTypeCodes; @@ -79,7 +74,6 @@ import io.mosip.preregistration.core.common.dto.DemographicResponseDTO; import io.mosip.preregistration.core.common.dto.DocumentMultipartResponseDTO; import io.mosip.preregistration.core.common.dto.DocumentsMetaData; -import io.mosip.preregistration.core.common.dto.ExceptionJSONInfoDTO; import io.mosip.preregistration.core.common.dto.MainRequestDTO; import io.mosip.preregistration.core.common.dto.MainResponseDTO; import io.mosip.preregistration.core.common.dto.PreRegIdsByRegCenterIdDTO; @@ -90,7 +84,6 @@ import io.mosip.preregistration.core.common.entity.DocumentEntity; import io.mosip.preregistration.core.config.LoggerConfiguration; import io.mosip.preregistration.core.exception.EncryptionFailedException; -import io.mosip.preregistration.core.exception.HashingException; import io.mosip.preregistration.core.exception.InvalidPreRegistrationIdException; import io.mosip.preregistration.core.exception.InvalidRequestParameterException; import io.mosip.preregistration.core.exception.PreIdInvalidForUserIdException; @@ -98,7 +91,6 @@ import io.mosip.preregistration.core.exception.RecordFailedToDeleteException; import io.mosip.preregistration.core.util.AuditLogUtil; import io.mosip.preregistration.core.util.CryptoUtil; -import io.mosip.preregistration.core.util.HashUtill; import io.mosip.preregistration.core.util.ValidationUtil; import io.mosip.preregistration.demographic.exception.system.SystemFileIOException; @@ -142,6 +134,9 @@ public class DemographicService implements DemographicServiceIntf { @Autowired private DocumentServiceIntf documentServiceImpl; + @Autowired + CommonServiceUtil commonServiceUtil; + /** * Autowired reference for {@link #AuditLogUtil} */ @@ -174,11 +169,6 @@ public class DemographicService implements DemographicServiceIntf { */ @Value("${mosip.preregistration.demographic.retrieve.basic.id}") private String retrieveId; - /** - * Reference for ${retrieveDetailsId} from property file - */ - @Value("${mosip.preregistration.demographic.retrieve.details.id}") - private String retrieveDetailsId; /** * Reference for ${retrieveStatusId} from property file @@ -223,12 +213,6 @@ public class DemographicService implements DemographicServiceIntf { @Value("${mosip.pregistration.pagesize}") private String pageSize; - /** - * Reference for ${mosip.utc-datetime-pattern} from property file - */ - @Value("${mosip.utc-datetime-pattern}") - private String dateFormat; - @Value("${preregistration.config.identityjson}") private String preregistrationIdJson; /** @@ -251,7 +235,6 @@ public class DemographicService implements DemographicServiceIntf { @Value("${mosip.utc-datetime-pattern}") private String mosipDateTimeFormat; - /** * This method acts as a post constructor to initialize the required request * parameters. @@ -650,48 +633,7 @@ private BookingRegistrationDTO getAppointmentData(DemographicEntity demographicE @Override public MainResponseDTO getApplicationStatus(String preRegId, String userId) { log.info("sessionId", "idType", "id", "In getApplicationStatus method of pre-registration service "); - PreRegistartionStatusDTO statusdto = new PreRegistartionStatusDTO(); - MainResponseDTO response = new MainResponseDTO<>(); - Map requestParamMap = new HashMap<>(); - response.setId(retrieveStatusId); - response.setVersion(version); - response.setResponsetime(serviceUtil.getCurrentResponseTime()); - try { - requestParamMap.put(DemographicRequestCodes.PRE_REGISTRAION_ID.getCode(), preRegId); - if (validationUtil.requstParamValidator(requestParamMap)) { - DemographicEntity demographicEntity = demographicRepository.findBypreRegistrationId(preRegId); - List list = listAuth(authUserDetails().getAuthorities()); - if (demographicEntity != null) { - if (list.contains("ROLE_INDIVIDUAL")) { - userValidation(authUserDetails().getUserId(), demographicEntity.getCreatedBy()); - } - String hashString = HashUtill.hashUtill(demographicEntity.getApplicantDetailJson()); - - if (HashUtill.isHashEqual(demographicEntity.getDemogDetailHash().getBytes(), - hashString.getBytes())) { - statusdto.setPreRegistartionId(demographicEntity.getPreRegistrationId()); - statusdto.setStatusCode(demographicEntity.getStatusCode()); - response.setResponse(statusdto); - - } else { - throw new HashingException( - io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_010.name(), - io.mosip.preregistration.core.errorcodes.ErrorMessages.HASHING_FAILED.name()); - - } - } else { - throw new RecordNotFoundException(DemographicErrorCodes.PRG_PAM_APP_005.getCode(), - DemographicErrorMessages.UNABLE_TO_FETCH_THE_PRE_REGISTRATION.getMessage()); - - } - } - } catch (Exception ex) { - log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In getApplicationStatus method of pre-registration service - " + ex.getMessage()); - new DemographicExceptionCatcher().handle(ex, response); - } - return response; + return commonServiceUtil.getApplicationStatus(preRegId, userId); } /* @@ -778,50 +720,7 @@ public MainResponseDTO deleteIndividual(String preregI @Override public MainResponseDTO getDemographicData(String preRegId) { log.info("sessionId", "idType", "id", "In getDemographicData method of pre-registration service "); - MainResponseDTO response = new MainResponseDTO<>(); - Map requestParamMap = new HashMap<>(); - response.setResponsetime(serviceUtil.getCurrentResponseTime()); - response.setId(retrieveDetailsId); - response.setVersion(version); - try { - requestParamMap.put(DemographicRequestCodes.PRE_REGISTRAION_ID.getCode(), preRegId); - if (validationUtil.requstParamValidator(requestParamMap)) { - - DemographicEntity demographicEntity = demographicRepository.findBypreRegistrationId(preRegId); - if (demographicEntity != null) { - List list = listAuth(authUserDetails().getAuthorities()); - log.info("sessionId", "idType", "id", - "In getDemographicData method of pre-registration service with list " + list); - if (list.contains("ROLE_INDIVIDUAL")) { - userValidation(authUserDetails().getUserId(), demographicEntity.getCreatedBy()); - } - String hashString = HashUtill.hashUtill(demographicEntity.getApplicantDetailJson()); - - if (HashUtill.isHashEqual(demographicEntity.getDemogDetailHash().getBytes(), - hashString.getBytes())) { - - DemographicResponseDTO createDto = serviceUtil.setterForCreateDTO(demographicEntity); - response.setResponse(createDto); - } else { - throw new HashingException( - io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_010.name(), - io.mosip.preregistration.core.errorcodes.ErrorMessages.HASHING_FAILED.name()); - - } - } else { - throw new RecordNotFoundException(DemographicErrorCodes.PRG_PAM_APP_005.getCode(), - DemographicErrorMessages.UNABLE_TO_FETCH_THE_PRE_REGISTRATION.getMessage()); - } - } - } catch (Exception ex) { - log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In getDemographicData of pre-registration service- " + ex.getMessage()); - new DemographicExceptionCatcher().handle(ex, response); - } - - response.setErrors(null); - return response; + return commonServiceUtil.getDemographicData(preRegId); } /* @@ -834,36 +733,7 @@ public MainResponseDTO getDemographicData(String preRegI @Override public MainResponseDTO updatePreRegistrationStatus(String preRegId, String status, String userId) { log.info("sessionId", "idType", "id", "In updatePreRegistrationStatus method of pre-registration service "); - MainResponseDTO response = new MainResponseDTO<>(); - Map requestParamMap = new HashMap<>(); - response.setResponsetime(serviceUtil.getCurrentResponseTime()); - response.setId(updateStatusId); - response.setVersion(version); - try { - requestParamMap.put(DemographicRequestCodes.PRE_REGISTRAION_ID.getCode(), preRegId); - requestParamMap.put(DemographicRequestCodes.STATUS_CODE.getCode(), status); - if (validationUtil.requstParamValidator(requestParamMap)) { - DemographicEntity demographicEntity = demographicRepository.findBypreRegistrationId(preRegId); - statusCheck(demographicEntity, status, userId); - response.setResponse("STATUS_UPDATED_SUCESSFULLY"); - } - } catch (RecordFailedToUpdateException | RecordNotFoundException ex) { - response.setResponse("STATUS_NOT_UPDATED_SUCESSFULLY"); - log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "Error in updatePreRegistrationStatus method of pre-registration service- " + ex.getMessage()); - // new DemographicExceptionCatcher().handle(ex, response); - ExceptionJSONInfoDTO errorDetails = new ExceptionJSONInfoDTO(ex.getErrorCode(), ex.getErrorText()); - List errorList = new ArrayList<>(); - errorList.add(errorDetails); - response.setErrors(errorList); - } catch (Exception ex) { - log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "Error in updatePreRegistrationStatus method of pre-registration service- " + ex.getMessage()); - new DemographicExceptionCatcher().handle(ex, response); - } - return response; + return commonServiceUtil.updatePreRegistrationStatus(preRegId, status, userId); } /** @@ -874,105 +744,11 @@ public MainResponseDTO updatePreRegistrationStatus(String preRegId, Stri */ public void statusCheck(DemographicEntity demographicEntity, String status, String userId) { - if (demographicEntity != null) { - if (serviceUtil.isStatusValid(status)) { - demographicEntity.setStatusCode(StatusCodes.valueOf(status.toUpperCase()).getCode()); - List list = listAuth(authUserDetails().getAuthorities()); - if (list.contains("ROLE_INDIVIDUAL")) { - userValidation(authUserDetails().getUserId(), demographicEntity.getCreatedBy()); - } - if (status.toLowerCase().equals(StatusCodes.PENDING_APPOINTMENT.getCode().toLowerCase())) { - try { - if (isupdateStausToPendingAppointmentValid(demographicEntity)) { - String prid = demographicEntity.getPreRegistrationId(); - serviceUtil.updateApplicationStatus(prid, status, userId); - log.info("Application booking status updated succesfully --> {}", status); - demographicRepository.update(demographicEntity); - log.info("demographic booking status updated succesfully --> {}", status); - - } else { - throw new RecordFailedToUpdateException(DemographicErrorCodes.PRG_PAM_APP_023.getCode(), - DemographicErrorMessages.FAILED_TO_UPDATE_STATUS_PENDING_APPOINTMENT.getMessage()); - } - } catch(Exception e) { - throw new RecordFailedToUpdateException(DemographicErrorCodes.PRG_PAM_APP_023.getCode(), - DemographicErrorMessages.FAILED_TO_UPDATE_STATUS_PENDING_APPOINTMENT.getMessage()); - } - } else { - String prid = demographicEntity.getPreRegistrationId(); - serviceUtil.updateApplicationStatus(prid, status, userId); - log.info("Application booking status updated succesfully --> {}", status); - demographicRepository.update(demographicEntity); - log.info("demographic booking status updated succesfully --> {}", status); - - } - } else { - throw new RecordFailedToUpdateException(DemographicErrorCodes.PRG_PAM_APP_005.getCode(), - DemographicErrorMessages.INVALID_STATUS_CODE.getMessage()); - } - } else { - throw new RecordNotFoundException(DemographicErrorCodes.PRG_PAM_APP_005.getCode(), - DemographicErrorMessages.UNABLE_TO_FETCH_THE_PRE_REGISTRATION.getMessage()); - } + commonServiceUtil.statusCheck(demographicEntity, status, userId); } public boolean isupdateStausToPendingAppointmentValid(DemographicEntity demographicEntity) { - boolean isValid = false; - try { - List validMandatoryDocForApplicant = validMandatoryDocumentsForApplicant(demographicEntity); - - log.info("valid mandatory Docs category for applicant-->{}", validMandatoryDocForApplicant); - List uploadedDocs = demographicEntity.getDocumentEntity().stream().map(doc -> doc.getDocCatCode()) - .collect(Collectors.toList()); - log.info("uploaded Docs category --> {}", uploadedDocs); - - isValid = compareUploadedDocListAndValidMandatoryDocList(uploadedDocs, validMandatoryDocForApplicant); - - } catch (Exception ex) { - - log.error("Exception Docs category -->", ex); - throw new DemographicServiceException(((DemographicServiceException) ex).getErrorCode(), - ((DemographicServiceException) ex).getErrorText()); - - } - return isValid; - - } - - public List validMandatoryDocumentsForApplicant(DemographicEntity demographicEntity) throws ParseException { - - String applicantTypeCode = null; - ApplicantValidDocumentDto applicantValidDocuments = null; - - ApplicantTypeRequestDTO applicantTypeRequest = serviceUtil.createApplicantTypeRequest(demographicEntity); - - applicantTypeCode = serviceUtil.getApplicantypeCode(applicantTypeRequest); - - applicantValidDocuments = serviceUtil.getDocCatAndTypeForApplicantCode(applicantTypeCode, - demographicEntity.getLangCode()); - Set mandatoryDocCat = serviceUtil.getMandatoryDocCatogery(); - - log.info("mandatory Docs category --> {}", mandatoryDocCat); - List validMandatoryDocumentForApplicant = applicantValidDocuments.getDocumentCategories().stream() - .filter(docCat -> mandatoryDocCat.contains(docCat.getCode())).map(docCat -> docCat.getCode()) - .collect(Collectors.toList()); - - return validMandatoryDocumentForApplicant; - } - - private boolean compareUploadedDocListAndValidMandatoryDocList(List uploadedDocs, - List validMandatoryDocForApplicant) { - if (validMandatoryDocForApplicant.size() == 0) { - return true; - } else { - uploadedDocs.forEach(docCat -> validMandatoryDocForApplicant.remove(docCat)); - if (validMandatoryDocForApplicant.size() > 0) { - return false; - } else { - return true; - } - } - + return commonServiceUtil.isupdateStausToPendingAppointmentValid(demographicEntity); } /** @@ -1030,7 +806,6 @@ private void getBookingServiceToDeleteAllByPreId(String preregId) throws Excepti throw new BookingDeletionFailedException(deleteBooking.getErrors().get(0).getErrorCode(), deleteBooking.getErrors().get(0).getMessage()); } - } /* @@ -1119,21 +894,6 @@ private JSONObject getDocumentMetadata(DemographicEntity demographicEntity, Stri return null; } - /** - * This method is used to get the list of authorization role - * - * @param collection - * @return list of auth role - */ - public List listAuth(Collection collection) { - List listWORole = new ArrayList<>(); - for (GrantedAuthority authority : collection) { - String s = authority.getAuthority(); - listWORole.add(s); - } - return listWORole; - } - public DemographicIdentityRequestDTO getPreregistrationIdentityJson() { try { @@ -1145,32 +905,6 @@ public DemographicIdentityRequestDTO getPreregistrationIdentityJson() { } return null; } - - private MainResponseDTO getConfigDetailsResponse(String fileName) { - - String response = serviceUtil.getJson(fileName); - JSONObject jsonObject = null; - SchemaResponseDto schemaResponseDto = null; - try { - jsonObject = objectMapper.readValue(response, JSONObject.class); - } catch (JsonParseException e) { - throw new io.mosip.preregistration.demographic.exception.system.JsonParseException( - DemographicErrorMessages.JSON_PARSING_FAILED.getMessage()); - } catch (JsonMappingException e) { - throw new SystemFileIOException(DemographicErrorCodes.PRG_PAM_APP_018.getCode(), - DemographicErrorMessages.UBALE_TO_READ_IDENTITY_JSON.getMessage(), null); - } catch (IOException e) { - throw new SystemFileIOException(DemographicErrorCodes.PRG_PAM_APP_018.getCode(), - DemographicErrorMessages.UBALE_TO_READ_IDENTITY_JSON.getMessage(), null); - } - - MainResponseDTO responseDto = new MainResponseDTO<>(); - schemaResponseDto = new SchemaResponseDto(); - schemaResponseDto.setIdSchema(jsonObject); - responseDto.setResponse(schemaResponseDto); - return responseDto; - - } private List convertSchemaJsonToArray(String schemaJson) { List idschemaAttributes = new ArrayList(); @@ -1196,7 +930,7 @@ private List convertSchemaJsonToArray(String schemaJson) { public MainResponseDTO getPregistrationInfo(String prid) { log.info("In getPregistrationInfo method of DemographicService for prid {}", prid); - MainResponseDTO response = new MainResponseDTO(); + MainResponseDTO response = new MainResponseDTO<>(); response.setVersion(version); response.setResponsetime(DateTimeFormatter.ofPattern(mosipDateTimeFormat).format(LocalDateTime.now())); ApplicationInfoMetadataDTO applicationInfo = new ApplicationInfoMetadataDTO(); @@ -1227,6 +961,4 @@ public MainResponseDTO getPregistrationInfo(String p } return response; } - - } \ No newline at end of file diff --git a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/util/CommonServiceUtil.java b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/util/CommonServiceUtil.java new file mode 100644 index 00000000000..e1429700094 --- /dev/null +++ b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/util/CommonServiceUtil.java @@ -0,0 +1,402 @@ +package io.mosip.preregistration.application.service.util; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +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.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +import io.mosip.kernel.core.authmanager.authadapter.model.AuthUserDetails; +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.preregistration.application.code.DemographicRequestCodes; +import io.mosip.preregistration.application.dto.ApplicantTypeRequestDTO; +import io.mosip.preregistration.application.dto.ApplicantValidDocumentDto; +import io.mosip.preregistration.application.errorcodes.DemographicErrorCodes; +import io.mosip.preregistration.application.errorcodes.DemographicErrorMessages; +import io.mosip.preregistration.application.exception.DemographicServiceException; +import io.mosip.preregistration.application.exception.RecordFailedToUpdateException; +import io.mosip.preregistration.application.exception.RecordNotFoundException; +import io.mosip.preregistration.application.exception.util.DemographicExceptionCatcher; +import io.mosip.preregistration.application.repository.DemographicRepository; +import io.mosip.preregistration.core.code.StatusCodes; +import io.mosip.preregistration.core.common.dto.DemographicResponseDTO; +import io.mosip.preregistration.core.common.dto.ExceptionJSONInfoDTO; +import io.mosip.preregistration.core.common.dto.MainResponseDTO; +import io.mosip.preregistration.core.common.dto.PreRegistartionStatusDTO; +import io.mosip.preregistration.core.common.entity.DemographicEntity; +import io.mosip.preregistration.core.config.LoggerConfiguration; +import io.mosip.preregistration.core.exception.EncryptionFailedException; +import io.mosip.preregistration.core.exception.HashingException; +import io.mosip.preregistration.core.exception.PreIdInvalidForUserIdException; +import io.mosip.preregistration.core.util.CryptoUtil; +import io.mosip.preregistration.core.util.HashUtill; +import io.mosip.preregistration.core.util.ValidationUtil; +import io.mosip.preregistration.demographic.exception.system.JsonParseException; + +/** + * This class provides the common service implementation for DocumentService and + * DemographicService + * + * @author Janardhan B S + * @since 1.0.0 + */ +@Component +@RefreshScope +public class CommonServiceUtil { + /** + * logger instance + */ + private Logger log = LoggerConfiguration.logConfig(CommonServiceUtil.class); + + @Value("${mosip.utc-datetime-pattern}") + private String utcDateTimePattern; + + /** + * Reference for ${retrieveDetailsId} from property file + */ + @Value("${mosip.preregistration.demographic.retrieve.details.id}") + private String retrieveDetailsId; + + /** + * Reference for ${retrieveStatusId} from property file + */ + @Value("${mosip.preregistration.demographic.retrieve.status.id}") + private String retrieveStatusId; + + /** + * Reference for ${ver} from property file + */ + @Value("${version}") + private String version; + + @Value("${masterdata.resource.url}") + private String masterdataResourseUrl; + + /** + * Reference for ${updateStatusId} from property file + */ + @Value("${mosip.preregistration.demographic.update.status.id}") + private String updateStatusId; + + @Autowired + private ValidationUtil validationUtil; + + @Autowired + private CryptoUtil cryptoUtil; + + @Autowired + private DemographicServiceUtil demographicServiceUtil; + + /** + * Autowired reference for {@link #RegistrationRepositary} + */ + @Autowired + private DemographicRepository demographicRepository; + + public MainResponseDTO getDemographicData(String preRegId) { + MainResponseDTO response = new MainResponseDTO<>(); + Map requestParamMap = new HashMap<>(); + response.setResponsetime(getCurrentResponseTime()); + response.setId(retrieveDetailsId); + response.setVersion(version); + try { + requestParamMap.put(DemographicRequestCodes.PRE_REGISTRAION_ID.getCode(), preRegId); + if (validationUtil.requstParamValidator(requestParamMap)) { + DemographicEntity demographicEntity = demographicRepository.findBypreRegistrationId(preRegId); + if (demographicEntity != null) { + List list = listAuth(authUserDetails().getAuthorities()); + log.info("sessionId", "idType", "id", + "In getDemographicData method of pre-registration service with list " + list); + if (list.contains("ROLE_INDIVIDUAL")) { + userValidation(authUserDetails().getUserId(), demographicEntity.getCreatedBy()); + } + + String hashString = HashUtill.hashUtill(demographicEntity.getApplicantDetailJson()); + if (HashUtill.isHashEqual(demographicEntity.getDemogDetailHash().getBytes(), + hashString.getBytes())) { + + DemographicResponseDTO createDto = setterForCreateDTO(demographicEntity); + response.setResponse(createDto); + } else { + throw new HashingException( + io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_010.name(), + io.mosip.preregistration.core.errorcodes.ErrorMessages.HASHING_FAILED.name()); + } + } else { + throw new RecordNotFoundException(DemographicErrorCodes.PRG_PAM_APP_005.getCode(), + DemographicErrorMessages.UNABLE_TO_FETCH_THE_PRE_REGISTRATION.getMessage()); + } + } + } catch (Exception ex) { + log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); + log.error("sessionId", "idType", "id", + "In getDemographicData of pre-registration service- " + ex.getMessage()); + new DemographicExceptionCatcher().handle(ex, response); + } + + response.setErrors(null); + return response; + } + + public String getCurrentResponseTime() { + log.info("sessionId", "idType", "id", "In getCurrentResponseTime method of document service util"); + return DateUtils.formatDate(new Date(System.currentTimeMillis()), utcDateTimePattern); + } + + public AuthUserDetails authUserDetails() { + return (AuthUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + } + + public void userValidation(String authUserId, String preregUserId) { + log.info("sessionId", "idType", "id", "In getDemographicData method of userValidation with priid " + + preregUserId + " and userID " + authUserId); + if (!authUserId.trim().equals(preregUserId.trim())) { + throw new PreIdInvalidForUserIdException(DemographicErrorCodes.PRG_PAM_APP_017.getCode(), + DemographicErrorMessages.INVALID_PREID_FOR_USER.getMessage()); + } + } + + public DemographicResponseDTO setterForCreateDTO(DemographicEntity demographicEntity) { + log.info("sessionId", "idType", "id", "In setterForCreateDTO method of pre-registration service util"); + JSONParser jsonParser = new JSONParser(); + DemographicResponseDTO createDto = new DemographicResponseDTO(); + try { + createDto.setPreRegistrationId(demographicEntity.getPreRegistrationId()); + createDto.setDemographicDetails((JSONObject) jsonParser.parse(new String(cryptoUtil + .decrypt(demographicEntity.getApplicantDetailJson(), demographicEntity.getEncryptedDateTime())))); + createDto.setStatusCode(demographicEntity.getStatusCode()); + createDto.setLangCode(demographicEntity.getLangCode()); + createDto.setCreatedBy(demographicEntity.getCreatedBy()); + createDto.setCreatedDateTime(getLocalDateString(demographicEntity.getCreateDateTime())); + createDto.setUpdatedBy(demographicEntity.getUpdatedBy()); + createDto.setUpdatedDateTime(getLocalDateString(demographicEntity.getUpdateDateTime())); + } catch (ParseException ex) { + log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); + log.error("sessionId", "idType", "id", + "In setterForCreateDTO method of pre-registration service- " + ex.getMessage()); + throw new JsonParseException(DemographicErrorCodes.PRG_PAM_APP_007.getCode(), + DemographicErrorMessages.JSON_PARSING_FAILED.getMessage(), ex.getCause()); + } catch (EncryptionFailedException ex) { + log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); + log.error("sessionId", "idType", "id", + "In setterForCreateDTO method of pre-registration service- " + ex.getMessage()); + throw ex; + } + return createDto; + } + + public String getLocalDateString(LocalDateTime date) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(utcDateTimePattern); + return date.format(dateTimeFormatter); + } + + /** + * This method is used to get the list of authorization role + * + * @param collection + * @return list of auth role + */ + public List listAuth(Collection collection) { + List listWORole = new ArrayList<>(); + for (GrantedAuthority authority : collection) { + String s = authority.getAuthority(); + listWORole.add(s); + } + return listWORole; + } + + public List validMandatoryDocumentsForApplicant(DemographicEntity demographicEntity) throws ParseException { + + String applicantTypeCode = null; + ApplicantValidDocumentDto applicantValidDocuments = null; + + ApplicantTypeRequestDTO applicantTypeRequest = demographicServiceUtil + .createApplicantTypeRequest(demographicEntity); + + applicantTypeCode = demographicServiceUtil.getApplicantypeCode(applicantTypeRequest); + + applicantValidDocuments = demographicServiceUtil.getDocCatAndTypeForApplicantCode(applicantTypeCode, + demographicEntity.getLangCode()); + Set mandatoryDocCat = demographicServiceUtil.getMandatoryDocCatogery(); + + log.info("mandatory Docs category --> {}", mandatoryDocCat); + return applicantValidDocuments.getDocumentCategories().stream() + .filter(docCat -> mandatoryDocCat.contains(docCat.getCode())).map(docCat -> docCat.getCode()) + .collect(Collectors.toList()); + } + + public MainResponseDTO updatePreRegistrationStatus(String preRegId, String status, String userId) { + log.info("sessionId", "idType", "id", "In updatePreRegistrationStatus method of pre-registration service "); + MainResponseDTO response = new MainResponseDTO<>(); + Map requestParamMap = new HashMap<>(); + response.setResponsetime(getCurrentResponseTime()); + response.setId(updateStatusId); + response.setVersion(version); + try { + requestParamMap.put(DemographicRequestCodes.PRE_REGISTRAION_ID.getCode(), preRegId); + requestParamMap.put(DemographicRequestCodes.STATUS_CODE.getCode(), status); + if (validationUtil.requstParamValidator(requestParamMap)) { + DemographicEntity demographicEntity = demographicRepository.findBypreRegistrationId(preRegId); + statusCheck(demographicEntity, status, userId); + response.setResponse("STATUS_UPDATED_SUCESSFULLY"); + } + } catch (RecordFailedToUpdateException | RecordNotFoundException ex) { + response.setResponse("STATUS_NOT_UPDATED_SUCESSFULLY"); + log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); + log.error("sessionId", "idType", "id", + "Error in updatePreRegistrationStatus method of pre-registration service- " + ex.getMessage()); + ExceptionJSONInfoDTO errorDetails = new ExceptionJSONInfoDTO(ex.getErrorCode(), ex.getErrorText()); + List errorList = new ArrayList<>(); + errorList.add(errorDetails); + response.setErrors(errorList); + } catch (Exception ex) { + log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); + log.error("sessionId", "idType", "id", + "Error in updatePreRegistrationStatus method of pre-registration service- " + ex.getMessage()); + new DemographicExceptionCatcher().handle(ex, response); + } + return response; + } + + public MainResponseDTO getApplicationStatus(String preRegId, String userId) { + log.info("sessionId", "idType", "id", "In getApplicationStatus method of pre-registration service "); + PreRegistartionStatusDTO statusdto = new PreRegistartionStatusDTO(); + MainResponseDTO response = new MainResponseDTO<>(); + Map requestParamMap = new HashMap<>(); + response.setId(retrieveStatusId); + response.setVersion(version); + response.setResponsetime(getCurrentResponseTime()); + try { + requestParamMap.put(DemographicRequestCodes.PRE_REGISTRAION_ID.getCode(), preRegId); + if (validationUtil.requstParamValidator(requestParamMap)) { + DemographicEntity demographicEntity = demographicRepository.findBypreRegistrationId(preRegId); + List list = listAuth(authUserDetails().getAuthorities()); + if (demographicEntity != null) { + if (list.contains("ROLE_INDIVIDUAL")) { + userValidation(authUserDetails().getUserId(), demographicEntity.getCreatedBy()); + } + String hashString = HashUtill.hashUtill(demographicEntity.getApplicantDetailJson()); + + if (HashUtill.isHashEqual(demographicEntity.getDemogDetailHash().getBytes(), + hashString.getBytes())) { + statusdto.setPreRegistartionId(demographicEntity.getPreRegistrationId()); + statusdto.setStatusCode(demographicEntity.getStatusCode()); + response.setResponse(statusdto); + + } else { + throw new HashingException( + io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_010.name(), + io.mosip.preregistration.core.errorcodes.ErrorMessages.HASHING_FAILED.name()); + + } + } else { + throw new RecordNotFoundException(DemographicErrorCodes.PRG_PAM_APP_005.getCode(), + DemographicErrorMessages.UNABLE_TO_FETCH_THE_PRE_REGISTRATION.getMessage()); + + } + } + } catch (Exception ex) { + log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); + log.error("sessionId", "idType", "id", + "In getApplicationStatus method of pre-registration service - " + ex.getMessage()); + new DemographicExceptionCatcher().handle(ex, response); + } + return response; + } + + public void statusCheck(DemographicEntity demographicEntity, String status, String userId) { + if (demographicEntity != null) { + if (demographicServiceUtil.isStatusValid(status)) { + demographicEntity.setStatusCode(StatusCodes.valueOf(status.toUpperCase()).getCode()); + List list = listAuth(authUserDetails().getAuthorities()); + if (list.contains("ROLE_INDIVIDUAL")) { + userValidation(authUserDetails().getUserId(), demographicEntity.getCreatedBy()); + } + if (status.toLowerCase().equals(StatusCodes.PENDING_APPOINTMENT.getCode().toLowerCase())) { + try { + if (isupdateStausToPendingAppointmentValid(demographicEntity)) { + String prid = demographicEntity.getPreRegistrationId(); + demographicServiceUtil.updateApplicationStatus(prid, status, userId); + log.info("Application booking status updated succesfully --> {}", status); + demographicRepository.update(demographicEntity); + log.info("demographic booking status updated succesfully --> {}", status); + + } else { + throw new RecordFailedToUpdateException(DemographicErrorCodes.PRG_PAM_APP_023.getCode(), + DemographicErrorMessages.FAILED_TO_UPDATE_STATUS_PENDING_APPOINTMENT.getMessage()); + } + } catch (Exception e) { + throw new RecordFailedToUpdateException(DemographicErrorCodes.PRG_PAM_APP_023.getCode(), + DemographicErrorMessages.FAILED_TO_UPDATE_STATUS_PENDING_APPOINTMENT.getMessage()); + } + } else { + String prid = demographicEntity.getPreRegistrationId(); + demographicServiceUtil.updateApplicationStatus(prid, status, userId); + log.info("Application booking status updated succesfully --> {}", status); + demographicRepository.update(demographicEntity); + log.info("demographic booking status updated succesfully --> {}", status); + + } + } else { + throw new RecordFailedToUpdateException(DemographicErrorCodes.PRG_PAM_APP_005.getCode(), + DemographicErrorMessages.INVALID_STATUS_CODE.getMessage()); + } + } else { + throw new RecordNotFoundException(DemographicErrorCodes.PRG_PAM_APP_005.getCode(), + DemographicErrorMessages.UNABLE_TO_FETCH_THE_PRE_REGISTRATION.getMessage()); + } + } + + public boolean isupdateStausToPendingAppointmentValid(DemographicEntity demographicEntity) { + boolean isValid = false; + try { + List validMandatoryDocForApplicant = validMandatoryDocumentsForApplicant(demographicEntity); + + log.info("valid mandatory Docs category for applicant-->{}", validMandatoryDocForApplicant); + List uploadedDocs = demographicEntity.getDocumentEntity().stream().map(doc -> doc.getDocCatCode()) + .collect(Collectors.toList()); + log.info("uploaded Docs category --> {}", uploadedDocs); + + isValid = compareUploadedDocListAndValidMandatoryDocList(uploadedDocs, validMandatoryDocForApplicant); + + } catch (Exception ex) { + + log.error("Exception Docs category -->", ex); + throw new DemographicServiceException(((DemographicServiceException) ex).getErrorCode(), + ((DemographicServiceException) ex).getErrorText()); + + } + return isValid; + } + + private boolean compareUploadedDocListAndValidMandatoryDocList(List uploadedDocs, + List validMandatoryDocForApplicant) { + if (validMandatoryDocForApplicant.isEmpty()) { + return true; + } else { + uploadedDocs.forEach(docCat -> validMandatoryDocForApplicant.remove(docCat)); + if (!validMandatoryDocForApplicant.isEmpty()) { + return false; + } else { + return true; + } + } + } +} \ No newline at end of file diff --git a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/util/DocumentServiceUtil.java b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/util/DocumentServiceUtil.java index c7245252258..6554e8c92e0 100644 --- a/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/util/DocumentServiceUtil.java +++ b/pre-registration/pre-registration-application-service/src/main/java/io/mosip/preregistration/application/service/util/DocumentServiceUtil.java @@ -45,7 +45,6 @@ import io.mosip.preregistration.application.exception.DocumentNotValidException; import io.mosip.preregistration.application.exception.DocumentSizeExceedException; import io.mosip.preregistration.application.exception.InvalidDocumentIdExcepion; -import io.mosip.preregistration.application.service.DemographicService; import io.mosip.preregistration.core.code.StatusCodes; import io.mosip.preregistration.core.common.dto.DemographicResponseDTO; import io.mosip.preregistration.core.common.dto.MainRequestDTO; @@ -93,7 +92,7 @@ public class DocumentServiceUtil { ValidationUtil validationUtil; @Autowired - private DemographicService demographgicService; + private CommonServiceUtil commonServiceUtil; /** * Reference for ${demographic.resource.url} from property file @@ -235,7 +234,6 @@ public Integer parseDocumentId(String documentId) { throw new InvalidDocumentIdExcepion(DocumentErrorCodes.PRG_PAM_DOC_019.toString(), DocumentErrorMessages.INVALID_DOCUMENT_ID.getMessage()); } - } public boolean isValidCatCode(String catCode) { @@ -306,9 +304,10 @@ public boolean fileSizeCheck(long uploadedFileSize) { */ public boolean fileExtensionCheck(MultipartFile file) { log.info("sessionId", "idType", "id", "In fileExtensionCheck method of document service util"); - //List fileExtensionList = Arrays.asList(fileExtension.split("\\s*,\\s*")); + // List fileExtensionList = + // Arrays.asList(fileExtension.split("\\s*,\\s*")); List fileExtensionList = Arrays.asList(fileExtension.split(",")); - List fileExtensionTrimmedList = new ArrayList(); + List fileExtensionTrimmedList = new ArrayList(); fileExtensionList.forEach(str -> fileExtensionTrimmedList.add(str.trim())); if (fileExtensionTrimmedList.contains(FilenameUtils.getExtension(file.getOriginalFilename()).toUpperCase())) { return true; @@ -324,7 +323,6 @@ public boolean fileExtensionCheck(MultipartFile file) { * @param documentDto DocumentRequestDTO * @return boolean */ - public boolean isValidRequest(DocumentRequestDTO documentDto, String preRegistrationId) { log.info("sessionId", "idType", "id", "In isValidRequest method of document service util"); if (isNull(preRegistrationId)) { @@ -338,29 +336,29 @@ public boolean isValidRequest(DocumentRequestDTO documentDto, String preRegistra * This method checks the file extension * * @param file pass uploaded file - * @throws java.io.IOException + * @throws java.io.IOException * @throws DocumentNotValidException if uploaded document is not valid */ - public void virusScanCheck(MultipartFile file) throws java.io.IOException { - try { - log.info("sessionId", "idType", "id", "In isVirusScanSuccess method of document service util"); - Boolean scanSuccess = virusScan.scanDocument(file.getBytes()); - if (!scanSuccess) { - throw new VirusScannerException(DocumentErrorCodes.PRG_PAM_DOC_010.toString(), - DocumentErrorMessages.DOCUMENT_FAILED_IN_VIRUS_SCAN.getMessage()); - } - } catch (VirusScannerException e) { - log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(e)); - log.error("sessionId", "idType", "id", e.getMessage()); - throw new VirusScannerException(DocumentErrorCodes.PRG_PAM_DOC_010.toString(), - DocumentErrorMessages.DOCUMENT_FAILED_IN_VIRUS_SCAN.getMessage()); - } - } + public void virusScanCheck(MultipartFile file) throws java.io.IOException { + try { + log.info("sessionId", "idType", "id", "In isVirusScanSuccess method of document service util"); + Boolean scanSuccess = virusScan.scanDocument(file.getBytes()); + if (!scanSuccess) { + throw new VirusScannerException(DocumentErrorCodes.PRG_PAM_DOC_010.toString(), + DocumentErrorMessages.DOCUMENT_FAILED_IN_VIRUS_SCAN.getMessage()); + } + } catch (VirusScannerException e) { + log.error("sessionId", "idType", "id", ExceptionUtils.getStackTrace(e)); + log.error("sessionId", "idType", "id", e.getMessage()); + throw new VirusScannerException(DocumentErrorCodes.PRG_PAM_DOC_010.toString(), + DocumentErrorMessages.DOCUMENT_FAILED_IN_VIRUS_SCAN.getMessage()); + } + } public DemographicResponseDTO getPreRegInfoRestService(String preId) { log.info("sessionId", "idType", "id", "In callGetPreRegInfoRestService method of document service util"); - MainResponseDTO getDemographicData = demographgicService.getDemographicData(preId); + MainResponseDTO getDemographicData = commonServiceUtil.getDemographicData(preId); if (getDemographicData.getErrors() != null) { throw new DemographicGetDetailsException(getDemographicData.getErrors().get(0).getErrorCode(), getDemographicData.getErrors().get(0).getMessage()); @@ -382,28 +380,26 @@ public boolean isMandatoryDocumentDeleted(DemographicEntity demographicEntity) public List validMandatoryDocuments(DemographicEntity demographicEntity) throws org.json.simple.parser.ParseException { - return demographgicService.validMandatoryDocumentsForApplicant(demographicEntity); + return commonServiceUtil.validMandatoryDocumentsForApplicant(demographicEntity); } private boolean compareUploadedDocListAndValidMandatoryDocList(List availableDocs, List validMandatoryDocForApplicant) { - if (validMandatoryDocForApplicant.size() == 0) { + if (validMandatoryDocForApplicant.isEmpty()) { return false; } else { availableDocs.forEach(docCat -> validMandatoryDocForApplicant.remove(docCat)); - if (validMandatoryDocForApplicant.size() > 0) { + if (!validMandatoryDocForApplicant.isEmpty()) { return true; } else { return false; } } - } @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED) public void updateApplicationStatusToIncomplete(DemographicEntity demographicEntity) { - demographgicService.updatePreRegistrationStatus(demographicEntity.getPreRegistrationId(), + commonServiceUtil.updatePreRegistrationStatus(demographicEntity.getPreRegistrationId(), StatusCodes.APPLICATION_INCOMPLETE.getCode(), demographicEntity.getCreatedBy()); } - } diff --git a/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/service/DemographicServiceTest.java b/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/service/DemographicServiceTest.java index 6a3abcaf8da..dd30cc18887 100644 --- a/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/service/DemographicServiceTest.java +++ b/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/service/DemographicServiceTest.java @@ -28,7 +28,6 @@ import java.util.Map; import java.util.Set; import java.util.TimeZone; -import java.util.stream.Collectors; import org.json.simple.JSONArray; import org.json.simple.JSONObject; @@ -46,7 +45,6 @@ import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.ParameterizedTypeReference; @@ -72,8 +70,6 @@ */ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -97,6 +93,7 @@ import io.mosip.preregistration.application.exception.RecordNotFoundException; import io.mosip.preregistration.application.exception.RecordNotFoundForPreIdsException; import io.mosip.preregistration.application.repository.DemographicRepository; +import io.mosip.preregistration.application.service.util.CommonServiceUtil; import io.mosip.preregistration.application.service.util.DemographicServiceUtil; //import io.mosip.preregistration.booking.service.BookingServiceIntf; import io.mosip.preregistration.core.code.AuditLogVariables; @@ -138,14 +135,20 @@ @ContextConfiguration(classes = { DemographicServiceIntf.class }) public class DemographicServiceTest { + @Mock + private CryptoUtil cryptoUtil; + + @InjectMocks + private CommonServiceUtil commonServiceUtil; + /** - * Autowired reference for $link{DemographicService} + * Autowired reference for $link{DemographicServiceUtil} */ - @InjectMocks - private DemographicServiceIntf preRegistrationService = new DemographicService(); + @Mock + DemographicServiceUtil demographicServiceUtil; - @InjectMocks - DemographicService demographicService; + @Mock + ValidationUtil validationUtil; /** * Mocking the DemographicRepository bean @@ -153,6 +156,15 @@ public class DemographicServiceTest { @Mock private DemographicRepository demographicRepository; + /** + * Autowired reference for $link{DemographicService} + */ + @InjectMocks + private DemographicServiceIntf preRegistrationService = new DemographicService(); + + @InjectMocks + DemographicService demographicService; + /** * Mocking the RestTemplateBuilder bean */ @@ -171,15 +183,6 @@ public class DemographicServiceTest { @Mock(name = "idObjectValidator") private IdObjectValidator jsonValidator; - /** - * Autowired reference for $link{DemographicServiceUtil} - */ - @Mock - DemographicServiceUtil serviceUtil; - - @Mock - ValidationUtil validationUtil; - JSONParser parser = new JSONParser(); @Mock @@ -195,9 +198,6 @@ public class DemographicServiceTest { @Mock private AuditLogUtil auditLogUtil; - @Mock - private CryptoUtil cryptoUtil; - @Mock private RequestValidator requestValidator; @@ -328,6 +328,7 @@ public class DemographicServiceTest { public void setup() throws ParseException, FileNotFoundException, IOException, org.json.simple.parser.ParseException, URISyntaxException { + MockitoAnnotations.openMocks(this); MockitoAnnotations.initMocks(this); mapper = new ObjectMapper(); auditRequestDto = new AuditRequestDto(); @@ -337,7 +338,10 @@ public void setup() throws ParseException, FileNotFoundException, IOException, ReflectionTestUtils.setField(preRegistrationService, "preregistrationIdJson", "preregistration.config.identityjson"); ReflectionTestUtils.setField(preRegistrationService, "mosipDateTimeFormat", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - + ReflectionTestUtils.setField(commonServiceUtil, "utcDateTimePattern", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + ReflectionTestUtils.setField(preRegistrationService, "commonServiceUtil", commonServiceUtil); + ReflectionTestUtils.setField(demographicService, "commonServiceUtil", commonServiceUtil); + preRegistrationEntity = new DemographicEntity(); ClassLoader classLoader = getClass().getClassLoader(); URI uri = new URI( @@ -361,7 +365,7 @@ public void setup() throws ParseException, FileNotFoundException, IOException, preRegistrationEntity.setCreatedBy("9988905444"); preRegistrationEntity.setStatusCode("Pending_Appointment"); preRegistrationEntity.setUpdateDateTime(times); - List documentEntity = new ArrayList(); + List documentEntity = new ArrayList<>(); DocumentEntity e = new DocumentEntity(); e.setDocCatCode("POA"); documentEntity.add(e); @@ -371,7 +375,7 @@ public void setup() throws ParseException, FileNotFoundException, IOException, .setDemogDetailHash(HashUtill.hashUtill(jsonTestObject.toJSONString().getBytes()).toString()); userEntityDetails.add(preRegistrationEntity); - logger.info("Entity " + preRegistrationEntity); + logger.info("Entity {}", preRegistrationEntity); preRegistrationViewDTO = new DemographicViewDTO(); preRegistrationViewDTO.setStatusCode("Pending_Appointment"); @@ -405,10 +409,10 @@ public void setup() throws ParseException, FileNotFoundException, IOException, responseDTO = new MainResponseDTO(); responseCreateDTO = new MainResponseDTO(); - responseDTO.setResponsetime(serviceUtil.getCurrentResponseTime()); + responseDTO.setResponsetime(demographicServiceUtil.getCurrentResponseTime()); responseDTO.setErrors(null); - responseCreateDTO.setResponsetime(serviceUtil.getCurrentResponseTime()); + responseCreateDTO.setResponsetime(demographicServiceUtil.getCurrentResponseTime()); responseCreateDTO.setErrors(null); auditRequestDto.setActionTimeStamp(LocalDateTime.now(ZoneId.of("UTC"))); @@ -450,7 +454,7 @@ public void setup() throws ParseException, FileNotFoundException, IOException, documentResultDto.setResponse(documentMultipartResponseDTO); Mockito.when(validationUtil.requstParamValidator(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getJson(Mockito.any())) + Mockito.when(demographicServiceUtil.getJson(Mockito.any())) .thenReturn("{\n" + " \"identity\": {\n" + " \"name\": {\n" + " \"value\": \"abcd\"\n" + " },\n" + " \"dob\": {\n" + " \"value\": \"2021\"\n" + " }\n" + " },\n" + " \"documents\": {\n" + " \"poa\": {\n" + " \"value\": \"poa\"\n" @@ -466,8 +470,7 @@ public void setup() throws ParseException, FileNotFoundException, IOException, applicationEntity.setBookingStatusCode("Booked"); applicationEntity.setSlotFromTime(fDate); applicationEntity.setSlotToTime(tDate); - Mockito.when(serviceUtil.findApplicationById(Mockito.any())).thenReturn(applicationEntity); - + Mockito.when(demographicServiceUtil.findApplicationById(Mockito.any())).thenReturn(applicationEntity); } @Test @@ -477,10 +480,11 @@ public void getPreRegistrationTest() { preRegistrationEntity.setDemogDetailHash(HashUtill.hashUtill(preRegistrationEntity.getApplicantDetailJson())); demographicResponseDTO = new DemographicResponseDTO(); demographicResponseDTO.setPreRegistrationId("98746563542672"); - Mockito.when(serviceUtil.setterForCreateDTO(Mockito.any())).thenReturn(demographicResponseDTO); + Mockito.when(demographicServiceUtil.setterForCreateDTO(Mockito.any())).thenReturn(demographicResponseDTO); Mockito.when(demographicRepository.findBypreRegistrationId("98746563542672")).thenReturn(preRegistrationEntity); Mockito.when(cryptoUtil.decrypt(Mockito.any(), Mockito.any())).thenReturn(jsonObject.toString().getBytes()); - MainResponseDTO res = preRegistrationService.getDemographicData("98746563542672"); + + MainResponseDTO res = preRegistrationService.getDemographicData("98746563542672"); assertEquals("98746563542672", res.getResponse().getPreRegistrationId()); } @@ -502,7 +506,7 @@ public void createByDateFailureTest() throws Exception { demographicResponseDTO.setDemographicDetails(jsonObject); demographicResponseDTO.setPreRegistrationId(""); demographicResponseDTO.setCreatedBy("9988905444"); - demographicResponseDTO.setCreatedDateTime(serviceUtil.getLocalDateString(times)); + demographicResponseDTO.setCreatedDateTime(demographicServiceUtil.getLocalDateString(times)); demographicResponseDTO.setStatusCode("Pending_Appointment"); createPreRegistrationDTO = new DemographicRequestDTO(); createPreRegistrationDTO.setDemographicDetails(jsonObject); @@ -516,7 +520,7 @@ public void createByDateFailureTest() throws Exception { Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.eq(new ParameterizedTypeReference>() { }))).thenReturn(res); - Mockito.when(serviceUtil.generateId()).thenReturn("98746563542672"); + Mockito.when(demographicServiceUtil.generateId()).thenReturn("98746563542672"); responseDTO.setResponse(demographicResponseDTO); MainResponseDTO actualRes = preRegistrationService .addPreRegistration(request); @@ -638,7 +642,7 @@ public void getApplicationStatusHashingExceptionTest() { public void getApplicationDetailsTransactionFailureCheck() throws Exception { String userId = "9988905444"; - Mockito.when(serviceUtil.isNull(Mockito.any())).thenReturn(true); + Mockito.when(demographicServiceUtil.isNull(Mockito.any())).thenReturn(true); // DataAccessLayerException exception = new // DataAccessLayerException(DemographicErrorCodes.PRG_PAM_APP_002.toString(), // DemographicErrorMessages.PRE_REGISTRATION_TABLE_NOT_ACCESSIBLE.toString(), @@ -672,11 +676,11 @@ public void deleteIndividualSuccessTest() throws Exception { // delResponseDto.setStatus(Boolean.TRUE); delResponseDto.setErrors(null); delResponseDto.setResponse(deleteDTO); - delResponseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - Mockito.when(serviceUtil.isNull(Mockito.any())).thenReturn(false); - Mockito.when(serviceUtil.checkStatusForDeletion(Mockito.any())).thenReturn(true); + delResponseDto.setResponsetime(demographicServiceUtil.getCurrentResponseTime()); + Mockito.when(demographicServiceUtil.isNull(Mockito.any())).thenReturn(false); + Mockito.when(demographicServiceUtil.checkStatusForDeletion(Mockito.any())).thenReturn(true); MainResponseDTO e = new MainResponseDTO(); - Mockito.when(serviceUtil.deleteBooking(Mockito.any())).thenReturn(e); + Mockito.when(demographicServiceUtil.deleteBooking(Mockito.any())).thenReturn(e); Mockito.when(demographicRepository.findBypreRegistrationId(preRegId)).thenReturn(preRegistrationEntity); @@ -719,7 +723,7 @@ public void deleteIndividualSuccessTest2() throws Exception { deleteBookingDTO.setPreRegistrationId("98746563542672"); List list = new ArrayList<>(); MainResponseDTO e = new MainResponseDTO(); - Mockito.when(serviceUtil.deleteBooking(Mockito.any())).thenReturn(e); + Mockito.when(demographicServiceUtil.deleteBooking(Mockito.any())).thenReturn(e); Mockito.when(demographicRepository.findBypreRegistrationId(preRegId)).thenReturn(preRegistrationEntity); assertNotNull(preRegistrationService.deleteIndividual(preRegId, userId)); } @@ -742,7 +746,7 @@ public void getPreRegistrationHashingExceptionTest() { @Test public void updatePreRegistrationStatusTest() { Mockito.when(demographicRepository.findBypreRegistrationId("98746563542672")).thenReturn(preRegistrationEntity); - Mockito.when(serviceUtil.isStatusValid(Mockito.any())).thenReturn(true); + Mockito.when(demographicServiceUtil.isStatusValid(Mockito.any())).thenReturn(true); MainResponseDTO res = preRegistrationService.updatePreRegistrationStatus("98746563542672", "Booked", userId); assertEquals("STATUS_UPDATED_SUCESSFULLY", res.getResponse()); @@ -752,7 +756,7 @@ public void updatePreRegistrationStatusTest() { @Test public void updatePreRegistrationStatusTests() { Mockito.when(demographicRepository.findBypreRegistrationId("98746563542672")).thenReturn(preRegistrationEntity); - Mockito.when(serviceUtil.isStatusValid(Mockito.any())).thenReturn(true); + Mockito.when(demographicServiceUtil.isStatusValid(Mockito.any())).thenReturn(true); ExceptionJSONInfoDTO err = new ExceptionJSONInfoDTO("PRG_PAM_DOC_015", ""); List errlist = new ArrayList<>(); @@ -894,7 +898,7 @@ public void deleteRecordRestCallException() throws Exception { delResponseDto.setErrors(null); delResponseDto.setResponse(deleteDTO); - delResponseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); + delResponseDto.setResponsetime(demographicServiceUtil.getCurrentResponseTime()); ResponseEntity> res = new ResponseEntity<>(delResponseDto, HttpStatus.OK); @@ -907,8 +911,8 @@ public void deleteRecordRestCallException() throws Exception { Mockito.when(documentServiceIntf.deleteAllByPreId(Mockito.anyString())).thenReturn(deleteAllByPreId1); MainResponseDTO deleteBooking = new MainResponseDTO<>(); deleteBooking.setErrors(errlist); - Mockito.when(serviceUtil.deleteBooking(preRegistrationEntity.getPreRegistrationId())).thenReturn(deleteBooking); - Mockito.when(serviceUtil.checkStatusForDeletion(Mockito.any())).thenReturn(true); + Mockito.when(demographicServiceUtil.deleteBooking(preRegistrationEntity.getPreRegistrationId())).thenReturn(deleteBooking); + Mockito.when(demographicServiceUtil.checkStatusForDeletion(Mockito.any())).thenReturn(true); Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.DELETE), Mockito.any(), Mockito.eq(new ParameterizedTypeReference>() { @@ -936,17 +940,17 @@ public void statusCheckTest() { demographicEntity.setLangCode(""); String status = StatusCodes.PENDING_APPOINTMENT.getCode().toLowerCase(); String userId = "987654321"; - Mockito.when(serviceUtil.isStatusValid(status)).thenReturn(true); + Mockito.when(demographicServiceUtil.isStatusValid(status)).thenReturn(true); ApplicantValidDocumentDto applicantValidDocuments = new ApplicantValidDocumentDto(); Collection documentCategories = new ArrayList(); DocumentCategoryAndTypeResponseDto documentCategoryAndTypeResponseDto = new DocumentCategoryAndTypeResponseDto(); documentCategoryAndTypeResponseDto.setCode("abc"); Set mandatoryDocCat = new HashSet<>(); mandatoryDocCat.add(""); - Mockito.when(serviceUtil.getMandatoryDocCatogery()).thenReturn(mandatoryDocCat); + Mockito.when(demographicServiceUtil.getMandatoryDocCatogery()).thenReturn(mandatoryDocCat); documentCategories.add(documentCategoryAndTypeResponseDto); applicantValidDocuments.setDocumentCategories(documentCategories); - Mockito.when(serviceUtil.getDocCatAndTypeForApplicantCode(Mockito.any(), Mockito.any())) + Mockito.when(demographicServiceUtil.getDocCatAndTypeForApplicantCode(Mockito.any(), Mockito.any())) .thenReturn(applicantValidDocuments); demographicService.statusCheck(demographicEntity, status, userId); } @@ -964,17 +968,17 @@ public void statusCheckRecordFailedToUpdateExceptionTest() { demographicEntity.setLangCode(""); String status = StatusCodes.PENDING_APPOINTMENT.getCode().toLowerCase(); String userId = "987654321"; - Mockito.when(serviceUtil.isStatusValid(status)).thenReturn(true); + Mockito.when(demographicServiceUtil.isStatusValid(status)).thenReturn(true); ApplicantValidDocumentDto applicantValidDocuments = new ApplicantValidDocumentDto(); Collection documentCategories = new ArrayList(); DocumentCategoryAndTypeResponseDto documentCategoryAndTypeResponseDto = new DocumentCategoryAndTypeResponseDto(); documentCategoryAndTypeResponseDto.setCode("abc"); Set mandatoryDocCat = new HashSet<>(); mandatoryDocCat.add("abc"); - Mockito.when(serviceUtil.getMandatoryDocCatogery()).thenReturn(mandatoryDocCat); + Mockito.when(demographicServiceUtil.getMandatoryDocCatogery()).thenReturn(mandatoryDocCat); documentCategories.add(documentCategoryAndTypeResponseDto); applicantValidDocuments.setDocumentCategories(documentCategories); - Mockito.when(serviceUtil.getDocCatAndTypeForApplicantCode(Mockito.any(), Mockito.any())) + Mockito.when(demographicServiceUtil.getDocCatAndTypeForApplicantCode(Mockito.any(), Mockito.any())) .thenReturn(applicantValidDocuments); demographicService.statusCheck(demographicEntity, status, userId); } @@ -1025,11 +1029,11 @@ public void addPreRegistrationTest() throws Exception { request.setRequesttime(Date.from(Instant.now())); request.setRequest(demographicRequest); MainResponseDTO mainResponseDTO = new MainResponseDTO(); - Mockito.when((MainResponseDTO) serviceUtil.getMainResponseDto(request)) + Mockito.when((MainResponseDTO) demographicServiceUtil.getMainResponseDto(request)) .thenReturn(mainResponseDTO); IdSchemaDto idSchema = new IdSchemaDto(); - Mockito.when(serviceUtil.getSchema()).thenReturn(idSchema); + Mockito.when(demographicServiceUtil.getSchema()).thenReturn(idSchema); idSchema.setId(userId); idSchema.setSchemaJson(identityMappingJson); idSchema.setIdVersion(1.0); @@ -1053,7 +1057,7 @@ public void addPreRegistrationExceptionTest() throws Exception { request.setRequest(demographicRequest); IdSchemaDto idSchema = new IdSchemaDto(); - Mockito.when(serviceUtil.getSchema()).thenReturn(idSchema); + Mockito.when(demographicServiceUtil.getSchema()).thenReturn(idSchema); idSchema.setId(userId); idSchema.setSchemaJson(identityMappingJson); idSchema.setIdVersion(1.0); @@ -1076,7 +1080,7 @@ public void updatePreRegistrationTest() throws IOException { demographicRequest.setRequiredFields(requiredFields); MainResponseDTO mainResponseDTO = new MainResponseDTO(); - Mockito.when((MainResponseDTO) serviceUtil.getMainResponseDto(request)) + Mockito.when((MainResponseDTO) demographicServiceUtil.getMainResponseDto(request)) .thenReturn(mainResponseDTO); mainResponseDTO.setId("12345"); request.setId(userId); @@ -1085,13 +1089,13 @@ public void updatePreRegistrationTest() throws IOException { request.setRequest(demographicRequest); IdSchemaDto idSchema = new IdSchemaDto(); - Mockito.when(serviceUtil.getSchema()).thenReturn(idSchema); + Mockito.when(demographicServiceUtil.getSchema()).thenReturn(idSchema); idSchema.setId(userId); idSchema.setSchemaJson(identityMappingJson); idSchema.setIdVersion(1.0); LocalDateTime time = LocalDateTime.now(); String t = time.toString(); - Mockito.when(serviceUtil.getCurrentResponseTime()).thenReturn(t); + Mockito.when(demographicServiceUtil.getCurrentResponseTime()).thenReturn(t); DemographicEntity demographicEntity = new DemographicEntity(); demographicEntity.setCreatedBy("12345"); Mockito.when(demographicRepository.findBypreRegistrationId(preRegistrationId)).thenReturn(demographicEntity); diff --git a/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/service/DocumentServiceTest.java b/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/service/DocumentServiceTest.java index 414501eb976..bb30f04948a 100644 --- a/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/service/DocumentServiceTest.java +++ b/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/service/DocumentServiceTest.java @@ -582,5 +582,4 @@ public void uploadDocument2Test() public void setupTest() { documentUploadService.setup(); } - -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/test/service/util/DocumentServiceUtilTest.java b/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/test/service/util/DocumentServiceUtilTest.java index f5468cd8eb3..dd9e66415cb 100644 --- a/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/test/service/util/DocumentServiceUtilTest.java +++ b/pre-registration/pre-registration-application-service/src/test/java/io/mosip/preregistration/application/test/service/util/DocumentServiceUtilTest.java @@ -1,5 +1,8 @@ package io.mosip.preregistration.application.test.service.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.io.FileInputStream; import java.io.InputStream; @@ -12,11 +15,13 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.RestTemplate; import io.mosip.commons.khazana.spi.ObjectStoreAdapter; @@ -25,6 +30,7 @@ import io.mosip.preregistration.application.dto.DocumentRequestDTO; import io.mosip.preregistration.application.exception.InvalidDocumentIdExcepion; import io.mosip.preregistration.application.service.DemographicService; +import io.mosip.preregistration.application.service.util.CommonServiceUtil; import io.mosip.preregistration.application.service.util.DocumentServiceUtil; import io.mosip.preregistration.core.common.entity.DocumentEntity; import io.mosip.preregistration.core.exception.InvalidRequestException; @@ -50,8 +56,11 @@ public class DocumentServiceUtilTest { @MockBean private ValidationUtil util; + @MockBean + private CommonServiceUtil commonServiceUtil; + @Autowired - private DocumentServiceUtil serviceUtil; + private DocumentServiceUtil documentServiceUtil; private MockMultipartFile mockMultipartFile; @@ -70,6 +79,11 @@ public class DocumentServiceUtilTest { @Before public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + ReflectionTestUtils.setField(documentServiceUtil, "utcDateTimePattern", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + ReflectionTestUtils.setField(commonServiceUtil, "utcDateTimePattern", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + ReflectionTestUtils.setField(documentServiceUtil, "commonServiceUtil", commonServiceUtil); + ClassLoader classLoader = getClass().getClassLoader(); URI uri = new URI(classLoader.getResource("Doc.pdf").getFile().trim().replaceAll("\\u0020", "%20")); file = new File(uri.getPath()); @@ -78,33 +92,35 @@ public void setUp() throws Exception { @Test public void getDateStringTest() { - serviceUtil.getDateString(new Date()); + String responseTime = documentServiceUtil.getDateString(new Date()); + assertNotNull(responseTime); } @Test public void parseDocumentIdTest() { - serviceUtil.parseDocumentId("1234"); + String validDocumentId = "1234"; + Integer documentId = documentServiceUtil.parseDocumentId(validDocumentId); + assertEquals(Integer.valueOf(validDocumentId), documentId); } @Test(expected = InvalidDocumentIdExcepion.class) public void parseDocumentIdFailureTest() throws Exception { - serviceUtil.parseDocumentId("1234!@#$&^$$~~~~~~#@!$^%"); + documentServiceUtil.parseDocumentId("1234!@#$&^$$~~~~~~#@!$^%"); } @Test(expected = InvalidRequestException.class) - public void isValidCatCodeTest() throws Exception { - serviceUtil.isValidCatCode("13fww"); + public void isValidCatCodeTest() { + documentServiceUtil.isValidCatCode("13fww"); } @Test(expected = InvalidRequestException.class) - public void inValidPreIDTest() throws Exception { - serviceUtil.isValidRequest(documentDto, null); + public void inValidPreIDTest() { + documentServiceUtil.isValidRequest(documentDto, null); } @Test(expected = VirusScannerException.class) public void virusscannerFailureTest() throws Exception { Mockito.when(virusScan.scanDocument(mockMultipartFile.getBytes())).thenThrow(VirusScannerException.class); - serviceUtil.virusScanCheck(mockMultipartFile); + documentServiceUtil.virusScanCheck(mockMultipartFile); } - -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/ApplicationRequestDTO.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/ApplicationRequestDTO.java index 5336306c5ef..4a6a782b4cf 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/ApplicationRequestDTO.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/ApplicationRequestDTO.java @@ -2,12 +2,10 @@ import java.io.Serializable; -import lombok.Getter; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.ToString; - /** * This DTO class defines the variables to accept the input parameter from * request. @@ -16,12 +14,10 @@ * @since 1.2.0 * */ -@Getter -@Setter +@Data @NoArgsConstructor @ToString public class ApplicationRequestDTO implements Serializable { - /** * */ @@ -30,5 +26,4 @@ public class ApplicationRequestDTO implements Serializable { * language code */ private String langCode; - -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/ApplicationResponseDTO.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/ApplicationResponseDTO.java index 708b90d99c2..53ecaa4844a 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/ApplicationResponseDTO.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/ApplicationResponseDTO.java @@ -2,9 +2,8 @@ import java.io.Serializable; -import lombok.Getter; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.ToString; /** @@ -15,8 +14,7 @@ * @since 1.2.0 * */ -@Getter -@Setter +@Data @NoArgsConstructor @ToString public class ApplicationResponseDTO implements Serializable { @@ -55,10 +53,9 @@ public class ApplicationResponseDTO implements Serializable { * language code */ private String langCode; - + /** * the booking type */ private String bookingType; - -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/DeletePreRegistartionDTO.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/DeletePreRegistartionDTO.java index 407a50871f4..5b6eb151436 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/DeletePreRegistartionDTO.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/DeletePreRegistartionDTO.java @@ -33,7 +33,7 @@ public class DeletePreRegistartionDTO implements Serializable { /** The create date time. */ private Date deletedDateTime; - + public void setPreRegistrationId(String preRegistrationId) { this.preRegistrationId = preRegistrationId; } @@ -43,6 +43,6 @@ public void setDeletedBy(String deletedBy) { } public void setDeletedDateTime(Date deletedDateTime) { - this.deletedDateTime =deletedDateTime !=null ? new Date(deletedDateTime.getTime()) : null; + this.deletedDateTime = deletedDateTime != null ? new Date(deletedDateTime.getTime()) : null; } } diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/SchemaResponseDto.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/SchemaResponseDto.java index ab2b3fb832b..c185a365d37 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/SchemaResponseDto.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/application/dto/SchemaResponseDto.java @@ -13,9 +13,6 @@ @NoArgsConstructor @AllArgsConstructor public class SchemaResponseDto { - - - /** The id schema. */ - + /** The id schema. */ private JSONObject idSchema; -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/BookingStatusDTO.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/BookingStatusDTO.java index 7649c92f2db..49b433dc026 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/BookingStatusDTO.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/BookingStatusDTO.java @@ -1,11 +1,8 @@ package io.mosip.preregistration.booking.dto; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; -@Getter -@Setter +@Data public class BookingStatusDTO { - private String bookingMessage; -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/CancelBookingDTO.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/CancelBookingDTO.java index e9068a7133b..669e59a8d90 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/CancelBookingDTO.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/CancelBookingDTO.java @@ -1,22 +1,19 @@ package io.mosip.preregistration.booking.dto; - import java.io.Serializable; + import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; -@Getter -@Setter +@Data public class CancelBookingDTO implements Serializable { - /** * */ private static final long serialVersionUID = 1L; - + /** * registration Center Id */ @@ -35,11 +32,11 @@ public class CancelBookingDTO implements Serializable { @JsonProperty("time_slot_from") @ApiModelProperty(value = "From Time Slot", position = 4) private String slotFromTime; - + /** * booked to Time Slot */ @JsonProperty("time_slot_to") @ApiModelProperty(value = "To Time Slot", position = 5) private String slotToTime; -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/DateTimeDto.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/DateTimeDto.java index 9e57623dbc1..62c3042a6fa 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/DateTimeDto.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/DateTimeDto.java @@ -2,20 +2,17 @@ import java.util.List; -import lombok.Getter; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.ToString; -@Getter -@Setter +@Data @NoArgsConstructor @ToString public class DateTimeDto { - private String date; private boolean isHoliday; private List timeSlots; -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/DemographicBookingRightJoin.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/DemographicBookingRightJoin.java index dc0a1df3877..62fdef2c7be 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/DemographicBookingRightJoin.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/DemographicBookingRightJoin.java @@ -5,16 +5,13 @@ import java.time.LocalTime; import lombok.AllArgsConstructor; -import lombok.Getter; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Setter; -@Getter -@Setter +@Data @NoArgsConstructor @AllArgsConstructor public class DemographicBookingRightJoin implements Serializable { - /** * */ @@ -22,7 +19,7 @@ public class DemographicBookingRightJoin implements Serializable { /** Status of the preid */ private String statusCode; - + /** Registration center id. */ private String registrationCenterId; @@ -34,6 +31,4 @@ public class DemographicBookingRightJoin implements Serializable { /** Appointment date. */ private LocalDate regDate; - - -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/HolidayDto.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/HolidayDto.java index 0c438458674..f391e6b68aa 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/HolidayDto.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/HolidayDto.java @@ -1,28 +1,33 @@ package io.mosip.preregistration.booking.dto; -import lombok.Getter; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.ToString; -@Getter -@Setter +@Data @NoArgsConstructor @ToString public class HolidayDto { private String holidayId; + private String holidayDate; + /** - * Holiday day is day of week as integer value, week start from Monday , Monday is 1 and Sunday is 7 + * Holiday day is day of week as integer value, week start from Monday , Monday + * is 1 and Sunday is 7 */ private String holidayDay; + /** * Holiday month is month of the year as integer value. */ private String holidayMonth; + private String holidayYear; + private String holidayName; + private String languageCode; + private Boolean isActive; - -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequest.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequest.java index cdc93122109..7f4f4f13dcc 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequest.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequest.java @@ -2,17 +2,14 @@ import java.util.List; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; /** * @author Kishan Rathore * @since 1.0.0 * */ -@Getter -@Setter +@Data public class MultiBookingRequest { - - List bookingRequest; -} + private List bookingRequest; +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequestDTO.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequestDTO.java index e3ad9864572..afd7e7ec08b 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequestDTO.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequestDTO.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; @@ -16,8 +15,8 @@ */ @Getter @Setter -public class MultiBookingRequestDTO implements Serializable{ - +public class MultiBookingRequestDTO implements Serializable { + /** * */ @@ -51,5 +50,4 @@ public class MultiBookingRequestDTO implements Serializable{ @JsonProperty("time_slot_to") @ApiModelProperty(value = "To Time Slot", position = 4) private String slotToTime; - } \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterDto.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterDto.java index 86ec0c48760..d71840f39e2 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterDto.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterDto.java @@ -1,4 +1,5 @@ package io.mosip.preregistration.booking.dto; + import java.time.LocalTime; import lombok.Getter; @@ -6,13 +7,11 @@ import lombok.Setter; import lombok.ToString; - @Getter @Setter @NoArgsConstructor @ToString public class RegistrationCenterDto { - private String id; private String name; @@ -58,5 +57,4 @@ public class RegistrationCenterDto { private LocalTime lunchEndTime; private Boolean isActive; - -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterHolidayDto.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterHolidayDto.java index bf1e989e84d..a27c992aac6 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterHolidayDto.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterHolidayDto.java @@ -2,16 +2,15 @@ import java.util.List; -import lombok.Getter; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.ToString; -@Getter -@Setter +@Data @NoArgsConstructor @ToString public class RegistrationCenterHolidayDto { private RegistrationCenterDto registrationCenter; + private List holidays; -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterResponseDto.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterResponseDto.java index a51607c17e8..dac3d74b642 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterResponseDto.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterResponseDto.java @@ -2,16 +2,13 @@ import java.util.List; -import lombok.Getter; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.ToString; - -@Getter -@Setter +@Data @NoArgsConstructor @ToString public class RegistrationCenterResponseDto { private List registrationCenters; -} +} \ No newline at end of file diff --git a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/SlotDto.java b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/SlotDto.java index bdee7f5e19b..79b74a01c06 100644 --- a/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/SlotDto.java +++ b/pre-registration/pre-registration-core/src/main/java/io/mosip/preregistration/booking/dto/SlotDto.java @@ -2,20 +2,17 @@ import java.time.LocalTime; -import lombok.Getter; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.ToString; -@Getter -@Setter +@Data @NoArgsConstructor @ToString public class SlotDto { - private LocalTime fromTime; - + private LocalTime toTime; - + private int availability; -} +} \ No newline at end of file