diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml index eb9583675b..069ca0539f 100644 --- a/.github/workflows/push_trigger.yml +++ b/.github/workflows/push_trigger.yml @@ -56,7 +56,7 @@ jobs: - name: Build with Maven run: | cd commons-packet - mvn -U -B package -DskipTests --file pom.xml -s $GITHUB_WORKSPACE/settings.xml + mvn -U -B package --file pom.xml -s $GITHUB_WORKSPACE/settings.xml - name: Ready the springboot artifacts run: find -name '*.jar' -executable -type f -exec zip release.zip {} + @@ -120,12 +120,12 @@ jobs: - name: Build with Maven run: | cd commons-packet - mvn -B package -DskipTests --file pom.xml -s $GITHUB_WORKSPACE/settings.xml + mvn -B package --file pom.xml -s $GITHUB_WORKSPACE/settings.xml - name: Publish the maven package run: | cd commons-packet - mvn -B deploy -DskipTests -DaltDeploymentRepository=ossrh::default::${{ secrets.OSSRH_SNAPSHOT_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml + mvn -B deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.OSSRH_SNAPSHOT_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml env: GITHUB_TOKEN: ${{secrets.RELEASE_TOKEN}} GPG_TTY: $(tty) @@ -137,7 +137,6 @@ jobs: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} # required if: failure() # Pick up events even if the job fails or is canceled. - docker-commons-packet-service: needs: build @@ -198,7 +197,7 @@ jobs: env: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} # required if: failure() # Pick up events even if the job fails or is canceled. - + sonar_analysis: runs-on: ubuntu-latest steps: @@ -222,23 +221,21 @@ jobs: key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - - name: Install xmllint - run: | - sudo apt-get update - sudo apt-get install libxml2-utils - - name: Setup the settings file for ossrh server run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml + - name: Build with Maven + run: | + cd commons-packet + mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml - name: Analyze with SonarCloud run: | cd commons-packet - mvn -B -Dgpg.skip -DskipTests verify sonar:sonar -Dsonar.projectKey=mosip_${{ github.event.repository.name }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }} + mvn -B -Dgpg.skip verify sonar:sonar -Dsonar.projectKey=mosip_${{ github.event.repository.name }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - + - uses: 8398a7/action-slack@v3 with: status: ${{ job.status }} diff --git a/commons-packet/commons-packet-manager/pom.xml b/commons-packet/commons-packet-manager/pom.xml index f7685333da..1234072f71 100644 --- a/commons-packet/commons-packet-manager/pom.xml +++ b/commons-packet/commons-packet-manager/pom.xml @@ -146,6 +146,11 @@ ${junit.version} test + + org.apache.commons + commons-collections4 + 4.4 + diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/audit/AuditLogEntry.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/audit/AuditLogEntry.java index 2a266135c2..b846060655 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/audit/AuditLogEntry.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/audit/AuditLogEntry.java @@ -30,7 +30,6 @@ public class AuditLogEntry { @Autowired @Lazy - @Qualifier("restTemplate") private RestTemplate restTemplate; @Autowired diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/constants/PacketManagerConstants.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/constants/PacketManagerConstants.java index ec2746a467..9d22232ff1 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/constants/PacketManagerConstants.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/constants/PacketManagerConstants.java @@ -86,6 +86,7 @@ public class PacketManagerConstants { public static final String VALUE = "value"; public static final String TYPE = "type"; public static final String FORMAT = "format"; + public static final String REFNUMBER = "refNumber"; public static final String IDSCHEMA_URL = "IDSCHEMA"; public static final String SCHEMA_JSON = "schemaJson"; diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/constants/PacketUtilityErrorCodes.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/constants/PacketUtilityErrorCodes.java index 30de54991f..586e69b0cb 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/constants/PacketUtilityErrorCodes.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/constants/PacketUtilityErrorCodes.java @@ -1,52 +1,53 @@ -package io.mosip.commons.packet.constants; - -public enum PacketUtilityErrorCodes { - - UNKNOWN_RESOURCE_EXCEPTION("KER-PUT-001", - "Unknown resource provided"), - FILE_NOT_FOUND_IN_DESTINATION("KER-PUT-002", "Unable to Find File in Destination Folder"), - PACKET_DECRYPTION_FAILURE_EXCEPTION("KER-PUT-003", "Packet decryption failed"), - API_NOT_ACCESSIBLE_EXCEPTION("KER-PUT-005", "API not accessible"), - SYS_IO_EXCEPTION("KER-PUT-004", "Unable to Find File in Destination Folder"), - GET_ALL_IDENTITY_EXCEPTION("KER-PUT-005", "Unable to fetch identity json from all sub packets"), - NO_AVAILABLE_PROVIDER("KER-PUT-006", "No available provider for given source and process"), - BIOMETRIC_FIELDNAME_NOT_FOUND("KER-PUT-007", "Biometric fieldname is not present inside packet"), - GET_ALL_METAINFO_EXCEPTION("KER-PUT-008", "Unable to fetch meta information from all sub packets"), - ZIP_PARSING_EXCEPTION("KER-PUT-009", "Unable to parse the zip"), - SIGNATURE_EXCEPTION("KER-PUT-010", "Failed to generate digital signature"), - DOCUMENT_EXCEPTION("KER-PUT-011", "Failed to get document"), - BIOMETRIC_EXCEPTION("KER-PUT-012", "Unable to get biometric"), - OS_ADAPTER_EXCEPTION("KER-PUT-013", "No Object store adapter found."), - PACKET_KEEPER_GET_ERROR("KER-PUT-014", "Packet keeper exception occured."), - PACKET_KEEPER_PUT_ERROR("KER-PUT-015", "Packet keeper exception occured."), - PACKET_KEEPER_GETMETA_ERROR("KER-PUT-016", "Packet keeper exception occured."), - PACKET_KEEPER_INTEGRITY_ERROR("KER-PUT-017", "Packet keeper exception occured."), - CRYPTO_EXCEPTION("KER-PUT-018", "No available crypto service exception."), - INTEGRITY_FAILURE("KER-PUT-019", "Packet Integrity check failed."), - PACKET_VALIDATION_FAILED("KER-PUT-020", "Packet Validation exception occured."), - TAGGING_FAILED("KER-PUT-021", "Failed to add tags."), - TAG_ALREADY_EXIST("KER-PUT-022", "Tag Already Exist."), - GET_TAG_EXCEPTION("KER-PUT-023","Failed to get tags"), - TAG_NOT_FOUND("KER-PUT-024", "Requested tag not present"), - SOURCE_NOT_PRESENT("KER-PUT-025", "Source not present in request."), - DELETE_TAGGING_FAILED("KER-PUT-026", "Failed to delete tags."); - - - - - private final String errorCode; - private final String errorMessage; - - private PacketUtilityErrorCodes(final String errorCode, final String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - public String getErrorCode() { - return errorCode; - } - - public String getErrorMessage() { - return errorMessage; - } -} +package io.mosip.commons.packet.constants; + +public enum PacketUtilityErrorCodes { + + UNKNOWN_RESOURCE_EXCEPTION("KER-PUT-001", + "Unknown resource provided"), + FILE_NOT_FOUND_IN_DESTINATION("KER-PUT-002", "Unable to Find File in Destination Folder"), + PACKET_DECRYPTION_FAILURE_EXCEPTION("KER-PUT-003", "Packet decryption failed"), + API_NOT_ACCESSIBLE_EXCEPTION("KER-PUT-005", "API not accessible"), + SYS_IO_EXCEPTION("KER-PUT-004", "Unable to Find File in Destination Folder"), + GET_ALL_IDENTITY_EXCEPTION("KER-PUT-005", "Unable to fetch identity json from all sub packets"), + NO_AVAILABLE_PROVIDER("KER-PUT-006", "No available provider for given source and process"), + BIOMETRIC_FIELDNAME_NOT_FOUND("KER-PUT-007", "Biometric fieldname is not present inside packet"), + GET_ALL_METAINFO_EXCEPTION("KER-PUT-008", "Unable to fetch meta information from all sub packets"), + ZIP_PARSING_EXCEPTION("KER-PUT-009", "Unable to parse the zip"), + SIGNATURE_EXCEPTION("KER-PUT-010", "Failed to generate digital signature"), + DOCUMENT_EXCEPTION("KER-PUT-011", "Failed to get document"), + BIOMETRIC_EXCEPTION("KER-PUT-012", "Unable to get biometric"), + OS_ADAPTER_EXCEPTION("KER-PUT-013", "No Object store adapter found."), + PACKET_KEEPER_GET_ERROR("KER-PUT-014", "Packet keeper exception occured."), + PACKET_KEEPER_PUT_ERROR("KER-PUT-015", "Packet keeper exception occured."), + PACKET_KEEPER_GETMETA_ERROR("KER-PUT-016", "Packet keeper exception occured."), + PACKET_KEEPER_INTEGRITY_ERROR("KER-PUT-017", "Packet keeper exception occured."), + CRYPTO_EXCEPTION("KER-PUT-018", "No available crypto service exception."), + INTEGRITY_FAILURE("KER-PUT-019", "Packet Integrity check failed."), + PACKET_VALIDATION_FAILED("KER-PUT-020", "Packet Validation exception occured."), + TAGGING_FAILED("KER-PUT-021", "Failed to add tags."), + TAG_ALREADY_EXIST("KER-PUT-022", "Tag Already Exist."), + GET_TAG_EXCEPTION("KER-PUT-023","Failed to get tags"), + TAG_NOT_FOUND("KER-PUT-024", "Requested tag not present"), + SOURCE_NOT_PRESENT("KER-PUT-025", "Invalid source or process."), + DELETE_TAGGING_FAILED("KER-PUT-026", "Failed to delete tags."), + OBJECT_DOESNOT_EXISTS("KER-PUT-027", "Object doesnot exists."),; + + + + + private final String errorCode; + private final String errorMessage; + + private PacketUtilityErrorCodes(final String errorCode, final String errorMessage) { + this.errorCode = errorCode; + this.errorMessage = errorMessage; + } + + public String getErrorCode() { + return errorCode; + } + + public String getErrorMessage() { + return errorMessage; + } +} diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/exception/ObjectDoesnotExistsException.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/exception/ObjectDoesnotExistsException.java new file mode 100644 index 0000000000..bb207eeb39 --- /dev/null +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/exception/ObjectDoesnotExistsException.java @@ -0,0 +1,26 @@ +package io.mosip.commons.packet.exception; + +import io.mosip.commons.packet.constants.PacketUtilityErrorCodes; +import io.mosip.kernel.core.exception.BaseUncheckedException; + +public class ObjectDoesnotExistsException extends BaseUncheckedException { + + public ObjectDoesnotExistsException() { + super(PacketUtilityErrorCodes.OBJECT_DOESNOT_EXISTS.getErrorCode(), + PacketUtilityErrorCodes.OBJECT_DOESNOT_EXISTS.getErrorMessage()); + } + + public ObjectDoesnotExistsException(String message) { + super(PacketUtilityErrorCodes.OBJECT_DOESNOT_EXISTS.getErrorCode(), + message); + } + + public ObjectDoesnotExistsException(Throwable e) { + super(PacketUtilityErrorCodes.OBJECT_DOESNOT_EXISTS.getErrorCode(), + PacketUtilityErrorCodes.OBJECT_DOESNOT_EXISTS.getErrorMessage(), e); + } + + public ObjectDoesnotExistsException(String errorMessage, Throwable t) { + super(PacketUtilityErrorCodes.OBJECT_DOESNOT_EXISTS.getErrorCode(), errorMessage, t); + } +} diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/OfflinePacketCryptoServiceImpl.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/OfflinePacketCryptoServiceImpl.java index 8ec3fdcd05..73e7a4b843 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/OfflinePacketCryptoServiceImpl.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/OfflinePacketCryptoServiceImpl.java @@ -60,29 +60,28 @@ public class OfflinePacketCryptoServiceImpl implements IPacketCryptoService { @Override public byte[] sign(byte[] packet) { TpmSignRequestDto signRequest = new TpmSignRequestDto(); - signRequest.setData(CryptoUtil.encodeBase64(packet)); - return CryptoUtil.decodeBase64(getTpmCryptoService().csSign(signRequest).getData()); + signRequest.setData(CryptoUtil.encodeToURLSafeBase64(packet)); + return CryptoUtil.decodeURLSafeBase64(getTpmCryptoService().csSign(signRequest).getData()); } @Override public byte[] encrypt(String refId, byte[] packet) { - String packetString = CryptoUtil.encodeBase64String(packet); + String packetString = CryptoUtil.encodeToURLSafeBase64(packet); CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); cryptomanagerRequestDto.setApplicationId(APPLICATION_ID); cryptomanagerRequestDto.setData(packetString); cryptomanagerRequestDto.setReferenceId(refId); - cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); SecureRandom sRandom = new SecureRandom(); byte[] nonce = new byte[CryptomanagerConstant.GCM_NONCE_LENGTH]; byte[] aad = new byte[CryptomanagerConstant.GCM_AAD_LENGTH]; sRandom.nextBytes(nonce); sRandom.nextBytes(aad); - cryptomanagerRequestDto.setAad(CryptoUtil.encodeBase64String(aad)); - cryptomanagerRequestDto.setSalt(CryptoUtil.encodeBase64String(nonce)); + cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); + cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); - byte[] encryptedData = CryptoUtil.decodeBase64(getCryptomanagerService().encrypt(cryptomanagerRequestDto).getData()); + byte[] encryptedData = CryptoUtil.decodeURLSafeBase64(getCryptomanagerService().encrypt(cryptomanagerRequestDto).getData()); return EncryptionUtil.mergeEncryptedData(encryptedData, nonce, aad); } @@ -97,20 +96,19 @@ public byte[] decrypt(String refId, byte[] packet) { CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); cryptomanagerRequestDto.setApplicationId(APPLICATION_ID); cryptomanagerRequestDto.setReferenceId(refId); - cryptomanagerRequestDto.setAad(CryptoUtil.encodeBase64String(aad)); - cryptomanagerRequestDto.setSalt(CryptoUtil.encodeBase64String(nonce)); - cryptomanagerRequestDto.setData(CryptoUtil.encodeBase64String(encryptedData)); - cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); + cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); + cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); + cryptomanagerRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(encryptedData)); cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); - return CryptoUtil.decodeBase64(getCryptomanagerService().decrypt(cryptomanagerRequestDto).getData()); + return CryptoUtil.decodeURLSafeBase64(getCryptomanagerService().decrypt(cryptomanagerRequestDto).getData()); } @Override public boolean verify(String machineId, byte[] packet, byte[] signature) { TpmSignVerifyRequestDto tpmSignVerifyRequestDto = new TpmSignVerifyRequestDto(); - tpmSignVerifyRequestDto.setData(CryptoUtil.encodeBase64(packet)); - tpmSignVerifyRequestDto.setSignature(CryptoUtil.encodeBase64(signature)); + tpmSignVerifyRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(packet)); + tpmSignVerifyRequestDto.setSignature(CryptoUtil.encodeToURLSafeBase64(signature)); //TODO - get public key based on machine Id //tpmSignVerifyRequestDto.setPublicKey(<>); TpmSignVerifyResponseDto tpmSignVerifyResponseDto = getTpmCryptoService().csVerify(tpmSignVerifyRequestDto); diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/OnlinePacketCryptoServiceImpl.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/OnlinePacketCryptoServiceImpl.java index 27c34dcf14..3e2556eb33 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/OnlinePacketCryptoServiceImpl.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/OnlinePacketCryptoServiceImpl.java @@ -65,7 +65,6 @@ public class OnlinePacketCryptoServiceImpl implements IPacketCryptoService { private boolean isPrependThumbprintEnabled; @Autowired - @Qualifier("restTemplate") private RestTemplate restTemplate; @Autowired @@ -88,7 +87,7 @@ public byte[] sign(byte[] packet) { try { TpmSignRequestDto dto = new TpmSignRequestDto(); - dto.setData(CryptoUtil.encodeBase64(packet)); + dto.setData(CryptoUtil.encodeToURLSafeBase64(packet)); RequestWrapper request = new RequestWrapper<>(); request.setRequest(dto); request.setMetadata(null); @@ -101,7 +100,7 @@ public byte[] sign(byte[] packet) { String.class); LinkedHashMap responseMap = (LinkedHashMap) mapper.readValue(response.getBody(), LinkedHashMap.class).get("response"); if (responseMap != null && responseMap.size() > 0) - return CryptoUtil.decodeBase64((String) responseMap.get("data")); + return CryptoUtil.decodeURLSafeBase64((String) responseMap.get("data")); else throw new SignatureException(); } catch (IOException e) { @@ -116,7 +115,7 @@ public byte[] encrypt(String refId, byte[] packet) { byte[] encryptedPacket = null; try { - String packetString = CryptoUtil.encodeBase64String(packet); + String packetString = CryptoUtil.encodeToURLSafeBase64(packet); CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); RequestWrapper request = new RequestWrapper<>(); cryptomanagerRequestDto.setApplicationId(APPLICATION_ID); @@ -129,8 +128,8 @@ public byte[] encrypt(String refId, byte[] packet) { byte[] aad = new byte[CryptomanagerConstant.GCM_AAD_LENGTH]; sRandom.nextBytes(nonce); sRandom.nextBytes(aad); - cryptomanagerRequestDto.setAad(CryptoUtil.encodeBase64String(aad)); - cryptomanagerRequestDto.setSalt(CryptoUtil.encodeBase64String(nonce)); + cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); + cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); request.setId(DECRYPT_SERVICE_ID); @@ -154,7 +153,7 @@ public byte[] encrypt(String refId, byte[] packet) { "Packet encryption failure message : " + error.getMessage()); throw new PacketDecryptionFailureException(error.getMessage()); } - byte[] encryptedData = CryptoUtil.decodeBase64(responseObject.getResponse().getData()); + byte[] encryptedData = CryptoUtil.decodeURLSafeBase64(responseObject.getResponse().getData()); encryptedPacket = EncryptionUtil.mergeEncryptedData(encryptedData, nonce, aad); LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, "Successfully encrypted Packet"); @@ -197,9 +196,9 @@ public byte[] decrypt(String refId, byte[] packet) { CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH); byte[] encryptedData = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH, packet.length); - cryptomanagerRequestDto.setAad(CryptoUtil.encodeBase64String(aad)); - cryptomanagerRequestDto.setSalt(CryptoUtil.encodeBase64String(nonce)); - cryptomanagerRequestDto.setData(CryptoUtil.encodeBase64String(encryptedData)); + cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); + cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); + cryptomanagerRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(encryptedData)); cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); @@ -226,7 +225,7 @@ public byte[] decrypt(String refId, byte[] packet) { "Error message : " + error.getMessage()); throw new PacketDecryptionFailureException(error.getMessage()); } - decryptedPacket = CryptoUtil.decodeBase64(responseObject.getResponse().getData()); + decryptedPacket = CryptoUtil.decodeURLSafeBase64(responseObject.getResponse().getData()); LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, "Successfully decrypted Packet"); } catch (IOException e) { @@ -257,11 +256,10 @@ public byte[] decrypt(String refId, byte[] packet) { @Override public boolean verify(String refId, byte[] packet, byte[] signature) { try { - String machineId = refId.split("_")[1]; - String publicKey=getPublicKey(machineId); + String publicKey=getPublicKey(refId); TpmSignVerifyRequestDto dto = new TpmSignVerifyRequestDto(); - dto.setData(CryptoUtil.encodeBase64(packet)); - dto.setSignature(CryptoUtil.encodeBase64(signature)); + dto.setData(CryptoUtil.encodeToURLSafeBase64(packet)); + dto.setSignature(CryptoUtil.encodeToURLSafeBase64(signature)); dto.setPublicKey(publicKey); RequestWrapper request = new RequestWrapper<>(); request.setRequest(dto); @@ -274,11 +272,15 @@ public boolean verify(String refId, byte[] packet, byte[] signature) { ResponseEntity response = restTemplate.exchange(keymanagerCsverifysignUrl, HttpMethod.POST, httpEntity, String.class); LinkedHashMap responseMap = (LinkedHashMap) mapper.readValue(response.getBody(), LinkedHashMap.class).get("response");//.get("signature"); - if (responseMap != null && responseMap.size() > 0) - return responseMap.get("verified") != null && responseMap.get("verified").toString().equalsIgnoreCase("true"); - else { - LOGGER.error(PacketManagerLogger.SESSIONID, "SIGNATURE", new String(signature), - "Failed to verify signature"); + if (responseMap != null && responseMap.size() > 0) { + boolean result = responseMap.get("verified") != null && responseMap.get("verified").toString().equalsIgnoreCase("true"); + if (!result) + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + "Signature verification Failed."); + return result; + } else { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + "Failed to verify signature. Received error response from keymanager verify API."); throw new SignatureException(); } } catch (IOException e) { @@ -292,15 +294,16 @@ public boolean verify(String refId, byte[] packet, byte[] signature) { } } - private String getPublicKey(String machineId) throws IOException { + private String getPublicKey(String refId) throws IOException { + String machineId = refId.split("_")[1]; ResponseEntity response = restTemplate.exchange(syncdataGetTpmKeyUrl+machineId, HttpMethod.GET, null, String.class); LinkedHashMap responseMap = (LinkedHashMap) mapper.readValue(response.getBody(), LinkedHashMap.class).get("response");//.get("signature"); if (responseMap != null && responseMap.size() > 0) - return (String) responseMap.get("signingPublicKey") ; + return (String) responseMap.get("signingPublicKey"); else { - LOGGER.error(PacketManagerLogger.SESSIONID, "PUBLIC_KEY", machineId, - "Failed to get public key"); + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + "Failed to get public key. Error Response : " + response.getBody()); throw new SignatureException(); } } diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/PacketReaderImpl.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/PacketReaderImpl.java index 1d3608ce95..b259ef9653 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/PacketReaderImpl.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/PacketReaderImpl.java @@ -5,6 +5,7 @@ import static io.mosip.commons.packet.constants.PacketManagerConstants.IDENTITY; import static io.mosip.commons.packet.constants.PacketManagerConstants.LABEL; import static io.mosip.commons.packet.constants.PacketManagerConstants.META_INFO_OPERATIONS_DATA; +import static io.mosip.commons.packet.constants.PacketManagerConstants.REFNUMBER; import static io.mosip.commons.packet.constants.PacketManagerConstants.TYPE; import static io.mosip.commons.packet.constants.PacketManagerConstants.VALUE; @@ -18,6 +19,7 @@ import java.util.List; import java.util.Map; +import io.mosip.commons.packet.facade.PacketReader; import io.mosip.kernel.biometrics.constant.BiometricType; import io.mosip.kernel.core.util.JsonUtils; import org.apache.commons.collections4.CollectionUtils; @@ -74,6 +76,9 @@ public class PacketReaderImpl implements IPacketReader { @Value("${mosip.commons.packetnames}") private String packetNames; + @Autowired + private PacketReader packetReader; + @Autowired private PacketKeeper packetKeeper; @@ -100,13 +105,13 @@ public class PacketReaderImpl implements IPacketReader { public boolean validatePacket(String id, String source, String process) { try { return packetValidator.validate(id, source, process); - } catch (BaseCheckedException | IOException | NoSuchAlgorithmException e) { + } catch (Exception e) { LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "Packet Validation exception : " + ExceptionUtils.getStackTrace(e)); if (e instanceof BaseCheckedException) throw new PacketValidationFailureException(((BaseCheckedException) e).getMessage(), e); else - throw new PacketValidationFailureException(((IOException) e).getMessage(), e); + throw new PacketValidationFailureException((e).getMessage(), e); } } @@ -158,10 +163,10 @@ else if (value != null && (value instanceof String)) ExceptionUtils.getStackTrace(e)); if (e instanceof BaseCheckedException) { BaseCheckedException ex = (BaseCheckedException) e; - throw new GetAllIdentityException(ex.getErrorCode(), ex.getMessage()); + throw new GetAllIdentityException(ex.getErrorCode(), ex.getErrorText()); } else if (e instanceof BaseUncheckedException) { BaseUncheckedException ex = (BaseUncheckedException) e; - throw new GetAllIdentityException(ex.getErrorCode(), ex.getMessage()); + throw new GetAllIdentityException(ex.getErrorCode(), ex.getErrorText()); } throw new GetAllIdentityException(e.getMessage()); } @@ -197,12 +202,10 @@ public Map getFields(String id, List fields, String sour public Document getDocument(String id, String documentName, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "getDocument :: for - " + documentName); - Map idobjectMap = getAll(id, source, process); - Double schemaVersion = idobjectMap.get(PacketManagerConstants.IDSCHEMA_VERSION) != null - ? Double.valueOf(idobjectMap.get(PacketManagerConstants.IDSCHEMA_VERSION).toString()) - : null; - String documentString = (String) idobjectMap.get(documentName); try { + String schemaVersionString = packetReader.getField(id, idSchemaUtils.getIdschemaVersionFromMappingJson(), source, process, false); + Double schemaVersion = schemaVersionString != null ? Double.valueOf(schemaVersionString) : null; + String documentString = packetReader.getField(id, documentName, source, process, false); if (documentString != null && schemaVersion != null) { JSONObject documentMap = new JSONObject(documentString); String packetName = idSchemaUtils.getSource(documentName, schemaVersion); @@ -213,13 +216,13 @@ public Document getDocument(String id, String documentName, String source, Strin Document document = new Document(); document.setDocument(IOUtils.toByteArray(documentStream)); document.setValue(value); - document.setType(documentMap.get(TYPE) != null ? documentMap.get(TYPE).toString() : null); - document.setFormat(documentMap.get(FORMAT) != null ? documentMap.get(FORMAT).toString() : null); + document.setType(documentMap.has(TYPE) ? documentMap.get(TYPE).toString() : null); + document.setFormat(documentMap.has(FORMAT) ? documentMap.get(FORMAT).toString() : null); + document.setRefNumber(documentMap.has(REFNUMBER) ? documentMap.get(REFNUMBER).toString() : null); return document; } } - } catch (IOException | ApiNotAccessibleException | PacketDecryptionFailureException | JSONException - | PacketKeeperException e) { + } catch (Exception e) { LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, ExceptionUtils.getStackTrace(e)); throw new GetDocumentException(e.getMessage()); @@ -236,8 +239,7 @@ public BiometricRecord getBiometric(String id, String biometricFieldName, List idobjectMap = getAll(id, source, process); - String bioString = (String) idobjectMap.get(biometricFieldName); + String bioString = packetReader.getField(id, biometricFieldName, source, process, false);//(String) idobjectMap.get(biometricFieldName); JSONObject biometricMap = null; if (bioString != null) biometricMap = new JSONObject(bioString); @@ -258,9 +260,9 @@ public BiometricRecord getBiometric(String id, String biometricFieldName, List metaMap = PacketManagerHelper.getMetaMap(packetInfo); metaMap = getAdapter().addObjectMetaData(PACKET_MANAGER_ACCOUNT, packet.getPacketInfo().getId(), packet.getPacketInfo().getSource(), packet.getPacketInfo().getProcess(), packet.getPacketInfo().getPacketName(), metaMap); diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/IdSchemaUtils.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/IdSchemaUtils.java index 181fea0f74..7f883ccc84 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/IdSchemaUtils.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/IdSchemaUtils.java @@ -10,10 +10,15 @@ import static io.mosip.commons.packet.constants.PacketManagerConstants.SCHEMA_JSON; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.ArrayUtils; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; @@ -37,7 +42,34 @@ @Component public class IdSchemaUtils { + private org.json.simple.JSONObject mappingJsonObject = null; + private static Map categorySubpacketMapping = new HashMap<>(); private Map idschema = null; + public static final String RESPONSE = "response"; + public static final String PROPERTIES = "properties"; + public static final String IDENTITY = "identity"; + public static final String SCHEMA_CATEGORY = "fieldCategory"; + public static final String SCHEMA_ID = "id"; + public static final String SCHEMA_TYPE = "type"; + public static final String SCHEMA_REF = "$ref"; + public static final String IDSCHEMA_URL = "IDSCHEMA"; + public static final String SCHEMA_JSON = "schemaJson"; + public static final String SCHEMA_VERSION_QUERY_PARAM = "schemaVersion"; + public static final String SCHEMA_REF_DEFINITIONS_PREFIX = "#/definitions/"; + + static { + categorySubpacketMapping.put("pvt", "id"); + categorySubpacketMapping.put("kyc", "id"); + categorySubpacketMapping.put("none", "id,evidence,optional"); + categorySubpacketMapping.put("evidence", "evidence"); + categorySubpacketMapping.put("optional", "optional"); + } + + @Value("${config.server.file.storage.uri}") + private String configServerUrl; + + @Value("${registration.processor.identityjson}") + private String mappingjsonFileName; @Value("${packet.default.source:REGISTRATION_CLIENT}") private String defaultSource; @@ -47,9 +79,11 @@ public class IdSchemaUtils { @Value("${IDSCHEMAURL:null}") private String idschemaUrl; + + @Autowired + private ObjectMapper objMapper; @Autowired - @Qualifier("restTemplate") private RestTemplate restTemplate; @@ -158,4 +192,83 @@ private JSONObject getJSONObjFromStr(String jsonString, String id) { return null; } } + + public List getDefaultFields(Double schemaVersion) throws JSONException, IOException { + List fieldList = new ArrayList<>(); + List> fieldMapList = loadDefaultFields(schemaVersion); + fieldMapList.stream().forEach(f -> fieldList.add(f.get(SCHEMA_ID))); + return fieldList; + } + + public List> loadDefaultFields(Double schemaVersion) throws JSONException, IOException { + Map>> packetBasedMap = new HashMap>>(); + + String schemaJson = getIdSchema(schemaVersion); + + JSONObject schema = getIdentityFieldsSchema(schemaJson); + + JSONArray fieldNames = schema.names(); + for(int i=0;i>()); + } + + Map attributes = new HashMap<>(); + attributes.put(SCHEMA_ID, fieldName); + attributes.put(SCHEMA_TYPE, fieldDetail.has(SCHEMA_REF) ? + fieldDetail.getString(SCHEMA_REF) : fieldDetail.getString(SCHEMA_TYPE)); + packetBasedMap.get(packetName).add(attributes); + } + } + return packetBasedMap.get("id"); + } + + private JSONObject getIdentityFieldsSchema(String schemaJson) throws JSONException { + + JSONObject schema = new JSONObject(schemaJson); + schema = schema.getJSONObject(PROPERTIES); + schema = schema.getJSONObject(IDENTITY); + schema = schema.getJSONObject(PROPERTIES); + + return schema; + } + + + public String getIdschemaVersionFromMappingJson() throws IOException { + String field = getJSONValue(getJSONObject(getMappingJson(), PacketManagerConstants.IDSCHEMA_VERSION), PacketManagerConstants.VALUE); + return field; + + } + + public org.json.simple.JSONObject getMappingJson() throws IOException { + + if (mappingJsonObject == null) { + String mappingJsonString = restTemplate.getForObject(configServerUrl + "/" + mappingjsonFileName, String.class); + mappingJsonObject = objMapper.readValue(mappingJsonString, org.json.simple.JSONObject.class); + + } + return getJSONObject(mappingJsonObject, PacketManagerConstants.IDENTITY); + } + + public static org.json.simple.JSONObject getJSONObject(org.json.simple.JSONObject jsonObject, Object key) { + if(jsonObject == null) + return null; + LinkedHashMap identity = (LinkedHashMap) jsonObject.get(key); + return identity != null ? new org.json.simple.JSONObject(identity) : null; + } + + public static T getJSONValue(org.json.simple.JSONObject jsonObject, String key) { + if(jsonObject == null) + return null; + T value = (T) jsonObject.get(key); + return value; + } } diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketValidator.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketValidator.java index cc6f61445f..4f6ab27351 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketValidator.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketValidator.java @@ -15,9 +15,12 @@ import java.util.List; import java.util.Map; -import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.commons.packet.facade.PacketReader; import io.mosip.kernel.core.util.HMACUtils2; import org.apache.commons.io.IOUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONTokener; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -58,6 +61,8 @@ public class PacketValidator { private static final String eventName = "PACKET MANAGER"; private static final String eventType = "SYSTEM"; + @Autowired + private PacketReader reader; @Autowired private Environment env; @@ -78,7 +83,7 @@ public class PacketValidator { private AuditLogEntry auditLogEntry; - public boolean validate(String id, String source, String process) throws IdObjectIOException, IdObjectValidationFailedException, InvalidIdSchemaException, IOException, JsonProcessingException, PacketKeeperException, NoSuchAlgorithmException { + public boolean validate(String id, String source, String process) throws IdObjectIOException, InvalidIdSchemaException, IOException, JsonProcessingException, PacketKeeperException, NoSuchAlgorithmException, JSONException { boolean result = validateSchema(id, source, process); if(result) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "Id object validation successful for process name : " + process); @@ -92,38 +97,28 @@ public boolean validate(String id, String source, String process) throws IdObjec return result; } - private boolean validateSchema(String id, String source, String process) throws IOException, InvalidIdSchemaException, IdObjectIOException { - LinkedHashMap objectMap = new LinkedHashMap<>(); + private boolean validateSchema(String id, String source, String process) throws IOException, InvalidIdSchemaException, IdObjectIOException, JSONException { + Map objectMap = new HashMap<>(); try { - for (String packetName : packetNames.split(",")) { - Packet packet = packetKeeper.getPacket(getPacketInfo(id, packetName, source, process)); - InputStream idJsonStream = ZipUtils.unzipAndGetFile(packet.getPacket(), "ID"); - if (idJsonStream != null) { - byte[] bytearray = IOUtils.toByteArray(idJsonStream); - String jsonString = new String(bytearray); - LinkedHashMap currentIdMap = (LinkedHashMap) mapper - .readValue(jsonString, LinkedHashMap.class).get(IDENTITY); - if (convertIdschemaToDouble && currentIdMap.get(IDSCHEMA_VERSION) != null) - currentIdMap.put(IDSCHEMA_VERSION, Double.valueOf(currentIdMap.get(IDSCHEMA_VERSION).toString())); - currentIdMap.entrySet().forEach(e -> objectMap.putIfAbsent(e.getKey(), e.getValue())); + String idschemaValueFromMappingJson = idSchemaUtils.getIdschemaVersionFromMappingJson(); + String idschemaVersion = reader.getField(id, idschemaValueFromMappingJson, source, process, false); + List allFields = idSchemaUtils.getDefaultFields(Double.valueOf(idschemaVersion)); + Map fieldsMap = reader.getFields(id, allFields, source, process, false); + objectMap.putAll(fieldsMap); + + if (convertIdschemaToDouble) + objectMap.put(idschemaValueFromMappingJson, Double.valueOf(fieldsMap.get(idschemaValueFromMappingJson))); - } - } String fields = env.getProperty(String.format(FIELD_LIST, IdObjectsSchemaValidationOperationMapper.getOperation(process))); LinkedHashMap finalMap = new LinkedHashMap(); - finalMap.put(IDENTITY, objectMap); + finalMap.put(IDENTITY, loadDemographicIdentity(objectMap)); JSONObject finalIdObject = new JSONObject(finalMap); return idObjectValidator.validateIdObject(idSchemaUtils.getIdSchema(Double.valueOf(objectMap.get( PacketManagerConstants.IDSCHEMA_VERSION).toString())), finalIdObject, Arrays.asList(fields.split(","))); - } catch (IdObjectValidationFailedException | PacketKeeperException e) { - if (e instanceof IdObjectValidationFailedException) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "Id object masterdata validation failed with errors: " + e.getErrorTexts()); - } else { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "Id object validation failed : " + ExceptionUtils.getStackTrace(e)); - } + } catch (IdObjectValidationFailedException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "Id object masterdata validation failed with errors: " + e.getErrorTexts()); return false; } @@ -296,5 +291,34 @@ private boolean checksumValidation(List hashseq1List, List hashseq2List, Map fieldMap) throws IOException, JSONException { + LinkedHashMap demographicIdentity = new LinkedHashMap(); + for (Map.Entry e : fieldMap.entrySet()) { + if (e.getValue() != null) { + String value = e.getValue().toString(); + if (value != null) { + Object json = new JSONTokener(value).nextValue(); + if (json instanceof org.json.JSONObject) { + HashMap hashMap = new ObjectMapper().readValue(value, HashMap.class); + demographicIdentity.putIfAbsent(e.getKey(), hashMap); + } + else if (json instanceof JSONArray) { + List jsonList = new ArrayList<>(); + JSONArray jsonArray = new JSONArray(value); + for (int i = 0; i < jsonArray.length(); i++) { + Object obj = jsonArray.get(i); + HashMap hashMap = new ObjectMapper().readValue(obj.toString(), HashMap.class); + jsonList.add(hashMap); + } + demographicIdentity.putIfAbsent(e.getKey(), jsonList); + } else + demographicIdentity.putIfAbsent(e.getKey(), e.getValue()); + } else + demographicIdentity.putIfAbsent(e.getKey(), value); + } + } + return demographicIdentity; + } + } diff --git a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/facade/PacketReaderTest.java b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/facade/PacketReaderTest.java index 4569603f50..4389440049 100644 --- a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/facade/PacketReaderTest.java +++ b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/facade/PacketReaderTest.java @@ -1,240 +1,239 @@ -package io.mosip.commons.packet.test.facade; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyString; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import com.google.common.collect.Lists; - -import io.mosip.commons.khazana.dto.ObjectDto; -import io.mosip.commons.packet.dto.Document; -import io.mosip.commons.packet.exception.NoAvailableProviderException; -import io.mosip.commons.packet.facade.PacketReader; -import io.mosip.commons.packet.impl.PacketReaderImpl; -import io.mosip.commons.packet.keeper.PacketKeeper; -import io.mosip.commons.packet.spi.IPacketReader; -import io.mosip.commons.packet.util.PacketHelper; -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.constant.QualityType; -import io.mosip.kernel.biometrics.entities.BDBInfo; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.entities.RegistryIDType; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({PacketHelper.class}) -@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) -public class PacketReaderTest { - - @InjectMocks - private PacketReader packetReader = new PacketReader(); - - @Mock - private PacketReaderImpl packetReaderProvider; - - private Map allFields; - - private static final String source = "reg-client"; - private static final String process = "NEW"; - private static final String id = "110111101120191111121111"; - - @Mock - private PacketKeeper packetKeeper; - - @Before - public void setup() { - PowerMockito.mockStatic(PacketHelper.class); - PowerMockito.when(PacketHelper.isSourceAndProcessPresent(anyString(),anyString(),anyString(),any())).thenReturn(true); - List referenceReaderProviders = new ArrayList<>(); - referenceReaderProviders.add(packetReaderProvider); - ReflectionTestUtils.setField(packetReader, "referenceReaderProviders", referenceReaderProviders); - allFields = new HashMap<>(); - allFields.put("name", "mono"); - allFields.put("email", "mono@mono.com"); - allFields.put("phone", "1234567"); - - Mockito.when(packetReaderProvider.getAll(anyString(), anyString(), anyString())).thenReturn(allFields); - - } - - @Test - public void testGetFieldWithBypassCache() { - String field = "name"; - Mockito.when(packetReaderProvider.getField(anyString(), anyString(), anyString(), anyString())).thenReturn(field); - - String result = packetReader.getField(id, field, source, process, true); - - assertTrue(result == field); - } - - @Test - public void testGetField() { - String field = "name"; - - String result = packetReader.getField(id, field, source, process, false); - - assertTrue(result.equals(allFields.get("name"))); - } - - @Test - public void testGetFields() { - String field = "name"; - List fieldList = Lists.newArrayList(field); - Map fieldMap = new HashMap<>(); - fieldMap.put(field, field); - Mockito.when(packetReaderProvider.getFields(anyString(), anyList(), anyString(), anyString())).thenReturn(fieldMap); - - Map result = packetReader.getFields(id, fieldList, source, process, true); - - assertTrue(result.size() == 1); - } - - @Test - public void testGetFieldsBypassCache() { - String field = "name"; - List fieldList = Lists.newArrayList(field); - Map fieldMap = new HashMap<>(); - fieldMap.put(field, field); - Mockito.when(packetReaderProvider.getFields(anyString(), anyList(), anyString(), anyString())).thenReturn(fieldMap); - - Map result = packetReader.getFields(id, fieldList, source, process, false); - - assertTrue(result.size() == 1); - } - - @Test - public void testGetDocument() { - String docName = "poa"; - Document document = new Document(); - document.setValue("document"); - - Mockito.when(packetReaderProvider.getDocument(anyString(), anyString(), anyString(), anyString())).thenReturn(document); - - Document result = packetReader.getDocument(id, docName, source, process); - - assertTrue(result.equals(document)); - } - - @Test - public void testGetBiometrics() { - List birTypeList = new ArrayList<>(); - BIR birType1 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); - RegistryIDType registryIDType = new RegistryIDType("Mosip", "257"); - QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - BiometricType singleType1 = BiometricType.FINGER; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); - bdbInfoType1.setSubtype(subtype1); - bdbInfoType1.setType(singleTypeList1); - birType1.setBdbInfo(bdbInfoType1); - birTypeList.add(birType1); - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - - Mockito.when(packetReaderProvider.getBiometric(anyString(), anyString(), anyList(), anyString(), anyString())).thenReturn(biometricRecord); - - BiometricRecord result = packetReader.getBiometric(id, "individualBiometrics", Lists.newArrayList(), source, process, true); - - assertTrue(result.equals(biometricRecord)); - } - - @Test - public void testGetMetaInfo() { - Map metaMap = new HashMap<>(); - metaMap.put("operationsData","officerid:1234"); - - Mockito.when(packetReaderProvider.getMetaInfo(anyString(), anyString(), anyString())).thenReturn(metaMap); - - Map result = packetReader.getMetaInfo(id, source, process, true); - - assertTrue(result.equals(metaMap)); - } - - @Test - public void testGetAudits() { - Map auditMap = new HashMap<>(); - auditMap.put("audit","audit1"); - List> auditList = new ArrayList<>(); - auditList.add(auditMap); - - Mockito.when(packetReaderProvider.getAuditInfo(anyString(), anyString(), anyString())).thenReturn(auditList); - - List> result = packetReader.getAudits(id, source, process, true); - - assertTrue(result.equals(auditList)); - } - - @Test - public void testValidatePacket() { - Map auditMap = new HashMap<>(); - auditMap.put("audit","audit1"); - List> auditList = new ArrayList<>(); - auditList.add(auditMap); - - Mockito.when(packetReaderProvider.validatePacket(anyString(), anyString(), anyString())).thenReturn(true); - - boolean result = packetReader.validatePacket(id, source, process); - - assertTrue(result); - } - - @Test(expected = NoAvailableProviderException.class) - public void testProviderException() { - PowerMockito.when(PacketHelper.isSourceAndProcessPresent(anyString(),anyString(),anyString(),any())).thenReturn(false); - - packetReader.validatePacket(id, source, process); - } - - @Test - public void testGetTags() { - Map tags = new HashMap<>(); - tags.put("test", "testValue"); - - Mockito.when(packetKeeper.getTags(any())).thenReturn(tags); - - Map expectedTags= packetReader.getTags("id"); - - assertEquals(expectedTags,tags); - } - - @Test - public void testInfo() { - ObjectDto objectDto = new ObjectDto("source1", "process1", "object1", new Date()); - ObjectDto objectDto2 = new ObjectDto("source2", "process2", "object2", new Date()); - ObjectDto objectDto3 = new ObjectDto("source3", "process3", "object3", new Date()); - List objectDtos = Lists.newArrayList(objectDto, objectDto2, objectDto3); - - - Mockito.when(packetKeeper.getAll(any())).thenReturn(objectDtos); - - List result = packetReader.info("id"); - - assertEquals(objectDtos.size(), result.size()); - } -} +package io.mosip.commons.packet.test.facade; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.assertj.core.util.Lists; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import io.mosip.commons.khazana.dto.ObjectDto; +import io.mosip.commons.packet.dto.Document; +import io.mosip.commons.packet.exception.NoAvailableProviderException; +import io.mosip.commons.packet.facade.PacketReader; +import io.mosip.commons.packet.impl.PacketReaderImpl; +import io.mosip.commons.packet.keeper.PacketKeeper; +import io.mosip.commons.packet.spi.IPacketReader; +import io.mosip.commons.packet.util.PacketHelper; +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.constant.QualityType; +import io.mosip.kernel.biometrics.entities.BDBInfo; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.entities.RegistryIDType; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({PacketHelper.class}) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +public class PacketReaderTest { + + @InjectMocks + private PacketReader packetReader = new PacketReader(); + + @Mock + private PacketReaderImpl packetReaderProvider; + + private Map allFields; + + private static final String source = "reg-client"; + private static final String process = "NEW"; + private static final String id = "110111101120191111121111"; + + @Mock + private PacketKeeper packetKeeper; + + @Before + public void setup() { + PowerMockito.mockStatic(PacketHelper.class); + PowerMockito.when(PacketHelper.isSourceAndProcessPresent(anyString(),anyString(),anyString(),any())).thenReturn(true); + List referenceReaderProviders = new ArrayList<>(); + referenceReaderProviders.add(packetReaderProvider); + ReflectionTestUtils.setField(packetReader, "referenceReaderProviders", referenceReaderProviders); + allFields = new HashMap<>(); + allFields.put("name", "mono"); + allFields.put("email", "mono@mono.com"); + allFields.put("phone", "1234567"); + + Mockito.when(packetReaderProvider.getAll(anyString(), anyString(), anyString())).thenReturn(allFields); + + } + + @Test + public void testGetFieldWithBypassCache() { + String field = "name"; + Mockito.when(packetReaderProvider.getField(anyString(), anyString(), anyString(), anyString())).thenReturn(field); + + String result = packetReader.getField(id, field, source, process, true); + + assertTrue(result == field); + } + + @Test + public void testGetField() { + String field = "name"; + + String result = packetReader.getField(id, field, source, process, false); + + assertTrue(result.equals(allFields.get("name"))); + } + + @Test + public void testGetFields() { + String field = "name"; + List fieldList = Lists.newArrayList(field); + Map fieldMap = new HashMap<>(); + fieldMap.put(field, field); + Mockito.when(packetReaderProvider.getFields(anyString(), anyList(), anyString(), anyString())).thenReturn(fieldMap); + + Map result = packetReader.getFields(id, fieldList, source, process, true); + + assertTrue(result.size() == 1); + } + + @Test + public void testGetFieldsBypassCache() { + String field = "name"; + List fieldList = Lists.newArrayList(field); + Map fieldMap = new HashMap<>(); + fieldMap.put(field, field); + Mockito.when(packetReaderProvider.getFields(anyString(), anyList(), anyString(), anyString())).thenReturn(fieldMap); + + Map result = packetReader.getFields(id, fieldList, source, process, false); + + assertTrue(result.size() == 1); + } + + @Test + public void testGetDocument() { + String docName = "poa"; + Document document = new Document(); + document.setValue("document"); + + Mockito.when(packetReaderProvider.getDocument(anyString(), anyString(), anyString(), anyString())).thenReturn(document); + + Document result = packetReader.getDocument(id, docName, source, process); + + assertTrue(result.equals(document)); + } + + @Test + public void testGetBiometrics() { + List birTypeList = new ArrayList<>(); + BIR birType1 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); + RegistryIDType registryIDType = new RegistryIDType("Mosip", "257"); + QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + BiometricType singleType1 = BiometricType.FINGER; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); + bdbInfoType1.setSubtype(subtype1); + bdbInfoType1.setType(singleTypeList1); + birType1.setBdbInfo(bdbInfoType1); + birTypeList.add(birType1); + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + + Mockito.when(packetReaderProvider.getBiometric(anyString(), anyString(), anyList(), anyString(), anyString())).thenReturn(biometricRecord); + + BiometricRecord result = packetReader.getBiometric(id, "individualBiometrics", Lists.newArrayList(), source, process, true); + + assertTrue(result.equals(biometricRecord)); + } + + @Test + public void testGetMetaInfo() { + Map metaMap = new HashMap<>(); + metaMap.put("operationsData","officerid:1234"); + + Mockito.when(packetReaderProvider.getMetaInfo(anyString(), anyString(), anyString())).thenReturn(metaMap); + + Map result = packetReader.getMetaInfo(id, source, process, true); + + assertTrue(result.equals(metaMap)); + } + + @Test + public void testGetAudits() { + Map auditMap = new HashMap<>(); + auditMap.put("audit","audit1"); + List> auditList = new ArrayList<>(); + auditList.add(auditMap); + + Mockito.when(packetReaderProvider.getAuditInfo(anyString(), anyString(), anyString())).thenReturn(auditList); + + List> result = packetReader.getAudits(id, source, process, true); + + assertTrue(result.equals(auditList)); + } + + @Test + public void testValidatePacket() { + Map auditMap = new HashMap<>(); + auditMap.put("audit","audit1"); + List> auditList = new ArrayList<>(); + auditList.add(auditMap); + + Mockito.when(packetReaderProvider.validatePacket(anyString(), anyString(), anyString())).thenReturn(true); + + boolean result = packetReader.validatePacket(id, source, process); + + assertTrue(result); + } + + @Test(expected = NoAvailableProviderException.class) + public void testProviderException() { + PowerMockito.when(PacketHelper.isSourceAndProcessPresent(anyString(),anyString(),anyString(),any())).thenReturn(false); + + packetReader.validatePacket(id, source, process); + } + + @Test + public void testGetTags() { + Map tags = new HashMap<>(); + tags.put("test", "testValue"); + + Mockito.when(packetKeeper.getTags(any())).thenReturn(tags); + + Map expectedTags= packetReader.getTags("id"); + + assertEquals(expectedTags,tags); + } + + @Test + public void testInfo() { + ObjectDto objectDto = new ObjectDto("source1", "process1", "object1", new Date()); + ObjectDto objectDto2 = new ObjectDto("source2", "process2", "object2", new Date()); + ObjectDto objectDto3 = new ObjectDto("source3", "process3", "object3", new Date()); + List objectDtos = Lists.newArrayList(objectDto, objectDto2, objectDto3); + + + Mockito.when(packetKeeper.getAll(any())).thenReturn(objectDtos); + + List result = packetReader.info("id"); + + assertEquals(objectDtos.size(), result.size()); + } +} diff --git a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/OfflinePacketCryptoServiceTest.java b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/OfflinePacketCryptoServiceTest.java index 16d603d898..490516b5e1 100644 --- a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/OfflinePacketCryptoServiceTest.java +++ b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/OfflinePacketCryptoServiceTest.java @@ -69,7 +69,7 @@ public void setup() { public void signTest() { String packetSignature = "signature"; TpmSignResponseDto signatureResponse = new TpmSignResponseDto(); - signatureResponse.setData(CryptoUtil.encodeBase64(packetSignature.getBytes(StandardCharsets.UTF_8))); + signatureResponse.setData(CryptoUtil.encodeToURLSafeBase64(packetSignature.getBytes(StandardCharsets.UTF_8))); Mockito.when(clientCryptoManagerService.csSign(any())).thenReturn(signatureResponse); diff --git a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/OnlinePacketCryptoServiceTest.java b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/OnlinePacketCryptoServiceTest.java index a058e35a50..09207027ad 100644 --- a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/OnlinePacketCryptoServiceTest.java +++ b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/OnlinePacketCryptoServiceTest.java @@ -63,9 +63,7 @@ public class OnlinePacketCryptoServiceTest { public void setup() { ReflectionTestUtils.setField(onlinePacketCryptoService, "DATETIME_PATTERN", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); ReflectionTestUtils.setField(onlinePacketCryptoService, "APPLICATION_VERSION", "v1"); - //ReflectionTestUtils.setField(onlinePacketCryptoService, "centerIdLength", 5); ReflectionTestUtils.setField(onlinePacketCryptoService, "cryptomanagerDecryptUrl", "http://localhost"); - //ReflectionTestUtils.setField(onlinePacketCryptoService, "machineIdLength", 5); ReflectionTestUtils.setField(onlinePacketCryptoService, "cryptomanagerEncryptUrl", "http://localhost"); ReflectionTestUtils.setField(onlinePacketCryptoService, "DATETIME_PATTERN", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); @@ -75,7 +73,7 @@ public void setup() { public void signTest() throws IOException { String expected = "signature"; LinkedHashMap submap = new LinkedHashMap(); - submap.put("data", CryptoUtil.encodeBase64(expected.getBytes(StandardCharsets.UTF_8))); + submap.put("data", CryptoUtil.encodeToURLSafeBase64(expected.getBytes(StandardCharsets.UTF_8))); LinkedHashMap responseMap = new LinkedHashMap(); responseMap.put("response", submap); ReflectionTestUtils.setField(onlinePacketCryptoService, "keymanagerCsSignUrl", "localhost"); @@ -127,7 +125,7 @@ public void encryptTest() throws IOException { @Test(expected = PacketDecryptionFailureException.class) public void encryptExceptionTest() throws IOException { String expected = "signature"; - byte[] packet = "packetpacketpacketpacket".getBytes(); + byte[] packet = "packet".getBytes(); ReflectionTestUtils.setField(onlinePacketCryptoService, "cryptomanagerEncryptUrl", "localhost"); @@ -142,7 +140,7 @@ public void decryptTest() throws IOException { byte[] packet = "10001100770000320200720092256_packetwithsignatureandaad".getBytes(); CryptomanagerResponseDto cryptomanagerResponseDto = new CryptomanagerResponseDto(); cryptomanagerResponseDto.setErrors(null); - DecryptResponseDto decryptResponseDto = new DecryptResponseDto(CryptoUtil.encodeBase64("packet".getBytes())); + DecryptResponseDto decryptResponseDto = new DecryptResponseDto(CryptoUtil.encodeToURLSafeBase64("packet".getBytes())); cryptomanagerResponseDto.setResponse(decryptResponseDto); @@ -159,7 +157,7 @@ public void decryptTest() throws IOException { @Test(expected = PacketDecryptionFailureException.class) public void decryptExceptionTest() throws IOException { String expected = "signature"; - byte[] packet = "10001100770000320200720092256_packetwithsignatureandaad".getBytes(); + byte[] packet = "packet".getBytes(); ReflectionTestUtils.setField(onlinePacketCryptoService, "cryptomanagerDecryptUrl", "localhost"); @@ -172,7 +170,7 @@ public void decryptExceptionTest() throws IOException { @Test public void verifyTest() throws IOException { String expected = "signature"; - byte[] packet = "packetpacketpacketpacket".getBytes(); + byte[] packet = "packet".getBytes(); LinkedHashMap submap = new LinkedHashMap(); submap.put("verified", true); diff --git a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/PacketReaderImplTest.java b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/PacketReaderImplTest.java index 045b8d6945..160ccfd62f 100644 --- a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/PacketReaderImplTest.java +++ b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/impl/PacketReaderImplTest.java @@ -1,437 +1,450 @@ -package io.mosip.commons.packet.test.impl; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyObject; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.io.IOUtils; -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.context.annotation.PropertySource; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.Lists; - -import io.mosip.commons.packet.dto.Document; -import io.mosip.commons.packet.dto.Packet; -import io.mosip.commons.packet.exception.GetAllIdentityException; -import io.mosip.commons.packet.exception.GetAllMetaInfoException; -import io.mosip.commons.packet.exception.GetDocumentException; -import io.mosip.commons.packet.exception.PacketKeeperException; -import io.mosip.commons.packet.exception.PacketValidationFailureException; -import io.mosip.commons.packet.impl.PacketReaderImpl; -import io.mosip.commons.packet.keeper.PacketKeeper; -import io.mosip.commons.packet.spi.IPacketReader; -import io.mosip.commons.packet.util.IdSchemaUtils; -import io.mosip.commons.packet.util.PacketValidator; -import io.mosip.commons.packet.util.ZipUtils; -import io.mosip.kernel.biometrics.commons.CbeffValidator; -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.constant.QualityType; -import io.mosip.kernel.biometrics.entities.BDBInfo; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.entities.RegistryIDType; -import io.mosip.kernel.core.idobjectvalidator.exception.IdObjectIOException; -import io.mosip.kernel.core.idobjectvalidator.exception.IdObjectValidationFailedException; -import io.mosip.kernel.core.idobjectvalidator.exception.InvalidIdSchemaException; -import io.mosip.kernel.core.util.JsonUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ZipUtils.class, IOUtils.class, JsonUtils.class, CbeffValidator.class}) -@PropertySource("classpath:application-test.properties") -@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) -public class PacketReaderImplTest { - - @InjectMocks - private IPacketReader iPacketReader = new PacketReaderImpl(); - - @Mock - private PacketValidator packetValidator; - - @Mock - private PacketKeeper packetKeeper; - - @Mock - private ObjectMapper objectMapper; - - @Mock - private IdSchemaUtils idSchemaUtils; - - private static final String docName = "proofOfIdentity"; - private static final String biometricFieldName = "individualBiometrics"; - - @Before - public void setup() throws PacketKeeperException, IOException { - Packet packet = new Packet(); - packet.setPacket("hello".getBytes()); - - String str = "{ \"identity\" : {\n" + - " \"proofOfAddress\" : {\n" + - " \"value\" : \"proofOfAddress\",\n" + - " \"type\" : \"DOC004\",\n" + - " \"format\" : \"jpg\"\n" + - " },\n" + - " \"gender\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"Male\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"الذكر\"\n" + - " } ],\n" + - " \"city\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"Kenitra\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"القنيطرة\"\n" + - " } ],\n" + - " \"postalCode\" : \"14000\",\n" + - " \"fullName\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"Test after fix\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"Test after fix\"\n" + - " } ],\n" + - " \"dateOfBirth\" : \"1976/01/01\",\n" + - " \"referenceIdentityNumber\" : \"2345235252352353523\",\n" + - " \"individualBiometrics\" : {\n" + - " \"format\" : \"cbeff\",\n" + - " \"version\" : 1.0,\n" + - " \"value\" : \"individualBiometrics_bio_CBEFF\"\n" + - " },\n" + - " \"IDSchemaVersion\" : \"0.1\",\n" + - " \"province\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"Kenitra\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"القنيطرة\"\n" + - " } ],\n" + - " \"zone\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"Assam\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"العصام\"\n" + - " } ],\n" + - " \"phone\" : \"9606139887\",\n" + - " \"addressLine1\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"asdadsfas\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"asdadsfas\"\n" + - " } ],\n" + - " \"addressLine2\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"qqwqrqwrw\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"qqwqrqwrw\"\n" + - " } ],\n" + - " \"residenceStatus\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"Non-Foreigner\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"غير أجنبي\"\n" + - " } ],\n" + - " \"addressLine3\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"wfwfwef\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"wfwfwef\"\n" + - " } ],\n" + - " \"region\" : [ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \"Rabat Sale Kenitra\"\n" + - " }, {\n" + - " \"language\" : \"ara\",\n" + - " \"value\" : \"جهة الرباط سلا القنيطرة\"\n" + - " } ],\n" + - " \"email\" : \"niyati.swami@technoforte.co.in\"\n" + - "} } "; - - Map keyValueMap = new LinkedHashMap<>(); - keyValueMap.put("email", "niyati.swami@technoforte.co.in"); - keyValueMap.put("phone", "9606139887"); - keyValueMap.put("fullName", "[ {\r\n \"language\" : \"eng\",\r\n \"value\" : \"Test after fix\"\r\n}, {\r\n \"language\" : \"ara\",\r\n \"value\" : \"Test after fix\"\r\n} ]"); - keyValueMap.put("IDSchemaVersion", "0.1"); - keyValueMap.put(biometricFieldName, "{\r\n \"format\" : \"cbeff\",\r\n \"version\" : 1.0,\r\n \"value\" : \"individualBiometrics_bio_CBEFF\"\r\n}"); - keyValueMap.put(docName, "{\r\n \"value\" : \"proofOfIdentity\",\r\n \"type\" : \"DOC003\",\r\n \"format\" : \"jpg\"\r\n}"); - - - Map finalMap = new LinkedHashMap<>(); - finalMap.put("identity", keyValueMap); - - ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes()); - - MockitoAnnotations.initMocks(this); - ReflectionTestUtils.setField(iPacketReader, "packetNames", "id,evidence,optional"); - when(packetKeeper.getPacket(any())).thenReturn(packet); - - PowerMockito.mockStatic(ZipUtils.class); - when(ZipUtils.unzipAndGetFile(any(), anyString())).thenReturn(bis); - PowerMockito.mockStatic(IOUtils.class); - when(IOUtils.toByteArray(any(InputStream.class))).thenReturn(str.getBytes()); - - when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); - when(idSchemaUtils.getSource(any(), any())).thenReturn("id"); - - } - - @Test - public void validatePacketTest() throws JsonProcessingException, PacketKeeperException, InvalidIdSchemaException, IdObjectValidationFailedException, IdObjectIOException, IOException, NoSuchAlgorithmException { - when(packetValidator.validate(anyString(), anyString(), anyString())).thenReturn(true); - boolean result = iPacketReader.validatePacket("id", "source", "process"); - - assertTrue("Should be true", result); - } - - @Test(expected = PacketValidationFailureException.class) - public void validatePacketExceptionTest() throws JsonProcessingException, PacketKeeperException, InvalidIdSchemaException, IdObjectValidationFailedException, IdObjectIOException, IOException, NoSuchAlgorithmException { - when(packetValidator.validate(anyString(), anyString(), anyString())).thenThrow(new IOException("exception")); - boolean result = iPacketReader.validatePacket("id", "source","process"); - - } - - @Test - public void getAllTest() { - Map result = iPacketReader.getAll("id", "source", "process"); - - assertTrue("Should be true", result.size() == 6); - } - - @Test(expected = GetAllIdentityException.class) - public void getAllExceptionTest() throws IOException { - when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(null); - - Map result = iPacketReader.getAll("id", "source", "process"); - } - - @Test(expected = GetAllIdentityException.class) - public void getAllExceptionTest2() throws JsonProcessingException, IOException { - PowerMockito.mockStatic(JsonUtils.class); - Map keyValueMap = new LinkedHashMap<>(); - keyValueMap.put("email", new JSONObject(new LinkedHashMap())); - Map finalMap = new LinkedHashMap<>(); - finalMap.put("identity", keyValueMap); - when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); - - when(JsonUtils.javaObjectToJsonString(anyObject())).thenThrow(new JsonProcessingException("errormessage")); - Map result = iPacketReader.getAll("id", "source", "process"); - } - - @Test - public void getFieldTest() { - String result = iPacketReader.getField("id", "phone", "source","process"); - - assertTrue("Should be true", result.equals("9606139887")); - } - - @Test - public void getFieldsTest() { - List list = Lists.newArrayList("phone", "email"); - - Map result = iPacketReader.getFields("id", list, "source", "process"); - - assertTrue("Should be true", result.size() == 2); - } - - @Test - public void getDocumentTest() { - List list = Lists.newArrayList("phone", "email"); - - Document result = iPacketReader.getDocument("id", docName, "source", "process"); - - assertTrue("Should be true", result.getDocument() != null); - } - - @Test(expected = GetDocumentException.class) - public void getDocumentExceptionTest() throws IOException { - List list = Lists.newArrayList("phone", "email"); - - when(idSchemaUtils.getSource(any(), any())).thenThrow(new IOException("exception")); - - Document result = iPacketReader.getDocument("id", docName, "source", "process"); - - } - - @Test - public void getBiometricsTest() throws Exception { - BIR birType = new BIR(); - BIR bir1 = new BIR(); - BDBInfo bdbInfoType1 = new BDBInfo(); - RegistryIDType registryIDType = new RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - BiometricType singleType1 = BiometricType .FINGER; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); - bdbInfoType1.setSubtype(subtype1); - bdbInfoType1.setType(singleTypeList1); - bdbInfoType1.setFormat(registryIDType); - bir1.setBdbInfo(bdbInfoType1); - BIR bir2 = new BIR(); - bir2.setBdbInfo(bdbInfoType1); - - PowerMockito.mockStatic(CbeffValidator.class); - birType.setBirs(Lists.newArrayList(bir1, bir2)); - when(CbeffValidator.getBIRFromXML(any())).thenReturn(birType); - - BiometricRecord result = iPacketReader.getBiometric("id", biometricFieldName, null, "source", "process"); - - assertTrue("Should be true", result.getSegments().size() == 2); - } - - @Test - @Ignore - public void getBiometricsExceptionTest() throws Exception { - List list = Lists.newArrayList("phone", "email"); - BIR birType = new BIR(); - - BIR bir1 = new BIR(); - BDBInfo bdbInfoType1 = new BDBInfo(); - RegistryIDType registryIDType = new RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - BiometricType singleType1 = BiometricType.FINGER; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); - bdbInfoType1.setSubtype(subtype1); - bdbInfoType1.setType(singleTypeList1); - bdbInfoType1.setFormat(registryIDType); - bir1.setBdbInfo(bdbInfoType1); - BIR bir2 = new BIR(); - bir2.setBdbInfo(bdbInfoType1); - birType.setBirs(Lists.newArrayList(bir1, bir2)); - - Map keyValueMap = new LinkedHashMap<>(); - keyValueMap.put("operationsData", "[{\n \"label\\\" : \\\"officerId\\\",\n \\\"value\\\" : \\\"110012\\\"\n}, {\n \\\"label\\\" : \\\"officerBiometricFileName\\\",\n \\\"value\\\" : \\\"officer_bio_cbeff\\\"\n}, {\n \\\"label\\\" : \\\"supervisorId\\\",\n \\\"value\\\" : null\n}, {\n \\\"label\\\" : \\\"supervisorBiometricFileName\\\",\n \\\"value\\\" : null\n}, {\n \\\"label\\\" : \\\"supervisorPassword\\\",\n \\\"value\\\" : \\\"false\\\"\n}, {\n \\\"label\\\" : \\\"officerPassword\\\",\n \\\"value\\\" : \\\"true\\\"\n}, {\n \\\"label\\\" : \\\"supervisorPIN\\\",\n \\\"value\\\" : null\n}, {\n \\\"label\\\" : \\\"officerPIN\\\",\n \\\"value\\\" : null\n}]"); - keyValueMap.put("metaData", "[{\r\n \"label\" : \"registrationId\",\r\n \"value\" : \"10001100770000320200720092256\"\r\n}, {\r\n \"label\" : \"creationDate\",\r\n \"value\" : \"2020-07-20T14:54:49.823Z\"\r\n}, {\r\n \"label\" : \"Registration Client Version Number\",\r\n \"value\" : \"1.0.10\"\r\n}, {\r\n \"label\" : \"registrationType\",\r\n \"value\" : \"New\"\r\n}, {\r\n \"label\" : \"preRegistrationId\",\r\n \"value\" : null\r\n}, {\r\n \"label\" : \"machineId\",\r\n \"value\" : \"10077\"\r\n}, {\r\n \"label\" : \"centerId\",\r\n \"value\" : \"10001\"\r\n}, {\r\n \"label\" : \"dongleId\",\r\n \"value\" : null\r\n}, {\r\n \"label\" : \"keyIndex\",\r\n \"value\" : \"4F:38:72:D9:F8:DB:94:E7:22:48:96:D0:91:01:6D:3C:64:90:2E:14:DC:D2:F8:14:1F:2A:A4:19:1A:BC:91:41\"\r\n}, {\r\n \"label\" : \"consentOfApplicant\",\r\n \"value\" : \"Yes} ]"); - Map finalMap = new LinkedHashMap<>(); - finalMap.put("identity", keyValueMap); - - when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); - - PowerMockito.mockStatic(CbeffValidator.class); - when(CbeffValidator.getBIRFromXML(any())).thenReturn(birType); - - BiometricRecord result = iPacketReader.getBiometric("id", "officerBiometric", null, "source", "process"); - - assertTrue("Should be true", result.getSegments().size() == 2); - } - - @Test - public void getMetaInfoTest() throws IOException { - Map keyValueMap = new LinkedHashMap<>(); - keyValueMap.put("operationsData", "[{\n" + - "\t\"label\": \"officerId\",\n" + - "\t\"value\": \"110122\"\n" + - "}, {\n" + - "\t\"label\": \"officerBiometricFileName\",\n" + - "\t\"value\": \"officerBiometric\"\n" + - "}, {\n" + - "\t\"label\": \"supervisorId\",\n" + - "\t\"value\": null\n" + - "}, {\n" + - "\t\"label\": \"supervisorBiometricFileName\",\n" + - "\t\"value\": null\n" + - "}, {\n" + - "\t\"label\": \"supervisorPassword\",\n" + - "\t\"value\": \"false\"\n" + - "}, {\n" + - "\t\"label\": \"officerPassword\",\n" + - "\t\"value\": \"true\"\n" + - "}, {\n" + - "\t\"label\": \"supervisorPIN\",\n" + - "\t\"value\": null\n" + - "}, {\n" + - "\t\"label\": \"officerPIN\",\n" + - "\t\"value\": null\n" + - "}, {\n" + - "\t\"label\": \"supervisorOTPAuthentication\",\n" + - "\t\"value\": \"false\"\n" + - "}, {\n" + - "\t\"label\": \"officerOTPAuthentication\",\n" + - "\t\"value\": \"false\"\n" + - "}]"); - keyValueMap.put("metaData", "\"[ {\r\n \"label\" : \"registrationId\",\r\n \"value\" : \"10001100770000320200720092256\"\r\n}, {\r\n \"label\" : \"creationDate\",\r\n \"value\" : \"2020-07-20T14:54:49.823Z\"\r\n}, {\r\n \"label\" : \"Registration Client Version Number\",\r\n \"value\" : \"1.0.10\"\r\n}, {\r\n \"label\" : \"registrationType\",\r\n \"value\" : \"New\"\r\n}, {\r\n \"label\" : \"preRegistrationId\",\r\n \"value\" : null\r\n}, {\r\n \"label\" : \"machineId\",\r\n \"value\" : \"10077\"\r\n}, {\r\n \"label\" : \"centerId\",\r\n \"value\" : \"10001\"\r\n}, {\r\n \"label\" : \"dongleId\",\r\n \"value\" : null\r\n}, {\r\n \"label\" : \"keyIndex\",\r\n \"value\" : \"4F:38:72:D9:F8:DB:94:E7:22:48:96:D0:91:01:6D:3C:64:90:2E:14:DC:D2:F8:14:1F:2A:A4:19:1A:BC:91:41\"\r\n}, {\r\n \"label\" : \"consentOfApplicant\",\r\n \"value\" : \"Yes\"\r\n} ]\""); - Map finalMap = new LinkedHashMap<>(); - finalMap.put("identity", keyValueMap); - - when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); - - Map result = iPacketReader.getMetaInfo("id", "source", "process"); - - assertTrue("Should be true", result.size() == 2); - } - - @Test - public void getAuditTest() throws IOException { - ReflectionTestUtils.setField(iPacketReader, "packetNames", "id"); - Map keyValueMap = new LinkedHashMap<>(); - keyValueMap.put("audit1", "audit1"); - keyValueMap.put("audit2", "audit2"); - List> finalMap = new ArrayList<>(); - finalMap.add(keyValueMap); - - when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); - - List> result = iPacketReader.getAuditInfo("id", "source", "process"); - - assertTrue("Should be true", result.size() == 1); - } - - @Test(expected = GetAllMetaInfoException.class) - public void metaInfoExceptionTest() throws IOException { - when(objectMapper.readValue(anyString(), any(Class.class))).thenThrow(new IOException("exception")); - - iPacketReader.getMetaInfo("id", "source", "process"); - } - - @Test(expected = GetAllIdentityException.class) - public void getAuditExceptionTest() throws IOException { - when(objectMapper.readValue(anyString(), any(Class.class))).thenThrow(new IOException("exception")); - - iPacketReader.getAuditInfo("id", "source", "process"); - } - -} +package io.mosip.commons.packet.test.impl; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyObject; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import io.mosip.commons.packet.facade.PacketReader; +import org.apache.commons.io.IOUtils; +import org.assertj.core.util.Lists; +import org.json.JSONException; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.context.annotation.PropertySource; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.commons.packet.dto.Document; +import io.mosip.commons.packet.dto.Packet; +import io.mosip.commons.packet.exception.GetAllIdentityException; +import io.mosip.commons.packet.exception.GetAllMetaInfoException; +import io.mosip.commons.packet.exception.GetDocumentException; +import io.mosip.commons.packet.exception.PacketKeeperException; +import io.mosip.commons.packet.exception.PacketValidationFailureException; +import io.mosip.commons.packet.impl.PacketReaderImpl; +import io.mosip.commons.packet.keeper.PacketKeeper; +import io.mosip.commons.packet.spi.IPacketReader; +import io.mosip.commons.packet.util.IdSchemaUtils; +import io.mosip.commons.packet.util.PacketValidator; +import io.mosip.commons.packet.util.ZipUtils; +import io.mosip.kernel.biometrics.commons.CbeffValidator; +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.constant.QualityType; +import io.mosip.kernel.biometrics.entities.BDBInfo; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.entities.RegistryIDType; +import io.mosip.kernel.core.idobjectvalidator.exception.IdObjectIOException; +import io.mosip.kernel.core.idobjectvalidator.exception.IdObjectValidationFailedException; +import io.mosip.kernel.core.idobjectvalidator.exception.InvalidIdSchemaException; +import io.mosip.kernel.core.util.JsonUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ZipUtils.class, IOUtils.class, JsonUtils.class, CbeffValidator.class}) +@PropertySource("classpath:application-test.properties") +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +public class PacketReaderImplTest { + + @InjectMocks + private IPacketReader iPacketReader = new PacketReaderImpl(); + + @Mock + private PacketReader packetReader; + + @Mock + private PacketValidator packetValidator; + + @Mock + private PacketKeeper packetKeeper; + + @Mock + private ObjectMapper objectMapper; + + @Mock + private IdSchemaUtils idSchemaUtils; + + private static final String docName = "proofOfIdentity"; + private static final String biometricFieldName = "individualBiometrics"; + Map keyValueMap = null; + + @Before + public void setup() throws PacketKeeperException, IOException { + Packet packet = new Packet(); + packet.setPacket("hello".getBytes()); + + String str = "{ \"identity\" : {\n" + + " \"proofOfAddress\" : {\n" + + " \"value\" : \"proofOfAddress\",\n" + + " \"type\" : \"DOC004\",\n" + + " \"format\" : \"jpg\"\n" + + " },\n" + + " \"gender\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"Male\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"الذكر\"\n" + + " } ],\n" + + " \"city\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"Kenitra\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"القنيطرة\"\n" + + " } ],\n" + + " \"postalCode\" : \"14000\",\n" + + " \"fullName\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"Test after fix\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"Test after fix\"\n" + + " } ],\n" + + " \"dateOfBirth\" : \"1976/01/01\",\n" + + " \"referenceIdentityNumber\" : \"2345235252352353523\",\n" + + " \"individualBiometrics\" : {\n" + + " \"format\" : \"cbeff\",\n" + + " \"version\" : 1.0,\n" + + " \"value\" : \"individualBiometrics_bio_CBEFF\"\n" + + " },\n" + + " \"IDSchemaVersion\" : \"0.1\",\n" + + " \"province\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"Kenitra\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"القنيطرة\"\n" + + " } ],\n" + + " \"zone\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"Assam\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"العصام\"\n" + + " } ],\n" + + " \"phone\" : \"9606139887\",\n" + + " \"addressLine1\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"asdadsfas\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"asdadsfas\"\n" + + " } ],\n" + + " \"addressLine2\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"qqwqrqwrw\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"qqwqrqwrw\"\n" + + " } ],\n" + + " \"residenceStatus\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"Non-Foreigner\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"غير أجنبي\"\n" + + " } ],\n" + + " \"addressLine3\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"wfwfwef\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"wfwfwef\"\n" + + " } ],\n" + + " \"region\" : [ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \"Rabat Sale Kenitra\"\n" + + " }, {\n" + + " \"language\" : \"ara\",\n" + + " \"value\" : \"جهة الرباط سلا القنيطرة\"\n" + + " } ],\n" + + " \"email\" : \"niyati.swami@technoforte.co.in\"\n" + + "} } "; + + keyValueMap = new LinkedHashMap<>(); + keyValueMap.put("email", "niyati.swami@technoforte.co.in"); + keyValueMap.put("phone", "9606139887"); + keyValueMap.put("fullName", "[ {\r\n \"language\" : \"eng\",\r\n \"value\" : \"Test after fix\"\r\n}, {\r\n \"language\" : \"ara\",\r\n \"value\" : \"Test after fix\"\r\n} ]"); + keyValueMap.put("IDSchemaVersion", "0.1"); + keyValueMap.put(biometricFieldName, "{\r\n \"format\" : \"cbeff\",\r\n \"version\" : 1.0,\r\n \"value\" : \"individualBiometrics_bio_CBEFF\"\r\n}"); + keyValueMap.put(docName, "{\r\n \"value\" : \"proofOfIdentity\",\r\n \"type\" : \"DOC003\",\r\n \"format\" : \"jpg\"\r\n}"); + + + Map finalMap = new LinkedHashMap<>(); + finalMap.put("identity", keyValueMap); + + ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes()); + + MockitoAnnotations.initMocks(this); + ReflectionTestUtils.setField(iPacketReader, "packetNames", "id,evidence,optional"); + when(packetKeeper.getPacket(any())).thenReturn(packet); + + PowerMockito.mockStatic(ZipUtils.class); + when(ZipUtils.unzipAndGetFile(any(), anyString())).thenReturn(bis); + PowerMockito.mockStatic(IOUtils.class); + when(IOUtils.toByteArray(any(InputStream.class))).thenReturn(str.getBytes()); + + when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); + when(idSchemaUtils.getSource(any(), any())).thenReturn("id"); + when(idSchemaUtils.getIdschemaVersionFromMappingJson()).thenReturn("0.1"); + + } + + @Test + public void validatePacketTest() throws JsonProcessingException, PacketKeeperException, InvalidIdSchemaException, IdObjectIOException, IOException, NoSuchAlgorithmException, JSONException, IdObjectValidationFailedException { + when(packetValidator.validate(anyString(), anyString(), anyString())).thenReturn(true); + boolean result = iPacketReader.validatePacket("id", "source", "process"); + + assertTrue("Should be true", result); + } + + @Test(expected = PacketValidationFailureException.class) + public void validatePacketExceptionTest() throws JsonProcessingException, PacketKeeperException, InvalidIdSchemaException, IdObjectValidationFailedException, IdObjectIOException, IOException, NoSuchAlgorithmException, JSONException { + when(packetValidator.validate(anyString(), anyString(), anyString())).thenThrow(new IOException("exception")); + boolean result = iPacketReader.validatePacket("id", "source","process"); + + } + + @Test + public void getAllTest() { + Map result = iPacketReader.getAll("id", "source", "process"); + + assertTrue("Should be true", result.size() == 6); + } + + @Test(expected = GetAllIdentityException.class) + public void getAllExceptionTest() throws IOException { + when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(null); + + Map result = iPacketReader.getAll("id", "source", "process"); + } + + @Test(expected = GetAllIdentityException.class) + public void getAllExceptionTest2() throws JsonProcessingException, IOException { + PowerMockito.mockStatic(JsonUtils.class); + Map keyValueMap = new LinkedHashMap<>(); + keyValueMap.put("email", new JSONObject(new LinkedHashMap())); + Map finalMap = new LinkedHashMap<>(); + finalMap.put("identity", keyValueMap); + when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); + + when(JsonUtils.javaObjectToJsonString(anyObject())).thenThrow(new JsonProcessingException("errormessage")); + Map result = iPacketReader.getAll("id", "source", "process"); + } + + @Test + public void getFieldTest() { + String result = iPacketReader.getField("id", "phone", "source","process"); + + assertTrue("Should be true", result.equals("9606139887")); + } + + @Test + public void getFieldsTest() { + List list = Lists.newArrayList("phone", "email"); + + Map result = iPacketReader.getFields("id", list, "source", "process"); + + assertTrue("Should be true", result.size() == 2); + } + + @Test + public void getDocumentTest() { + List list = Lists.newArrayList("phone", "email"); + when(packetReader.getField("id","0.1","source","process",false)).thenReturn("0.1"); + when(packetReader.getField("id",docName,"source","process",false)).thenReturn(keyValueMap.get(docName).toString()); + + Document result = iPacketReader.getDocument("id", docName, "source", "process"); + + assertTrue("Should be true", result.getDocument() != null); + } + + @Test(expected = GetDocumentException.class) + public void getDocumentExceptionTest() throws IOException { + List list = Lists.newArrayList("phone", "email"); + when(packetReader.getField("id","0.1","source","process",false)).thenReturn("0.1"); + when(packetReader.getField("id",docName,"source","process",false)).thenReturn(keyValueMap.get(docName).toString()); + + when(idSchemaUtils.getSource(any(), any())).thenThrow(new IOException("exception")); + + Document result = iPacketReader.getDocument("id", docName, "source", "process"); + + } + + @Test + public void getBiometricsTest() throws Exception { + BIR birType = new BIR(); + BIR bir1 = new BIR(); + BDBInfo bdbInfoType1 = new BDBInfo(); + RegistryIDType registryIDType = new RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + BiometricType singleType1 = BiometricType .FINGER; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); + bdbInfoType1.setSubtype(subtype1); + bdbInfoType1.setType(singleTypeList1); + bdbInfoType1.setFormat(registryIDType); + bir1.setBdbInfo(bdbInfoType1); + BIR bir2 = new BIR(); + bir2.setBdbInfo(bdbInfoType1); + + PowerMockito.mockStatic(CbeffValidator.class); + birType.setBirs(Lists.newArrayList(bir1, bir2)); + when(CbeffValidator.getBIRFromXML(any())).thenReturn(birType); + + when(packetReader.getField("id",biometricFieldName,"source","process",false)).thenReturn(keyValueMap.get(biometricFieldName).toString()); + + BiometricRecord result = iPacketReader.getBiometric("id", biometricFieldName, null, "source", "process"); + + assertTrue("Should be true", result.getSegments().size() == 2); + } + + @Test + @Ignore + public void getBiometricsExceptionTest() throws Exception { + List list = Lists.newArrayList("phone", "email"); + BIR birType = new BIR(); + + BIR bir1 = new BIR(); + BDBInfo bdbInfoType1 = new BDBInfo(); + RegistryIDType registryIDType = new RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + BiometricType singleType1 = BiometricType.FINGER; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); + bdbInfoType1.setSubtype(subtype1); + bdbInfoType1.setType(singleTypeList1); + bdbInfoType1.setFormat(registryIDType); + bir1.setBdbInfo(bdbInfoType1); + BIR bir2 = new BIR(); + bir2.setBdbInfo(bdbInfoType1); + birType.setBirs(Lists.newArrayList(bir1, bir2)); + + Map keyValueMap = new LinkedHashMap<>(); + keyValueMap.put("operationsData", "[{\n \"label\\\" : \\\"officerId\\\",\n \\\"value\\\" : \\\"110012\\\"\n}, {\n \\\"label\\\" : \\\"officerBiometricFileName\\\",\n \\\"value\\\" : \\\"officer_bio_cbeff\\\"\n}, {\n \\\"label\\\" : \\\"supervisorId\\\",\n \\\"value\\\" : null\n}, {\n \\\"label\\\" : \\\"supervisorBiometricFileName\\\",\n \\\"value\\\" : null\n}, {\n \\\"label\\\" : \\\"supervisorPassword\\\",\n \\\"value\\\" : \\\"false\\\"\n}, {\n \\\"label\\\" : \\\"officerPassword\\\",\n \\\"value\\\" : \\\"true\\\"\n}, {\n \\\"label\\\" : \\\"supervisorPIN\\\",\n \\\"value\\\" : null\n}, {\n \\\"label\\\" : \\\"officerPIN\\\",\n \\\"value\\\" : null\n}]"); + keyValueMap.put("metaData", "[{\r\n \"label\" : \"registrationId\",\r\n \"value\" : \"10001100770000320200720092256\"\r\n}, {\r\n \"label\" : \"creationDate\",\r\n \"value\" : \"2020-07-20T14:54:49.823Z\"\r\n}, {\r\n \"label\" : \"Registration Client Version Number\",\r\n \"value\" : \"1.0.10\"\r\n}, {\r\n \"label\" : \"registrationType\",\r\n \"value\" : \"New\"\r\n}, {\r\n \"label\" : \"preRegistrationId\",\r\n \"value\" : null\r\n}, {\r\n \"label\" : \"machineId\",\r\n \"value\" : \"10077\"\r\n}, {\r\n \"label\" : \"centerId\",\r\n \"value\" : \"10001\"\r\n}, {\r\n \"label\" : \"dongleId\",\r\n \"value\" : null\r\n}, {\r\n \"label\" : \"keyIndex\",\r\n \"value\" : \"4F:38:72:D9:F8:DB:94:E7:22:48:96:D0:91:01:6D:3C:64:90:2E:14:DC:D2:F8:14:1F:2A:A4:19:1A:BC:91:41\"\r\n}, {\r\n \"label\" : \"consentOfApplicant\",\r\n \"value\" : \"Yes} ]"); + Map finalMap = new LinkedHashMap<>(); + finalMap.put("identity", keyValueMap); + + when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); + + PowerMockito.mockStatic(CbeffValidator.class); + when(CbeffValidator.getBIRFromXML(any())).thenReturn(birType); + + BiometricRecord result = iPacketReader.getBiometric("id", "officerBiometric", null, "source", "process"); + + assertTrue("Should be true", result.getSegments().size() == 2); + } + + @Test + public void getMetaInfoTest() throws IOException { + Map keyValueMap = new LinkedHashMap<>(); + keyValueMap.put("operationsData", "[{\n" + + "\t\"label\": \"officerId\",\n" + + "\t\"value\": \"110122\"\n" + + "}, {\n" + + "\t\"label\": \"officerBiometricFileName\",\n" + + "\t\"value\": \"officerBiometric\"\n" + + "}, {\n" + + "\t\"label\": \"supervisorId\",\n" + + "\t\"value\": null\n" + + "}, {\n" + + "\t\"label\": \"supervisorBiometricFileName\",\n" + + "\t\"value\": null\n" + + "}, {\n" + + "\t\"label\": \"supervisorPassword\",\n" + + "\t\"value\": \"false\"\n" + + "}, {\n" + + "\t\"label\": \"officerPassword\",\n" + + "\t\"value\": \"true\"\n" + + "}, {\n" + + "\t\"label\": \"supervisorPIN\",\n" + + "\t\"value\": null\n" + + "}, {\n" + + "\t\"label\": \"officerPIN\",\n" + + "\t\"value\": null\n" + + "}, {\n" + + "\t\"label\": \"supervisorOTPAuthentication\",\n" + + "\t\"value\": \"false\"\n" + + "}, {\n" + + "\t\"label\": \"officerOTPAuthentication\",\n" + + "\t\"value\": \"false\"\n" + + "}]"); + keyValueMap.put("metaData", "\"[ {\r\n \"label\" : \"registrationId\",\r\n \"value\" : \"10001100770000320200720092256\"\r\n}, {\r\n \"label\" : \"creationDate\",\r\n \"value\" : \"2020-07-20T14:54:49.823Z\"\r\n}, {\r\n \"label\" : \"Registration Client Version Number\",\r\n \"value\" : \"1.0.10\"\r\n}, {\r\n \"label\" : \"registrationType\",\r\n \"value\" : \"New\"\r\n}, {\r\n \"label\" : \"preRegistrationId\",\r\n \"value\" : null\r\n}, {\r\n \"label\" : \"machineId\",\r\n \"value\" : \"10077\"\r\n}, {\r\n \"label\" : \"centerId\",\r\n \"value\" : \"10001\"\r\n}, {\r\n \"label\" : \"dongleId\",\r\n \"value\" : null\r\n}, {\r\n \"label\" : \"keyIndex\",\r\n \"value\" : \"4F:38:72:D9:F8:DB:94:E7:22:48:96:D0:91:01:6D:3C:64:90:2E:14:DC:D2:F8:14:1F:2A:A4:19:1A:BC:91:41\"\r\n}, {\r\n \"label\" : \"consentOfApplicant\",\r\n \"value\" : \"Yes\"\r\n} ]\""); + Map finalMap = new LinkedHashMap<>(); + finalMap.put("identity", keyValueMap); + + when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); + + Map result = iPacketReader.getMetaInfo("id", "source", "process"); + + assertTrue("Should be true", result.size() == 2); + } + + @Test + public void getAuditTest() throws IOException { + ReflectionTestUtils.setField(iPacketReader, "packetNames", "id"); + Map keyValueMap = new LinkedHashMap<>(); + keyValueMap.put("audit1", "audit1"); + keyValueMap.put("audit2", "audit2"); + List> finalMap = new ArrayList<>(); + finalMap.add(keyValueMap); + + when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(finalMap); + + List> result = iPacketReader.getAuditInfo("id", "source", "process"); + + assertTrue("Should be true", result.size() == 1); + } + + @Test(expected = GetAllMetaInfoException.class) + public void metaInfoExceptionTest() throws IOException { + when(objectMapper.readValue(anyString(), any(Class.class))).thenThrow(new IOException("exception")); + + iPacketReader.getMetaInfo("id", "source", "process"); + } + + @Test(expected = GetAllIdentityException.class) + public void getAuditExceptionTest() throws IOException { + when(objectMapper.readValue(anyString(), any(Class.class))).thenThrow(new IOException("exception")); + + iPacketReader.getAuditInfo("id", "source", "process"); + } + +} diff --git a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/keeper/PacketKeeperTest.java b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/keeper/PacketKeeperTest.java index 347a6738e4..b8d6c4cc15 100644 --- a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/keeper/PacketKeeperTest.java +++ b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/keeper/PacketKeeperTest.java @@ -1,244 +1,242 @@ -package io.mosip.commons.packet.test.keeper; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.mosip.commons.packet.util.PacketManagerHelper; -import io.mosip.kernel.core.util.CryptoUtil; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import com.google.common.collect.Lists; - -import io.mosip.commons.khazana.dto.ObjectDto; -import io.mosip.commons.khazana.spi.ObjectStoreAdapter; -import io.mosip.commons.packet.constants.PacketManagerConstants; -import io.mosip.commons.packet.dto.Packet; -import io.mosip.commons.packet.dto.PacketInfo; -import io.mosip.commons.packet.dto.TagDto; -import io.mosip.commons.packet.dto.TagRequestDto; -import io.mosip.commons.packet.exception.PacketKeeperException; -import io.mosip.commons.packet.keeper.PacketKeeper; -import io.mosip.commons.packet.spi.IPacketCryptoService; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.util.DateUtils; - -@RunWith(SpringRunner.class) -public class PacketKeeperTest { - - @InjectMocks - private PacketKeeper packetKeeper; - - @Mock - @Qualifier("SwiftAdapter") - private ObjectStoreAdapter swiftAdapter; - - @Mock - @Qualifier("S3Adapter") - private ObjectStoreAdapter s3Adapter; - - @Mock - @Qualifier("PosixAdapter") - private ObjectStoreAdapter posixAdapter; - - @Mock - @Qualifier("OnlinePacketCryptoServiceImpl") - private IPacketCryptoService onlineCrypto; - - @Mock - private PacketManagerHelper helper; - - /*@Mock - private OfflinePacketCryptoServiceImpl offlineCrypto;*/ - - private Packet packet; - private PacketInfo packetInfo; - - private static final String id = "1234567890"; - private static final String source = "source"; - private static final String process = "process"; - - @Before - public void setup() throws NoSuchAlgorithmException { - ReflectionTestUtils.setField(packetKeeper, "cryptoName", onlineCrypto.getClass().getSimpleName()); - ReflectionTestUtils.setField(packetKeeper, "adapterName", swiftAdapter.getClass().getSimpleName()); - ReflectionTestUtils.setField(packetKeeper, "PACKET_MANAGER_ACCOUNT", "PACKET_MANAGER_ACCOUNT"); - ReflectionTestUtils.setField(packetKeeper, "centerIdLength", 5); - ReflectionTestUtils.setField(packetKeeper, "machineIdLength", 5); - ReflectionTestUtils.setField(packetKeeper, "disablePacketSignatureVerification", false); - - packetInfo = new PacketInfo(); - packetInfo.setCreationDate(DateUtils.getCurrentDateTimeString()); - packetInfo.setEncryptedHash("yWxtW-jQihLntc3Bsgf6ayQwl0yGgD2IkWdedv2ZLCA="); - packetInfo.setId(id); - packetInfo.setProcess(process); - packetInfo.setSource(source); - packetInfo.setSignature("signatures"); - packetInfo.setSchemaVersion("0.1"); - packetInfo.setProviderVersion("1.0"); - packet = new Packet(); - packet.setPacket("packet".getBytes()); - packet.setPacketInfo(packetInfo); - - Map metaMap = new HashMap<>(); - metaMap.put(PacketManagerConstants.ID, id); - metaMap.put(PacketManagerConstants.SOURCE, source); - metaMap.put(PacketManagerConstants.PROCESS, process); - metaMap.put(PacketManagerConstants.SIGNATURE, "signatures"); - metaMap.put(PacketManagerConstants.ENCRYPTED_HASH, "yWxtW-jQihLntc3Bsgf6ayQwl0yGgD2IkWdedv2ZLCA="); - - Mockito.when(onlineCrypto.encrypt(any(), any())).thenReturn("encryptedpacket".getBytes()); - Mockito.when(onlineCrypto.sign(any())).thenReturn("signed data".getBytes()); - Mockito.when(swiftAdapter.putObject(any(), any(), any(),any(), any(), any())).thenReturn(true); - Mockito.when(swiftAdapter.addObjectMetaData(any(), any(), any(),any(), any(), any())).thenReturn(metaMap); - - InputStream is = new ByteArrayInputStream("input".getBytes()); - - Mockito.when(swiftAdapter.getObject(any(), any(),any(), any(), any())).thenReturn(is); - Mockito.when(onlineCrypto.decrypt(any(), any())).thenReturn("decryptedpacket".getBytes()); - Mockito.when(swiftAdapter.getMetaData(any(), any(),any(), any(), any())).thenReturn(metaMap); - Mockito.when(onlineCrypto.verify(any(),any(), any())).thenReturn(true); - Map tagsMap = new HashMap<>(); - tagsMap.put("osivalidation", "pass"); - Mockito.when(swiftAdapter.getTags(any(), any())).thenReturn(tagsMap); - } - - @Test - public void testPutPacketSuccess() throws PacketKeeperException { - PacketInfo packetInfo = packetKeeper.putPacket(packet); - - assertTrue(packetInfo.getId().equals(id)); - assertTrue(packetInfo.getSource().equals(source)); - assertTrue(packetInfo.getProcess().equals(process)); - } - - @Test(expected = PacketKeeperException.class) - public void testPutPacketException() throws PacketKeeperException { - Mockito.when(onlineCrypto.encrypt(any(), any())).thenThrow(new BaseUncheckedException("code","message")); - - packetKeeper.putPacket(packet); - } - - @Test(expected = PacketKeeperException.class) - public void testObjectStoreAdapterException() throws PacketKeeperException { - ReflectionTestUtils.setField(packetKeeper, "adapterName", "wrongAdapterName"); - - packetKeeper.putPacket(packet); - } - - @Test(expected = PacketKeeperException.class) - public void testCryptoException() throws PacketKeeperException { - ReflectionTestUtils.setField(packetKeeper, "cryptoName", "wrongname"); - - packetKeeper.putPacket(packet); - } - - @Test - public void testGetPacketSuccess() throws PacketKeeperException { - Packet result = packetKeeper.getPacket(packetInfo); - - assertTrue(result.getPacketInfo().getId().equals(id)); - assertTrue(result.getPacketInfo().getSource().equals(source)); - assertTrue(result.getPacketInfo().getProcess().equals(process)); - } - - @Test(expected = PacketKeeperException.class) - public void testGetPacketFailure() throws PacketKeeperException { - Mockito.when(swiftAdapter.getObject(any(), any(), any(), any(), any())).thenThrow(new BaseUncheckedException("code","message")); - - packetKeeper.getPacket(packetInfo); - } - - @Test(expected = PacketKeeperException.class) - @Ignore - public void testPacketIntegrityFailure() throws PacketKeeperException { - Mockito.when(onlineCrypto.verify(any(),any(), any())).thenReturn(false); - - packetKeeper.getPacket(packetInfo); - } - @Test - public void testAddTags() { - TagDto tagDto=new TagDto(); - tagDto.setId(id); - Map tags = new HashMap<>(); - tags.put("test", "testValue"); - tagDto.setTags(tags); - Mockito.when(swiftAdapter.addTags(any(), any(),any())).thenReturn(tags); - Map map = packetKeeper.addTags(tagDto); - assertEquals(tags, map); - - } - - @Test - public void testUpdateTags() { - TagDto tagDto=new TagDto(); - tagDto.setId(id); - Map tags = new HashMap<>(); - tags.put("test", "testValue"); - tagDto.setTags(tags); - Mockito.when(swiftAdapter.addTags(any(), any(),any())).thenReturn(tags); - Map map = packetKeeper.addorUpdate(tagDto); - assertEquals(tags, map); - - } - - @Test - public void testGetTags() { - List tagNames=new ArrayList<>(); - tagNames.add("osivalidation"); - - Map map = packetKeeper.getTags(id); - assertEquals(map.get("osivalidation"), "pass"); - - } - - - @Test - public void testgetAll() { - ObjectDto objectDto = new ObjectDto("source1", "process1", "object1", new Date()); - ObjectDto objectDto2 = new ObjectDto("source2", "process2", "object2", new Date()); - ObjectDto objectDto3 = new ObjectDto("source3", "process3", "object3", new Date()); - List objectDtos = Lists.newArrayList(objectDto, objectDto2, objectDto3); - - Mockito.when(swiftAdapter.getAllObjects(anyString(), anyString())).thenReturn(objectDtos); - - List result = packetKeeper.getAll(id); - assertEquals(objectDtos.size(), result.size()); - - } - @Test - public void testdeleteTags() { - TagRequestDto tagRequestDto=new TagRequestDto(); - tagRequestDto.setId(id); - List tagNames=new ArrayList<>(); - tagNames.add("osivalidation"); - tagRequestDto.setTagNames(tagNames); - packetKeeper.deleteTags(tagRequestDto); - - } - - -} - - +package io.mosip.commons.packet.test.keeper; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.mosip.commons.packet.util.PacketManagerHelper; +import org.assertj.core.util.Lists; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import io.mosip.commons.khazana.dto.ObjectDto; +import io.mosip.commons.khazana.spi.ObjectStoreAdapter; +import io.mosip.commons.packet.constants.PacketManagerConstants; +import io.mosip.commons.packet.dto.Packet; +import io.mosip.commons.packet.dto.PacketInfo; +import io.mosip.commons.packet.dto.TagDto; +import io.mosip.commons.packet.dto.TagRequestDto; +import io.mosip.commons.packet.exception.PacketKeeperException; +import io.mosip.commons.packet.keeper.PacketKeeper; +import io.mosip.commons.packet.spi.IPacketCryptoService; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.util.DateUtils; + +@RunWith(SpringRunner.class) +public class PacketKeeperTest { + + @InjectMocks + private PacketKeeper packetKeeper; + + @Mock + private PacketManagerHelper helper; + + @Mock + @Qualifier("SwiftAdapter") + private ObjectStoreAdapter swiftAdapter; + + @Mock + @Qualifier("S3Adapter") + private ObjectStoreAdapter s3Adapter; + + @Mock + @Qualifier("PosixAdapter") + private ObjectStoreAdapter posixAdapter; + + @Mock + @Qualifier("OnlinePacketCryptoServiceImpl") + private IPacketCryptoService onlineCrypto; + + /*@Mock + private OfflinePacketCryptoServiceImpl offlineCrypto;*/ + + private Packet packet; + private PacketInfo packetInfo; + + private static final String id = "1234567890"; + private static final String source = "source"; + private static final String process = "process"; + + @Before + public void setup() { + ReflectionTestUtils.setField(packetKeeper, "cryptoName", onlineCrypto.getClass().getSimpleName()); + ReflectionTestUtils.setField(packetKeeper, "adapterName", swiftAdapter.getClass().getSimpleName()); + ReflectionTestUtils.setField(packetKeeper, "PACKET_MANAGER_ACCOUNT", "PACKET_MANAGER_ACCOUNT"); + ReflectionTestUtils.setField(packetKeeper, "centerIdLength", 5); + ReflectionTestUtils.setField(packetKeeper, "machineIdLength", 5); + ReflectionTestUtils.setField(packetKeeper, "disablePacketSignatureVerification", false); + + packetInfo = new PacketInfo(); + packetInfo.setCreationDate(DateUtils.getCurrentDateTimeString()); + packetInfo.setEncryptedHash("yWxtW-jQihLntc3Bsgf6ayQwl0yGgD2IkWdedv2ZLCA"); + packetInfo.setId(id); + packetInfo.setProcess(process); + packetInfo.setSource(source); + packetInfo.setSignature("sign"); + packetInfo.setSchemaVersion("0.1"); + packetInfo.setProviderVersion("1.0"); + packet = new Packet(); + packet.setPacket("packet".getBytes()); + packet.setPacketInfo(packetInfo); + + Map metaMap = new HashMap<>(); + metaMap.put(PacketManagerConstants.ID, id); + metaMap.put(PacketManagerConstants.SOURCE, source); + metaMap.put(PacketManagerConstants.PROCESS, process); + metaMap.put(PacketManagerConstants.SIGNATURE, "signaturesignaturesignaturesignaturesignaturesignaturesignaturesignaturesignaturesignature"); + metaMap.put(PacketManagerConstants.ENCRYPTED_HASH, "yWxtW-jQihLntc3Bsgf6ayQwl0yGgD2IkWdedv2ZLCA"); + + Mockito.when(onlineCrypto.encrypt(any(), any())).thenReturn("encryptedpacket".getBytes()); + Mockito.when(onlineCrypto.sign(any())).thenReturn("signed data".getBytes()); + Mockito.when(swiftAdapter.putObject(any(), any(), any(),any(), any(), any())).thenReturn(true); + Mockito.when(swiftAdapter.addObjectMetaData(any(), any(), any(),any(), any(), any())).thenReturn(metaMap); + + InputStream is = new ByteArrayInputStream("input".getBytes()); + + Mockito.when(swiftAdapter.getObject(any(), any(),any(), any(), any())).thenReturn(is); + Mockito.when(onlineCrypto.decrypt(any(), any())).thenReturn("decryptedpacket".getBytes()); + Mockito.when(swiftAdapter.getMetaData(any(), any(),any(), any(), any())).thenReturn(metaMap); + Mockito.when(helper.getRefId(any(), any())).thenReturn("11001_11001"); + Mockito.when(onlineCrypto.verify(any(),any(), any())).thenReturn(true); + Map tagsMap = new HashMap<>(); + tagsMap.put("osivalidation", "pass"); + Mockito.when(swiftAdapter.getTags(any(), any())).thenReturn(tagsMap); + + + } + + @Test + public void testPutPacketSuccess() throws PacketKeeperException { + PacketInfo packetInfo = packetKeeper.putPacket(packet); + + assertTrue(packetInfo.getId().equals(id)); + assertTrue(packetInfo.getSource().equals(source)); + assertTrue(packetInfo.getProcess().equals(process)); + } + + @Test(expected = PacketKeeperException.class) + public void testPutPacketException() throws PacketKeeperException { + Mockito.when(onlineCrypto.encrypt(any(), any())).thenThrow(new BaseUncheckedException("code","message")); + + packetKeeper.putPacket(packet); + } + + @Test(expected = PacketKeeperException.class) + public void testObjectStoreAdapterException() throws PacketKeeperException { + ReflectionTestUtils.setField(packetKeeper, "adapterName", "wrongAdapterName"); + + packetKeeper.putPacket(packet); + } + + @Test(expected = PacketKeeperException.class) + public void testCryptoException() throws PacketKeeperException { + ReflectionTestUtils.setField(packetKeeper, "cryptoName", "wrongname"); + + packetKeeper.putPacket(packet); + } + + @Test + public void testGetPacketSuccess() throws PacketKeeperException { + Packet result = packetKeeper.getPacket(packetInfo); + + assertTrue(result.getPacketInfo().getId().equals(id)); + assertTrue(result.getPacketInfo().getSource().equals(source)); + assertTrue(result.getPacketInfo().getProcess().equals(process)); + } + + @Test(expected = PacketKeeperException.class) + public void testGetPacketFailure() throws PacketKeeperException { + Mockito.when(swiftAdapter.getObject(any(), any(), any(), any(), any())).thenThrow(new BaseUncheckedException("code","message")); + + packetKeeper.getPacket(packetInfo); + } + + @Test(expected = PacketKeeperException.class) + @Ignore + public void testPacketIntegrityFailure() throws PacketKeeperException { + Mockito.when(onlineCrypto.verify(any(),any(), any())).thenReturn(false); + + packetKeeper.getPacket(packetInfo); + } + @Test + public void testAddTags() { + TagDto tagDto=new TagDto(); + tagDto.setId(id); + Map tags = new HashMap<>(); + tags.put("test", "testValue"); + tagDto.setTags(tags); + Mockito.when(swiftAdapter.addTags(any(), any(),any())).thenReturn(tags); + Map map = packetKeeper.addTags(tagDto); + assertEquals(tags, map); + + } + + @Test + public void testUpdateTags() { + TagDto tagDto=new TagDto(); + tagDto.setId(id); + Map tags = new HashMap<>(); + tags.put("test", "testValue"); + tagDto.setTags(tags); + Mockito.when(swiftAdapter.addTags(any(), any(),any())).thenReturn(tags); + Map map = packetKeeper.addorUpdate(tagDto); + assertEquals(tags, map); + + } + + @Test + public void testGetTags() { + List tagNames=new ArrayList<>(); + tagNames.add("osivalidation"); + + Map map = packetKeeper.getTags(id); + assertEquals(map.get("osivalidation"), "pass"); + + } + + + @Test + public void testgetAll() { + ObjectDto objectDto = new ObjectDto("source1", "process1", "object1", new Date()); + ObjectDto objectDto2 = new ObjectDto("source2", "process2", "object2", new Date()); + ObjectDto objectDto3 = new ObjectDto("source3", "process3", "object3", new Date()); + List objectDtos = Lists.newArrayList(objectDto, objectDto2, objectDto3); + + Mockito.when(swiftAdapter.getAllObjects(anyString(), anyString())).thenReturn(objectDtos); + + List result = packetKeeper.getAll(id); + assertEquals(objectDtos.size(), result.size()); + + } + @Test + public void testdeleteTags() { + TagRequestDto tagRequestDto=new TagRequestDto(); + tagRequestDto.setId(id); + List tagNames=new ArrayList<>(); + tagNames.add("osivalidation"); + tagRequestDto.setTagNames(tagNames); + packetKeeper.deleteTags(tagRequestDto); + + } + + +} + + diff --git a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/config/PacketServiceConfig.java b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/config/PacketServiceConfig.java new file mode 100644 index 0000000000..40a15dcea6 --- /dev/null +++ b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/config/PacketServiceConfig.java @@ -0,0 +1,19 @@ +package io.mosip.commons.packetmanager.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.fasterxml.jackson.module.afterburner.AfterburnerModule; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +@Configuration +public class PacketServiceConfig { + + @Bean + @Primary + public ObjectMapper getObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper().registerModule(new AfterburnerModule()).registerModule(new JavaTimeModule()); + return objectMapper; + } +} diff --git a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketReaderController.java b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketReaderController.java index 87de6e7117..f045971f35 100644 --- a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketReaderController.java +++ b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketReaderController.java @@ -207,7 +207,7 @@ public ResponseWrapper> getAudits(@RequestBody(required = @Operation(summary = "validatePacket", description = "validatePacket", tags = { "packet-reader-controller" }) @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public ResponseWrapper validatePacket(@RequestBody(required = true) RequestWrapper request) { diff --git a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketServiceControllerAdvice.java b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketServiceControllerAdvice.java index 5574bc5c74..4fa43684ab 100644 --- a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketServiceControllerAdvice.java +++ b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketServiceControllerAdvice.java @@ -17,12 +17,12 @@ public class PacketServiceControllerAdvice { @ExceptionHandler(BaseCheckedException.class) public ResponseEntity baseCheckedException(BaseCheckedException e) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(getResponse(e.getErrorCode(), e.getMessage())); + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(getResponse(e.getErrorCode(), e.getErrorText())); } @ExceptionHandler(BaseUncheckedException.class) public ResponseEntity baseUnCheckedException(BaseUncheckedException e) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(getResponse(e.getErrorCode(), e.getMessage())); + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(getResponse(e.getErrorCode(), e.getErrorText())); } private ResponseWrapper getResponse(String errorCode, String message) { diff --git a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/dto/DocumentDto.java b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/dto/DocumentDto.java index 9651072866..25cc42dd99 100644 --- a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/dto/DocumentDto.java +++ b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/dto/DocumentDto.java @@ -11,4 +11,5 @@ public class DocumentDto { private String documentName; private String source; private String process; + private Boolean bypassCache; } diff --git a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/service/PacketReaderService.java b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/service/PacketReaderService.java index 8dd40a6b70..b7f65dd94e 100644 --- a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/service/PacketReaderService.java +++ b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/service/PacketReaderService.java @@ -80,7 +80,6 @@ public class PacketReaderService { private PacketReader packetReader; @Autowired - @Qualifier("restTemplate") private RestTemplate restTemplate; @Autowired @@ -275,7 +274,7 @@ private ObjectDto searchProcessWithLatestIteration(String id, String source, Str obj.getSource().equals(source) && PacketHelper.getProcessWithoutIteration(obj.getProcess()).equalsIgnoreCase(process)).findAny(); - return objectDto.isPresent() ? objectDto.get() : null; + return objectDto.isPresent() ? objectDto.get() : getObjectDto(source, process); } public String getSourceFromIdField(String process, String idField) throws IOException { @@ -290,6 +289,13 @@ public String getSourceFromIdField(String process, String idField) throws IOExce return null; } + private ObjectDto getObjectDto(String source, String process) { + ObjectDto objectDto1 = new ObjectDto(); + objectDto1.setSource(source); + objectDto1.setProcess(process); + return objectDto1; + } + public String searchInMappingJson(String idField, String process) throws IOException { if (idField != null) { JSONObject jsonObject = getMappingJsonFile(); diff --git a/commons-packet/commons-packet-service/src/main/resources/bootstrap.properties b/commons-packet/commons-packet-service/src/main/resources/bootstrap.properties index 8d7a186999..89ac215c39 100644 --- a/commons-packet/commons-packet-service/src/main/resources/bootstrap.properties +++ b/commons-packet/commons-packet-service/src/main/resources/bootstrap.properties @@ -9,7 +9,7 @@ server.port=8093 health.config.enabled=false server.servlet.path=/commons/v1/packetmanager config.server.file.storage.uri=${spring.cloud.config.uri}/*/${spring.profiles.active}/${spring.cloud.config.label}/ -registration.processor.identityjson=registration-processor-identity.json +registration.processor.identityjson=identity-mapping.json object.store.s3.use.account.as.bucketname=true spring.mvc.servlet.path=${server.servlet.path} diff --git a/commons-packet/commons-packet-service/src/test/java/io/mosip/commons/packetmanager/test/controller/PacketManagerControllerTest.java b/commons-packet/commons-packet-service/src/test/java/io/mosip/commons/packetmanager/test/controller/PacketManagerControllerTest.java index 49d35d1018..9fbd4fdf36 100644 --- a/commons-packet/commons-packet-service/src/test/java/io/mosip/commons/packetmanager/test/controller/PacketManagerControllerTest.java +++ b/commons-packet/commons-packet-service/src/test/java/io/mosip/commons/packetmanager/test/controller/PacketManagerControllerTest.java @@ -86,6 +86,8 @@ public class PacketManagerControllerTest { @Before public void setup() { MockitoAnnotations.initMocks(this); + Mockito.when(packetReaderService.getSourceAndProcess(any(),any(),any(),any())).thenReturn(new SourceProcessDto("source", "process")); + Mockito.when(packetReaderService.getSourceAndProcess(any(),any(),any())).thenReturn(new SourceProcessDto("source", "process")); }