From eb1329fa1f4eb4402176e6f3f3d1f3efdac05e85 Mon Sep 17 00:00:00 2001 From: JanardhanBS-SyncByte Date: Wed, 12 Jun 2024 17:14:23 +0530 Subject: [PATCH] [Java21] Signed-off-by: JanardhanBS-SyncByte --- .../config/ApplicationEventListerner.java | 13 +- .../constant/PreRegLoginConstant.java | 7 ++ .../controller/DemographicController.java | 21 ++-- .../service/DemographicService.java | 23 +--- .../service/util/CommonServiceUtil.java | 7 +- .../service/util/DocumentServiceUtil.java | 41 +++---- .../service/DemographicServiceTest.java | 116 +++++++++--------- .../service/DocumentServiceTest.java | 3 +- .../service/util/DocumentServiceUtilTest.java | 38 ++++-- 9 files changed, 138 insertions(+), 131 deletions(-) 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 8caa52c5db8..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,7 +56,6 @@ 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; @@ -80,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; @@ -91,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; @@ -99,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; @@ -144,7 +135,7 @@ public class DemographicService implements DemographicServiceIntf { private DocumentServiceIntf documentServiceImpl; @Autowired - private CommonServiceUtil commonServiceUtil; + CommonServiceUtil commonServiceUtil; /** * Autowired reference for {@link #AuditLogUtil} @@ -178,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 @@ -227,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; /** @@ -255,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. 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 index 3c81f55a913..e1429700094 100644 --- 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 @@ -16,6 +16,7 @@ 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; @@ -57,6 +58,7 @@ * @since 1.0.0 */ @Component +@RefreshScope public class CommonServiceUtil { /** * logger instance @@ -235,11 +237,9 @@ public List validMandatoryDocumentsForApplicant(DemographicEntity demogr Set mandatoryDocCat = demographicServiceUtil.getMandatoryDocCatogery(); log.info("mandatory Docs category --> {}", mandatoryDocCat); - List validMandatoryDocumentForApplicant = applicantValidDocuments.getDocumentCategories().stream() + return applicantValidDocuments.getDocumentCategories().stream() .filter(docCat -> mandatoryDocCat.contains(docCat.getCode())).map(docCat -> docCat.getCode()) .collect(Collectors.toList()); - - return validMandatoryDocumentForApplicant; } public MainResponseDTO updatePreRegistrationStatus(String preRegId, String status, String userId) { @@ -262,7 +262,6 @@ public MainResponseDTO updatePreRegistrationStatus(String preRegId, Stri 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); 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 ff1be7ea86b..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; @@ -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,24 +336,24 @@ 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"); @@ -397,7 +395,6 @@ private boolean compareUploadedDocListAndValidMandatoryDocList(List avai return false; } } - } @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED) 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