diff --git a/commons-packet/commons-packet-manager/pom.xml b/commons-packet/commons-packet-manager/pom.xml index 2a8921ef70..739f77a51f 100644 --- a/commons-packet/commons-packet-manager/pom.xml +++ b/commons-packet/commons-packet-manager/pom.xml @@ -38,7 +38,7 @@ 1.2.1-SNAPSHOT 1.2.1-SNAPSHOT 1.2.1-SNAPSHOT - 1.2.1-SNAPSHOT + 1.2.2-SNAPSHOT 1.2.1-SNAPSHOT 3.11.2 **/constants/**,**/config/**,**/audit/**,**/util/**,**/dto/**,**/entity/**,**/model/**,**/exception/**,**/repository/**,**/security/**,**/*Config.java,**/*BootApplication.java,**/*VertxApplication.java,**/cbeffutil/**,**/*Utils.java,**/*Validator.java,**/*Helper.java,**/verticle/**,**/VidWriter.java/**,**/masterdata/utils/**,**/spi/**,**/core/http/**,"**/LocationServiceImpl.java","**/RegistrationCenterMachineServiceImpl.java","**/RegistrationCenterServiceImpl.java","**/pridgenerator/**","**/idgenerator/prid","**/proxy/**","**/cryptosignature/**" 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 7b60887685..9b3304cdb2 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 @@ -94,5 +94,4 @@ public String addAudit(String description, String eventId, return responseWrapper != null ? responseWrapper.getBody() : null; } - -} +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/audit/ServerUtil.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/audit/ServerUtil.java index 0f46c0c646..7bd48e44c3 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/audit/ServerUtil.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/audit/ServerUtil.java @@ -1,21 +1,21 @@ package io.mosip.commons.packet.audit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.net.InetAddress; import java.net.UnknownHostException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class ServerUtil { /** The server instance. */ private static ServerUtil serverInstance = null; - + /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(ServerUtil.class); - + /** The host not found. */ - private String noHost = "HOST_NOT_FOUND"; + private String noHost = "HOST_NOT_FOUND"; /** * @@ -38,7 +38,6 @@ public static synchronized ServerUtil getServerUtilInstance() { } else { return serverInstance; } - } /** @@ -48,14 +47,12 @@ public static synchronized ServerUtil getServerUtilInstance() { * */ public String getServerIp() { - try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { LOGGER.error(noHost, e.getMessage()); return "UNKNOWN-HOST"; } - } /** @@ -72,5 +69,4 @@ public String getServerName() { return "UNKNOWN-HOST"; } } - -} +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/OfflineConfig.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/OfflineConfig.java index 9dd13fcca7..aee0ecc845 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/OfflineConfig.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/OfflineConfig.java @@ -13,4 +13,4 @@ @EnableJpaRepositories(basePackages = {"io.mosip.kernel.keymanagerservice.repository.*"}) public class OfflineConfig { -} +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/PacketManagerConfig.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/PacketManagerConfig.java index bc345f6b72..96291f87cb 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/PacketManagerConfig.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/PacketManagerConfig.java @@ -53,16 +53,7 @@ public class PacketManagerConfig { */ @PostConstruct public void validateReferenceReaderProvider() throws ClassNotFoundException { - Set readerProviders = PacketHelper.getReaderProvider(packetReaderConfig); - if (!CollectionUtils.isEmpty(readerProviders)) { - for (String className : readerProviders) { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, - "Validating the reference provider readers are present or not."); - getBean(className); - } - } else - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, - "Reference provider reader class is not provided."); + validateProviders(PacketHelper.getReaderProvider(packetReaderConfig), "reader"); } /** @@ -72,16 +63,7 @@ public void validateReferenceReaderProvider() throws ClassNotFoundException { */ @PostConstruct public void validateReferenceWriterProvider() throws ClassNotFoundException { - Set writerProviders = PacketHelper.getWriterProvider(packetWriterConfig); - if (!CollectionUtils.isEmpty(writerProviders)) { - for (String className : writerProviders) { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, - "Validating the reference provider writers are present or not."); - getBean(className); - } - } else - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, - "Reference provider writer class is not provided."); + validateProviders(PacketHelper.getWriterProvider(packetWriterConfig), "writer"); } /** @@ -95,19 +77,7 @@ public void validateReferenceWriterProvider() throws ClassNotFoundException { @Bean @Lazy public List referenceReaderProviders() throws ClassNotFoundException { - List iPacketReaders = new ArrayList<>(); - Set readerProviders = PacketHelper.getReaderProvider(packetReaderConfig); - if (!CollectionUtils.isEmpty(readerProviders)) { - for (String className : readerProviders) { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, - "Validating the reference provider readers are present or not."); - iPacketReaders.add((IPacketReader) getBean(className)); - } - } else { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, - "reference provider reader is not present."); - } - return iPacketReaders; + return loadProviders(PacketHelper.getReaderProvider(packetReaderConfig), IPacketReader.class); } /** @@ -121,23 +91,56 @@ public List referenceReaderProviders() throws ClassNotFoundExcept @Bean @Lazy public List referenceWriterProviders() throws ClassNotFoundException { - List iPacketWriters = new ArrayList<>(); - Set writerProviders = PacketHelper.getWriterProvider(packetWriterConfig); - if (!CollectionUtils.isEmpty(writerProviders)) { - for (String className : writerProviders) { + return loadProviders(PacketHelper.getWriterProvider(packetWriterConfig), IPacketWriter.class); + } + + private void validateProviders(Set classNames, String type) { + if (CollectionUtils.isEmpty(classNames)) { + logger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, + String.format("No reference provider %s classes provided.", type)); + return; + } + + for (String className : classNames) { + try { logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, - "Validating the reference provider writers are present or not."); - iPacketWriters.add((IPacketWriter) getBean(className)); + String.format("Validating reference provider %s class: %s", type, className)); + getBean(className); + } catch (RuntimeException e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, + String.format("Invalid %s class %s: %s", type, className, e.getMessage())); + throw e; } - } else { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), null, - "reference provider writer is not present."); } - return iPacketWriters; } - - private Object getBean(String className) throws ClassNotFoundException { - Class clazz = Class.forName(className); - return applicationContext.getBean(clazz); + + private List loadProviders(Set classNames, Class expectedType) { + List providers = new ArrayList<>(); + if (!CollectionUtils.isEmpty(classNames)) { + for (String className : classNames) { + Object bean = getBean(className); + if (expectedType.isInstance(bean)) { + providers.add(expectedType.cast(bean)); + } else { + throw new IllegalArgumentException(String.format("Bean %s is not of expected type %s", className, expectedType.getSimpleName())); + } + } + } + return providers; + } + + private Object getBean(String className) { + try { + if (className == null || className.trim().isEmpty()) { + throw new ClassNotFoundException("Invalid class name: " + className); + } + className = className.replace(":", "").trim(); + Class clazz = Class.forName(className.trim()); + return applicationContext.getBean(clazz); + } catch (ClassNotFoundException e) { + throw new RuntimeException("Class not found: " + className, e); + } catch (Exception e) { + throw new RuntimeException("Failed to load bean: " + className, e); + } } -} +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/PacketReaderAndWriterConfig.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/PacketReaderAndWriterConfig.java index 64026ab501..fc46d3e6ce 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/PacketReaderAndWriterConfig.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/config/PacketReaderAndWriterConfig.java @@ -27,4 +27,4 @@ public Map readerConfiguration() { public Map writerConfiguration() { return new HashMap<>(); } -} +} \ No newline at end of file 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 5b46d90c10..3cf3b5b643 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 @@ -30,7 +30,7 @@ public enum PacketUtilityErrorCodes { 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."), + OBJECT_DOESNOT_EXISTS("KER-PUT-027", "Object does not exists."), UNKNOWN_EXCEPTION("KER-PUT-028", "Unknown Exception."); diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/dto/packet/CryptomanagerRequestDto.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/dto/packet/CryptomanagerRequestDto.java index 03b2f2c015..1b0ec07be4 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/dto/packet/CryptomanagerRequestDto.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/dto/packet/CryptomanagerRequestDto.java @@ -59,4 +59,4 @@ public class CryptomanagerRequestDto { @NotBlank(message = "should not be null or empty") private String aad; -} +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/dto/packet/CryptomanagerResponseDto.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/dto/packet/CryptomanagerResponseDto.java index 9b7dc470f2..5329998c07 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/dto/packet/CryptomanagerResponseDto.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/dto/packet/CryptomanagerResponseDto.java @@ -1,7 +1,5 @@ package io.mosip.commons.packet.dto.packet; - - import io.mosip.kernel.core.http.ResponseWrapper; import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketReader.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketReader.java index 945070c66f..3f381bc7ee 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketReader.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketReader.java @@ -2,24 +2,19 @@ import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.annotation.Cacheable; import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.Lazy; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; +import io.micrometer.core.annotation.Timed; 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.keeper.PacketKeeper; -import io.mosip.commons.packet.spi.IPacketReader; -import io.mosip.commons.packet.util.PacketHelper; import io.mosip.commons.packet.util.PacketManagerLogger; import io.mosip.kernel.biometrics.entities.BiometricRecord; import io.mosip.kernel.core.logger.spi.Logger; @@ -30,203 +25,192 @@ @RefreshScope @Component public class PacketReader { - - private static final Logger LOGGER = PacketManagerLogger.getLogger(PacketReader.class); - - @Autowired(required = false) - @Qualifier("referenceReaderProviders") - @Lazy - private List referenceReaderProviders; - - @Autowired - private PacketKeeper packetKeeper; - - /** - * Get a field from identity file - * - * @param id : the registration id - * @param field : field name to search - * @param source : the source packet. If not present return default - * @param process : the process - * @return String field - */ - @PreAuthorize("hasRole('DATA_READ')") - public String getField(String id, String field, String source, String process, boolean bypassCache) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "getFields for fields : " + field + " source : " + source + " process : " + process); - String value; - if (bypassCache) - value = getProvider(source, process).getField(id, field, source, process); - else { - Optional optionalValue = getAllFields(id, source, process).entrySet().stream().filter(m-> m.getKey().equalsIgnoreCase(field) && m.getValue()!=null).map(m -> m.getValue()).findAny(); - value = optionalValue.isPresent() ? optionalValue.get().toString() : null; - } - return value; - } - - /** - * Get fields from identity file - * - * @param id : the registration id - * @param fields : fields to search - * @param source : the source packet. If not present return default - * @param process : the process - * @return Map fields - */ - @PreAuthorize("hasRole('DATA_READ')") - public Map getFields(String id, List fields, String source, String process, boolean bypassCache) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "getFields for fields : " + fields.toString() + " source : " + source + " process : " + process); - Map values; - if (bypassCache) - values = getProvider(source, process).getFields(id, fields, source, process); - else { - values = getAllFields(id, source, process).entrySet() - .stream().filter(m -> fields.contains(m.getKey())).collect(Collectors.toMap(m -> m.getKey(), m -> m.getValue() != null ? m.getValue().toString() : null)); - } - return values; - } - - /** - * Get document by registration id, document name, source and process - * - * @param id : the registration id - * @param documentName : the document name - * @param source : the source packet. If not present return default - * @param process : the process - * @return Document : document information - */ - @PreAuthorize("hasRole('DOCUMENT_READ')") - @Cacheable(value = "packets",key = "'documents'.concat('-').concat(#p0).concat('-').concat(#p1).concat('-').concat(#p2).concat('-').concat(#p3)") - public Document getDocument(String id, String documentName, String source, String process) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "getDocument for documentName : " + documentName + " source : " + source + " process : " + process); - return getProvider(source, process).getDocument(id, documentName, source, process); - } - - /** - * Get biometric information by registration id, document name, source and process - * - * @param id : the registration id - * @param person : The person (ex - applicant, operator, supervisor, introducer etc) - * @param modalities : list of biometric modalities - * @param source : the source packet. If not present return default - * @param process : the process - * @return BiometricRecord : the biometric record - */ - @PreAuthorize("hasRole('BIOMETRIC_READ')") - @Cacheable(value = "packets", key = "'biometrics'.concat('-').#p0.concat('-').concat(#p1).concat('-').concat(#p2).concat('-').concat(#p3).concat('-').concat(#p4)", condition = "#p5 == false") - public BiometricRecord getBiometric(String id, String person, List modalities, String source, String process, boolean bypassCache) { - - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "getBiometric for source : " + source + " process : " + process); - return getProvider(source, process).getBiometric(id, person, modalities, source, process); - } - - /** - * Get packet meta information by registration id, source and process - * - * @param id : the registration id - * @param source : the source packet. If not present return default - * @param process : the process - * @return Map fields - */ - @PreAuthorize("hasRole('METADATA_READ')") - @Cacheable(value = "packets", key ="{'metaInfo'.concat('-').concat(#p0).concat('-').concat(#p1).concat('-').concat(#p2)}", condition = "#p3 == false") - public Map getMetaInfo(String id, String source, String process, boolean bypassCache) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "getMetaInfo for source : " + source + " process : " + process); - return getProvider(source, process).getMetaInfo(id, source, process); - } - - /** - * Get all field names from identity object - * - * @param id - * @param source - * @param process - * @return - */ - @PreAuthorize("hasRole('DATA_READ')") - @Cacheable(value = "info", key = "{#id}") - public List info(String id) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "info called"); - return packetKeeper.getAll(id); - } - - /** - * Get all field names from identity object - * - * @param id - * @param source - * @param process - * @return - */ - @PreAuthorize("hasRole('DATA_READ')") - public Set getAllKeys(String id, String source, String process) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "getAllKeys for source : " + source + " process : " + process); - return getProvider(source, process).getAll(id, source, process).keySet(); - } - - /** - * Get all fields from packet by id, source and process - * - * @param id : the registration id - * @param source : the source packet. If not present return default - * @param process : the process - * @return Map fields - */ - private Map getAllFields(String id, String source, String process) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "getAllFields for source : " + source + " process : " + process); - return getProvider(source, process).getAll(id, source, process); - } - - /** - * Get all fields from packet by id, source and process - * - * @param id : the registration id - * @param source : the source packet. If not present return default - * @param process : the process - * @return Map fields - */ - @Cacheable(value = "packets", key = "{#p0.concat('-').concat(#p1).concat('-').concat(#p2)}", condition = "#p3 == false") - public List> getAudits(String id, String source, String process, boolean bypassCache) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "getAllFields for source : " + source + " process : " + process); - return getProvider(source, process).getAuditInfo(id, source, process); - } - - @Cacheable(value = "tags", key = "{#p0}") - public Map getTags(String id) { - Map tags = packetKeeper.getTags(id); - return tags; - } - - public boolean validatePacket(String id, String source, String process) { - return getProvider(source, process).validatePacket(id, source, process); - } - - private IPacketReader getProvider(String source, String process) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, - "getProvider for source : " + source + " process : " + process); - IPacketReader provider = null; - if (referenceReaderProviders != null && !referenceReaderProviders.isEmpty()) { - Optional refProvider = referenceReaderProviders.stream().filter(refPr -> - (PacketHelper.isSourceAndProcessPresent(refPr.getClass().getName(), source, process, PacketHelper.Provider.READER))).findAny(); - if (refProvider.isPresent() && refProvider.get() != null) - provider = refProvider.get(); - } - - if (provider == null) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, - "No available provider found for source : " + source + " process : " + process); - throw new NoAvailableProviderException(); - } - - return provider; - } - + private static final Logger LOGGER = PacketManagerLogger.getLogger(PacketReader.class); + + @Autowired + private PacketKeeper packetKeeper; + + @Autowired + private PacketReaderProviderRegistry providerRegistry; + + /** + * Get a field from identity file + * + * @param id : the registration id + * @param field : field name to search + * @param source : the source packet. If not present return default + * @param process : the process + * @return String field + */ + @Timed("packet.reader.getField") + @PreAuthorize("hasRole('DATA_READ')") + public String getField(String id, String field, String source, String process, boolean bypassCache) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "getField - field={}, source={}, process={}", field, source, process); + + if (bypassCache) { + return providerRegistry.getReaderProvider(source, process).getField(id, field, source, process); + } + + return getAllFields(id, source, process).entrySet().stream() + .filter(e -> field.equalsIgnoreCase(e.getKey()) && e.getValue() != null) + .map(e -> e.getValue().toString()).findFirst().orElse(null); + } + + /** + * Get fields from identity file + * + * @param id : the registration id + * @param fields : fields to search + * @param source : the source packet. If not present return default + * @param process : the process + * @return Map fields + */ + @Timed("packet.reader.getFields") + @PreAuthorize("hasRole('DATA_READ')") + public Map getFields(String id, List fields, String source, String process, + boolean bypassCache) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "getFields - fields={}, source={}, process={}", fields, source, process); + + if (bypassCache) { + return providerRegistry.getReaderProvider(source, process).getFields(id, fields, source, process); + } + + return getAllFields(id, source, process).entrySet().stream().filter(entry -> fields.contains(entry.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, + e -> e.getValue() != null ? e.getValue().toString() : null)); + } + + /** + * Get document by registration id, document name, source and process + * + * @param id : the registration id + * @param documentName : the document name + * @param source : the source packet. If not present return default + * @param process : the process + * @return Document : document information + */ + @Timed("packet.reader.getDocument") + @PreAuthorize("hasRole('DOCUMENT_READ')") + @Cacheable(value = "packets", key = "'documents'.concat('-').concat(#p0).concat('-').concat(#p1).concat('-').concat(#p2).concat('-').concat(#p3)") + public Document getDocument(String id, String documentName, String source, String process) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "getDocument - documentName={}, source={}, process={}", documentName, source, process); + return providerRegistry.getReaderProvider(source, process).getDocument(id, documentName, source, process); + } + + /** + * Get biometric information by registration id, document name, source and + * process + * + * @param id : the registration id + * @param person : The person (ex - applicant, operator, supervisor, + * introducer etc) + * @param modalities : list of biometric modalities + * @param source : the source packet. If not present return default + * @param process : the process + * @return BiometricRecord : the biometric record + */ + @Timed("packet.reader.getBiometric") + @PreAuthorize("hasRole('BIOMETRIC_READ')") + @Cacheable(value = "packets", key = "'biometrics'.concat('-').#p0.concat('-').concat(#p1).concat('-').concat(#p2).concat('-').concat(#p3).concat('-').concat(#p4)", condition = "#p5 == false") + public BiometricRecord getBiometric(String id, String person, List modalities, String source, + String process, boolean bypassCache) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "getBiometric - source={}, process={}", source, process); + + return providerRegistry.getReaderProvider(source, process).getBiometric(id, person, modalities, source, + process); + } + + /** + * Get packet meta information by registration id, source and process + * + * @param id : the registration id + * @param source : the source packet. If not present return default + * @param process : the process + * @return Map fields + */ + @Timed("packet.reader.getMetaInfo") + @PreAuthorize("hasRole('METADATA_READ')") + @Cacheable(value = "packets", key = "{'metaInfo'.concat('-').concat(#p0).concat('-').concat(#p1).concat('-').concat(#p2)}", condition = "#p3 == false") + public Map getMetaInfo(String id, String source, String process, boolean bypassCache) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "getMetaInfo - source={}, process={}", source, process); + + return providerRegistry.getReaderProvider(source, process).getMetaInfo(id, source, process); + } + + /** + * Get all field names from identity object + * + * @param id + * @param source + * @param process + * @return + */ + @Timed("packet.reader.info") + @PreAuthorize("hasRole('DATA_READ')") + public List info(String id) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "info called"); + return packetKeeper.getAll(id); + } + + /** + * Get all field names from identity object + * + * @param id + * @param source + * @param process + * @return + */ + @Timed("packet.reader.getAllKeys") + @PreAuthorize("hasRole('DATA_READ')") + public Set getAllKeys(String id, String source, String process) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "getAllKeys - source={}, process={}", source, process); + return providerRegistry.getReaderProvider(source, process).getAll(id, source, process).keySet(); + } + + /** + * Get all fields from packet by id, source and process + * + * @param id : the registration id + * @param source : the source packet. If not present return default + * @param process : the process + * @return Map fields + */ + private Map getAllFields(String id, String source, String process) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "getAllFields - source={}, process={}", source, process); + return providerRegistry.getReaderProvider(source, process).getAll(id, source, process); + } + + /** + * Get all fields from packet by id, source and process + * + * @param id : the registration id + * @param source : the source packet. If not present return default + * @param process : the process + * @return Map fields + */ + @Timed("packet.reader.getAudits") + @Cacheable(value = "packets", key = "{#p0.concat('-').concat(#p1).concat('-').concat(#p2)}", condition = "#p3 == false") + public List> getAudits(String id, String source, String process, boolean bypassCache) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "getAudits - source={}, process={}", source, process); + + return providerRegistry.getReaderProvider(source, process).getAuditInfo(id, source, process); + } + + @Cacheable(value = "tags", key = "{#p0}") + public Map getTags(String id) { + Map tags = packetKeeper.getTags(id); + return tags; + } + + public boolean validatePacket(String id, String source, String process) { + return providerRegistry.getReaderProvider(source, process).validatePacket(id, source, process); + } } \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketReaderProviderRegistry.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketReaderProviderRegistry.java new file mode 100644 index 0000000000..a2edad1a11 --- /dev/null +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketReaderProviderRegistry.java @@ -0,0 +1,54 @@ +package io.mosip.commons.packet.facade; + +import io.mosip.commons.packet.exception.NoAvailableProviderException; +import io.mosip.commons.packet.spi.IPacketReader; +import io.mosip.commons.packet.util.PacketHelper; +import io.mosip.commons.packet.util.PacketManagerLogger; +import io.mosip.kernel.core.logger.spi.Logger; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +@Component +public class PacketReaderProviderRegistry { + private static final Logger LOGGER = PacketManagerLogger.getLogger(PacketReaderProviderRegistry.class); + + private final List referenceReaderProviders; + private final Map providerCache = new ConcurrentHashMap<>(); + private static final String UNDERSCORE = "_"; + + public PacketReaderProviderRegistry(@Qualifier("referenceReaderProviders") @Lazy List referenceReaderProviders) { + this.referenceReaderProviders = referenceReaderProviders; + } + + public IPacketReader getReaderProvider(String source, String process) { + String cacheKey = source + UNDERSCORE + process; + return providerCache.computeIfAbsent(cacheKey, key -> { + Optional provider = referenceReaderProviders.stream() + .filter(pr -> PacketHelper.isSourceAndProcessPresent( + pr.getClass().getName(), source, process, PacketHelper.Provider.READER)) + .findFirst(); + + if (provider.isEmpty()) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, + "No available IPacketReader provider for source={} and process={}", source, process); + throw new NoAvailableProviderException(); + } + + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, + "Cached IPacketReader for source={} and process={}", source, process); + return provider.get(); + }); + } + + public void clearCache() { + providerCache.clear(); + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, + "Provider cache cleared"); + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketWriter.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketWriter.java index 2718e31e0d..1d589daddb 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketWriter.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketWriter.java @@ -5,9 +5,7 @@ import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.annotation.CacheEvict; -import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import io.mosip.commons.packet.dto.Document; @@ -32,10 +30,8 @@ public class PacketWriter { private static final Logger LOGGER = PacketManagerLogger.getLogger(PacketWriter.class); - @Autowired(required = false) - @Qualifier("referenceWriterProviders") - @Lazy - private List referenceWriterProviders; + @Autowired + private PacketWriterProviderRegistry providerRegistry; @Autowired private PacketKeeper packetKeeper; @@ -50,7 +46,7 @@ public class PacketWriter { public void setField(String id, String fieldName, String value, String source, String process){ LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "setField for field name : " + fieldName + " source : " + source + " process : " + process); - getProvider(source, process).setField(id, fieldName, value); + providerRegistry.getWriterProvider(source, process).setField(id, fieldName, value); } /** @@ -62,7 +58,7 @@ public void setField(String id, String fieldName, String value, String source, S public void setFields(String id, Map fields, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "setFields : source : " + source + " process : " + process); - getProvider(source, process).setFields(id, fields); + providerRegistry.getWriterProvider(source, process).setFields(id, fields); } /** @@ -75,8 +71,7 @@ public void setFields(String id, Map fields, String source, Stri public void setBiometric(String id, String fieldName, BiometricRecord biometricRecord, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "setBiometric for field name : " + fieldName + " source : " + source + " process : " + process); - getProvider(source, process).setBiometric(id, fieldName, biometricRecord); - + providerRegistry.getWriterProvider(source, process).setBiometric(id, fieldName, biometricRecord); } /** @@ -89,7 +84,7 @@ public void setBiometric(String id, String fieldName, BiometricRecord biometricR public void setDocument(String id, String documentName, Document document, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "setDocument for field name : " + documentName + " source : " + source + " process : " + process); - getProvider(source, process).setDocument(id, documentName, document); + providerRegistry.getWriterProvider(source, process).setDocument(id, documentName, document); } /** @@ -101,7 +96,7 @@ public void setDocument(String id, String documentName, Document document, Strin public void addMetaInfo(String id, Map metaInfo, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "setMetaInfo for source : " + source + " process : " + process); - getProvider(source, process).addMetaInfo(id, metaInfo); + providerRegistry.getWriterProvider(source, process).addMetaInfo(id, metaInfo); } /** @@ -114,7 +109,7 @@ public void addMetaInfo(String id, Map metaInfo, String source, public void addMetaInfo(String id, String key, String value, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "setMetaInfo for source : " + source + " process : " + process); - getProvider(source, process).addMetaInfo(id, key, value); + providerRegistry.getWriterProvider(source, process).addMetaInfo(id, key, value); } /** @@ -128,7 +123,7 @@ public void addMetaInfo(String id, String key, String value, String source, Stri public void addAudits(String id, List> audits, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "setAudits for source : " + source + " process : " + process); - getProvider(source, process).addAudits(id, audits); + providerRegistry.getWriterProvider(source, process).addAudits(id, audits); } /** @@ -142,7 +137,7 @@ public void addAudits(String id, List> audits, String source public void addAudit(String id, Map audit, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "setAudits for source : " + source + " process : " + process); - getProvider(source, process).addAudit(id, audit); + providerRegistry.getWriterProvider(source, process).addAudit(id, audit); } /** @@ -157,14 +152,14 @@ public List persistPacket(String id, String version, String schemaJs String process, String additionalInfoReqId, String refId, boolean offlineMode) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "persistPacket for source : " + source + " process : " + process); - return getProvider(source, process).persistPacket(id, version, schemaJson, source, process, additionalInfoReqId, refId, offlineMode); + return providerRegistry.getWriterProvider(source, process).persistPacket(id, version, schemaJson, source, process, additionalInfoReqId, refId, offlineMode); } public List createPacket(PacketDto packetDto) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, packetDto.getId(), "createPacket for RID : " + packetDto.getId() + " source : " + packetDto.getSource() + " process : " + packetDto.getProcess()); List packetInfos = null; - IPacketWriter provider = getProvider(packetDto.getSource(), packetDto.getProcess()); + IPacketWriter provider = providerRegistry.getWriterProvider(packetDto.getSource(), packetDto.getProcess()); try { if (packetDto.getFields() != null) provider.setFields(packetDto.getId(), packetDto.getFields()); @@ -176,11 +171,13 @@ public List createPacket(PacketDto packetDto) { provider.addAudits(packetDto.getId(), packetDto.getAudits()); if (packetDto.getBiometrics() != null) packetDto.getBiometrics().entrySet().forEach(bio -> provider.setBiometric(packetDto.getId(), bio.getKey(), bio.getValue())); + packetInfos = provider.persistPacket(packetDto.getId(), packetDto.getSchemaVersion(), packetDto.getSchemaJson(), packetDto.getSource(), packetDto.getProcess(), packetDto.getAdditionalInfoReqId(), packetDto.getRefId(), packetDto.isOfflineMode()); } catch (Exception e) { + e.printStackTrace(); LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, packetDto.getId(), ExceptionUtils.getStackTrace(e)); LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, packetDto.getId(), ExceptionUtils.getStackTrace(e)); @@ -191,31 +188,6 @@ public List createPacket(PacketDto packetDto) { return packetInfos; } - /** - * Get the packet writer provider instance for source and process - * - * @param source : the source packet. Default if not provided. - * @param process : the process - * @return IPacketWriter : the provider instance - */ - private IPacketWriter getProvider(String source, String process) { - IPacketWriter provider = null; - if (referenceWriterProviders != null && !referenceWriterProviders.isEmpty()) { - Optional refProvider = referenceWriterProviders.stream().filter(refPr -> - (PacketHelper.isSourceAndProcessPresent(refPr.getClass().getName(), source, process, PacketHelper.Provider.WRITER))).findAny(); - if (refProvider.isPresent() && refProvider.get() != null) - provider = refProvider.get(); - } - - if (provider == null) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, - "No available provider found for source : " + source + " process : " + process); - throw new NoAvailableProviderException(); - } - - return provider; - } - @CacheEvict(value = "tags", key = "{#p1}") public Map addTags(TagDto tagDto,String id) { Map tags = packetKeeper.addTags(tagDto); @@ -232,4 +204,4 @@ public Map addorUpdate(TagDto tagDto,String id) { public void deleteTags(TagRequestDto tagDto, String id) { packetKeeper.deleteTags(tagDto); } -} +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketWriterProviderRegistry.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketWriterProviderRegistry.java new file mode 100644 index 0000000000..0dfc2e7542 --- /dev/null +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/facade/PacketWriterProviderRegistry.java @@ -0,0 +1,55 @@ +package io.mosip.commons.packet.facade; + +import io.mosip.commons.packet.exception.NoAvailableProviderException; +import io.mosip.commons.packet.spi.IPacketWriter; +import io.mosip.commons.packet.util.PacketHelper; +import io.mosip.commons.packet.util.PacketManagerLogger; +import io.mosip.kernel.core.logger.spi.Logger; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +@Component +public class PacketWriterProviderRegistry { + private static final Logger LOGGER = PacketManagerLogger.getLogger(PacketWriterProviderRegistry.class); + + private final List referenceWriterProviders; + private final Map providerCache = new ConcurrentHashMap<>(); + private static final String UNDERSCORE = "_"; + + public PacketWriterProviderRegistry(@Qualifier("referenceWriterProviders") @Lazy List referenceWriterProviders) { + this.referenceWriterProviders = referenceWriterProviders; + } + + public IPacketWriter getWriterProvider(String source, String process) { + String cacheKey = source + UNDERSCORE + process; + + return providerCache.computeIfAbsent(cacheKey, key -> { + Optional provider = referenceWriterProviders.stream() + .filter(pr -> PacketHelper.isSourceAndProcessPresent( + pr.getClass().getName(), source, process, PacketHelper.Provider.WRITER)) + .findFirst(); + + if (provider.isEmpty()) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, + "No available IPacketWriter provider for source={} and process={}", source, process); + throw new NoAvailableProviderException(); + } + + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, + "Cached IPacketWriter for source={} and process={}", source, process); + return provider.get(); + }); + } + + public void clearCache() { + providerCache.clear(); + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, + "Writer provider cache cleared"); + } +} \ No newline at end of file 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 73e7a4b843..e85c76018f 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 @@ -1,8 +1,16 @@ package io.mosip.commons.packet.impl; +import java.security.SecureRandom; +import java.util.Arrays; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; + import io.mosip.commons.khazana.util.EncryptionUtil; import io.mosip.commons.packet.constants.CryptomanagerConstant; -import io.mosip.commons.packet.exception.PacketDecryptionFailureException; import io.mosip.commons.packet.spi.IPacketCryptoService; import io.mosip.kernel.clientcrypto.dto.TpmSignRequestDto; import io.mosip.kernel.clientcrypto.dto.TpmSignVerifyRequestDto; @@ -12,20 +20,7 @@ import io.mosip.kernel.core.util.DateUtils; import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; import io.mosip.kernel.cryptomanager.service.CryptomanagerService; -import io.mosip.kernel.cryptomanager.service.impl.CryptomanagerServiceImpl; -import io.mosip.kernel.signature.dto.TimestampRequestDto; import io.mosip.kernel.signature.service.SignatureService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; - -import java.nio.charset.StandardCharsets; -import java.security.SecureRandom; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Arrays; @Component @Qualifier("OfflinePacketCryptoServiceImpl") @@ -42,21 +37,23 @@ public class OfflinePacketCryptoServiceImpl implements IPacketCryptoService { /** * The cryptomanager service. */ - private CryptomanagerService cryptomanagerService = null; + private volatile CryptomanagerService cryptomanagerService = null; /** * The key manager. */ - private SignatureService signatureService = null; + private volatile SignatureService signatureService = null; /** * The key manager. */ - private ClientCryptoManagerService tpmCryptoService = null; + private volatile ClientCryptoManagerService tpmCryptoService = null; @Value("${crypto.PrependThumbprint.enable:true}") private boolean isPrependThumbprintEnabled; + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + @Override public byte[] sign(byte[] packet) { TpmSignRequestDto signRequest = new TpmSignRequestDto(); @@ -66,17 +63,15 @@ public byte[] sign(byte[] packet) { @Override public byte[] encrypt(String refId, byte[] packet) { - String packetString = CryptoUtil.encodeToURLSafeBase64(packet); + byte[] nonce = new byte[CryptomanagerConstant.GCM_NONCE_LENGTH]; + byte[] aad = new byte[CryptomanagerConstant.GCM_AAD_LENGTH]; + SECURE_RANDOM.nextBytes(nonce); + SECURE_RANDOM.nextBytes(aad); + CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); cryptomanagerRequestDto.setApplicationId(APPLICATION_ID); - cryptomanagerRequestDto.setData(packetString); cryptomanagerRequestDto.setReferenceId(refId); - - 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.setData(CryptoUtil.encodeToURLSafeBase64(packet)); cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); @@ -116,20 +111,32 @@ public boolean verify(String machineId, byte[] packet, byte[] signature) { } private CryptomanagerService getCryptomanagerService() { - if (cryptomanagerService == null) - cryptomanagerService = applicationContext.getBean(CryptomanagerServiceImpl.class); + if (cryptomanagerService == null) { + synchronized (this) { + if (cryptomanagerService == null) + cryptomanagerService = applicationContext.getBean(CryptomanagerService.class); + } + } return cryptomanagerService; } private SignatureService getSignatureService() { - if (signatureService == null) - signatureService = applicationContext.getBean(SignatureService.class); + if (signatureService == null) { + synchronized (this) { + if (signatureService == null) + signatureService = applicationContext.getBean(SignatureService.class); + } + } return signatureService; } private ClientCryptoManagerService getTpmCryptoService() { - if (tpmCryptoService == null) - tpmCryptoService = applicationContext.getBean(ClientCryptoManagerService.class); + if (tpmCryptoService == null) { + synchronized (this) { + if (tpmCryptoService == null) + tpmCryptoService = applicationContext.getBean(ClientCryptoManagerService.class); + } + } return tpmCryptoService; } } \ No newline at end of file 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 d2c5399601..b44b2bb272 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 @@ -1,6 +1,27 @@ package io.mosip.commons.packet.impl; +import java.io.IOException; +import java.security.SecureRandom; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Arrays; +import java.util.LinkedHashMap; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + import com.fasterxml.jackson.databind.ObjectMapper; + import io.mosip.commons.khazana.util.EncryptionUtil; import io.mosip.commons.packet.constants.CryptomanagerConstant; import io.mosip.commons.packet.dto.TpmSignVerifyRequestDto; @@ -18,299 +39,276 @@ import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.CryptoUtil; import io.mosip.kernel.core.util.DateUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; -import org.springframework.web.client.RestClientException; -import org.springframework.web.client.RestTemplate; - -import java.io.IOException; -import java.security.SecureRandom; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.Arrays; -import java.util.LinkedHashMap; @Component @Qualifier("OnlinePacketCryptoServiceImpl") public class OnlinePacketCryptoServiceImpl implements IPacketCryptoService { - private static Logger LOGGER = PacketManagerLogger.getLogger(OnlinePacketCryptoServiceImpl.class); - - /** - * The Constant APPLICATION_ID. - */ - public static final String APPLICATION_ID = "REGISTRATION"; - private static final String DECRYPT_SERVICE_ID = "mosip.cryptomanager.decrypt"; - private static final String IO_EXCEPTION = "Exception while reading packet inputStream"; - private static final String DATE_TIME_EXCEPTION = "Error while parsing packet timestamp"; - - @Value("${mosip.utc-datetime-pattern:yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}") - private String DATETIME_PATTERN; - - @Value("${mosip.kernel.cryptomanager.request_version:v1}") - private String APPLICATION_VERSION; - - @Value("${CRYPTOMANAGER_DECRYPT:null}") - private String cryptomanagerDecryptUrl; - - @Value("${crypto.PrependThumbprint.enable:true}") - private boolean isPrependThumbprintEnabled; - - @Autowired - @Qualifier("selfTokenRestTemplate") - private RestTemplate restTemplate; - - @Autowired - private ObjectMapper mapper; - - @Value("${CRYPTOMANAGER_ENCRYPT:null}") - private String cryptomanagerEncryptUrl; - - @Value("${mosip.kernel.keymanager-service-CsSign-url:null}") - private String keymanagerCsSignUrl; - - @Value("${mosip.kernel.keymanager-service-csverifysign-url:null}") - private String keymanagerCsverifysignUrl; - - @Value("${mosip.kernel.syncdata-service-get-tpm-publicKey-url:null}") - private String syncdataGetTpmKeyUrl; - - @Override - public byte[] sign(byte[] packet) { - try { - - TpmSignRequestDto dto = new TpmSignRequestDto(); - dto.setData(CryptoUtil.encodeToURLSafeBase64(packet)); - RequestWrapper request = new RequestWrapper<>(); - request.setRequest(dto); - request.setMetadata(null); - DateTimeFormatter format = DateTimeFormatter.ofPattern(DATETIME_PATTERN); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(DATETIME_PATTERN), format); - request.setRequesttime(localdatetime); - HttpEntity> httpEntity = new HttpEntity<>(request); - ResponseEntity response = restTemplate.exchange(keymanagerCsSignUrl, HttpMethod.POST, httpEntity, - String.class); - LinkedHashMap responseMap = (LinkedHashMap) mapper.readValue(response.getBody(), LinkedHashMap.class).get("response"); - if (responseMap != null && responseMap.size() > 0) - return CryptoUtil.decodeURLSafeBase64((String) responseMap.get("data")); - else - throw new SignatureException(); - } catch (IOException e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, - ExceptionUtils.getStackTrace(e)); - throw new SignatureException(e); - } - } - - @Override - public byte[] encrypt(String refId, byte[] packet) { - byte[] encryptedPacket = null; - - try { - String packetString = CryptoUtil.encodeToURLSafeBase64(packet); - CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); - RequestWrapper request = new RequestWrapper<>(); - 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.encodeToURLSafeBase64(aad)); - cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); - cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); - - request.setId(DECRYPT_SERVICE_ID); - request.setMetadata(null); - request.setRequest(cryptomanagerRequestDto); - DateTimeFormatter format = DateTimeFormatter.ofPattern(DATETIME_PATTERN); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(DATETIME_PATTERN), format); - request.setRequesttime(localdatetime); - request.setVersion(APPLICATION_VERSION); - HttpEntity> httpEntity = new HttpEntity<>(request); - - ResponseEntity response = restTemplate.exchange(cryptomanagerEncryptUrl, HttpMethod.POST, httpEntity, String.class); - CryptomanagerResponseDto responseObject = mapper.readValue(response.getBody(), CryptomanagerResponseDto.class); - if (responseObject != null && - responseObject.getErrors() != null && !responseObject.getErrors().isEmpty()) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - "Packet encryption failed"); - ServiceError error = responseObject.getErrors().get(0); - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - "Packet encryption failure message : " + error.getMessage()); - throw new PacketDecryptionFailureException(error.getMessage()); - } - if (responseObject != null && responseObject.getResponse().getData() != null) { + private static Logger LOGGER = PacketManagerLogger.getLogger(OnlinePacketCryptoServiceImpl.class); + + /** + * The Constant APPLICATION_ID. + */ + public static final String APPLICATION_ID = "REGISTRATION"; + private static final String DECRYPT_SERVICE_ID = "mosip.cryptomanager.decrypt"; + private static final String IO_EXCEPTION = "Exception while reading packet inputStream"; + private static final String DATE_TIME_EXCEPTION = "Error while parsing packet timestamp"; + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + private static final String SPLIT_UNDERSCORE = "_"; + + @Value("${mosip.utc-datetime-pattern:yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}") + private String DATETIME_PATTERN; + + @Value("${mosip.kernel.cryptomanager.request_version:v1}") + private String APPLICATION_VERSION; + + @Value("${CRYPTOMANAGER_DECRYPT:null}") + private String cryptomanagerDecryptUrl; + + @Value("${crypto.PrependThumbprint.enable:true}") + private boolean isPrependThumbprintEnabled; + + @Autowired + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + + @Autowired + private ObjectMapper mapper; + + @Value("${CRYPTOMANAGER_ENCRYPT:null}") + private String cryptomanagerEncryptUrl; + + @Value("${mosip.kernel.keymanager-service-CsSign-url:null}") + private String keymanagerCsSignUrl; + + @Value("${mosip.kernel.keymanager-service-csverifysign-url:null}") + private String keymanagerCsverifysignUrl; + + @Value("${mosip.kernel.syncdata-service-get-tpm-publicKey-url:null}") + private String syncdataGetTpmKeyUrl; + + @Override + public byte[] sign(byte[] packet) { + try { + TpmSignRequestDto dto = new TpmSignRequestDto(); + dto.setData(CryptoUtil.encodeToURLSafeBase64(packet)); + + RequestWrapper request = new RequestWrapper<>(); + request.setRequest(dto); + request.setMetadata(null); + request.setRequesttime(getCurrentUtcDateTime()); + HttpEntity> httpEntity = new HttpEntity<>(request); + ResponseEntity response = restTemplate.exchange(keymanagerCsSignUrl, HttpMethod.POST, httpEntity, + String.class); + LinkedHashMap responseMap = (LinkedHashMap) mapper.readValue(response.getBody(), LinkedHashMap.class) + .get("response"); + if (responseMap != null && responseMap.size() > 0) + return CryptoUtil.decodeURLSafeBase64((String) responseMap.get("data")); + throw new SignatureException(); + } catch (IOException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, + ExceptionUtils.getStackTrace(e)); + throw new SignatureException(e); + } + } + + @Override + public byte[] encrypt(String refId, byte[] packet) { + try { + byte[] nonce = new byte[CryptomanagerConstant.GCM_NONCE_LENGTH]; + byte[] aad = new byte[CryptomanagerConstant.GCM_AAD_LENGTH]; + SECURE_RANDOM.nextBytes(nonce); + SECURE_RANDOM.nextBytes(aad); + + CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); + cryptomanagerRequestDto.setApplicationId(APPLICATION_ID); + cryptomanagerRequestDto.setReferenceId(refId); + cryptomanagerRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(packet)); + cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); + cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); + cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); + cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); + + RequestWrapper request = new RequestWrapper<>(); + request.setId(DECRYPT_SERVICE_ID); + request.setVersion(APPLICATION_VERSION); + request.setMetadata(null); + request.setRequest(cryptomanagerRequestDto); + request.setRequesttime(getCurrentUtcDateTime()); + + HttpEntity> httpEntity = new HttpEntity<>(request); + + ResponseEntity response = restTemplate.exchange(cryptomanagerEncryptUrl, HttpMethod.POST, + httpEntity, String.class); + CryptomanagerResponseDto responseObject = mapper.readValue(response.getBody(), + CryptomanagerResponseDto.class); + if (responseObject != null && responseObject.getErrors() != null && !responseObject.getErrors().isEmpty()) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + "Packet encryption failed"); + ServiceError error = responseObject.getErrors().get(0); + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + "Packet encryption failure message : " + error.getMessage()); + throw new PacketDecryptionFailureException(error.getMessage()); + } + if (responseObject != null && responseObject.getResponse().getData() != null) { byte[] encryptedData = CryptoUtil.decodeURLSafeBase64(responseObject.getResponse().getData()); - encryptedPacket = EncryptionUtil.mergeEncryptedData(encryptedData, nonce, aad); + byte[] encryptedPacket = EncryptionUtil.mergeEncryptedData(encryptedData, nonce, aad); LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, "Successfully encrypted Packet"); + return encryptedPacket; } - } catch (IOException e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - ExceptionUtils.getStackTrace(e)); - throw new PacketDecryptionFailureException(IO_EXCEPTION, e); - } catch (DateTimeParseException e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - ExceptionUtils.getStackTrace(e)); - throw new PacketDecryptionFailureException(DATE_TIME_EXCEPTION); - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - ExceptionUtils.getStackTrace(e)); - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - throw new ApiNotAccessibleException(httpClientException.getResponseBodyAsString()); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - throw new ApiNotAccessibleException(httpServerException.getResponseBodyAsString()); - } else { - throw new PacketDecryptionFailureException(e); - } - - } - return encryptedPacket; - } - - @Override - public byte[] decrypt(String refId, byte[] packet) { - byte[] decryptedPacket = null; - - try { - CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); - RequestWrapper request = new RequestWrapper<>(); - cryptomanagerRequestDto.setApplicationId(APPLICATION_ID); - cryptomanagerRequestDto.setReferenceId(refId); - byte[] nonce = Arrays.copyOfRange(packet, 0, CryptomanagerConstant.GCM_NONCE_LENGTH); - byte[] aad = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH, - CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH); - byte[] encryptedData = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH, - packet.length); - cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); - cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); - cryptomanagerRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(encryptedData)); - cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); - cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); - - request.setId(DECRYPT_SERVICE_ID); - request.setMetadata(null); - request.setRequest(cryptomanagerRequestDto); - DateTimeFormatter format = DateTimeFormatter.ofPattern(DATETIME_PATTERN); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(DATETIME_PATTERN), format); - request.setRequesttime(localdatetime); - request.setVersion(APPLICATION_VERSION); - HttpEntity> httpEntity = new HttpEntity<>(request); - - ResponseEntity response = restTemplate.exchange(cryptomanagerDecryptUrl, HttpMethod.POST, httpEntity, String.class); - - CryptomanagerResponseDto responseObject = mapper.readValue(response.getBody(), CryptomanagerResponseDto.class); - - if (responseObject != null && - responseObject.getErrors() != null && !responseObject.getErrors().isEmpty()) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - "Packet decryption failed"); - ServiceError error = responseObject.getErrors().get(0); - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - "Error message : " + error.getMessage()); - throw new PacketDecryptionFailureException(error.getMessage()); - } - + throw new PacketDecryptionFailureException("Packet encrypted failed"); + } catch (IOException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + ExceptionUtils.getStackTrace(e)); + throw new PacketDecryptionFailureException(IO_EXCEPTION, e); + } catch (DateTimeParseException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + ExceptionUtils.getStackTrace(e)); + throw new PacketDecryptionFailureException(DATE_TIME_EXCEPTION); + } catch (Exception e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + ExceptionUtils.getStackTrace(e)); + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + throw new ApiNotAccessibleException(httpClientException.getResponseBodyAsString()); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + throw new ApiNotAccessibleException(httpServerException.getResponseBodyAsString()); + } else { + throw new PacketDecryptionFailureException(e); + } + } + } + + @Override + public byte[] decrypt(String refId, byte[] packet) { + try { + byte[] nonce = Arrays.copyOfRange(packet, 0, CryptomanagerConstant.GCM_NONCE_LENGTH); + byte[] aad = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH, + CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH); + byte[] encryptedData = Arrays.copyOfRange(packet, + CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH, packet.length); + + CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); + cryptomanagerRequestDto.setApplicationId(APPLICATION_ID); + cryptomanagerRequestDto.setReferenceId(refId); + cryptomanagerRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(encryptedData)); + cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); + cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); + cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); + cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); + + RequestWrapper request = new RequestWrapper<>(); + request.setId(DECRYPT_SERVICE_ID); + request.setVersion(APPLICATION_VERSION); + request.setMetadata(null); + request.setRequest(cryptomanagerRequestDto); + request.setRequesttime(getCurrentUtcDateTime()); + + HttpEntity> httpEntity = new HttpEntity<>(request); + ResponseEntity response = restTemplate.exchange(cryptomanagerDecryptUrl, HttpMethod.POST, + httpEntity, String.class); + + CryptomanagerResponseDto responseObject = mapper.readValue(response.getBody(), + CryptomanagerResponseDto.class); + + if (responseObject != null && responseObject.getErrors() != null && !responseObject.getErrors().isEmpty()) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + "Packet decryption failed"); + ServiceError error = responseObject.getErrors().get(0); + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + "Error message : " + error.getMessage()); + throw new PacketDecryptionFailureException(error.getMessage()); + } + if (responseObject != null && responseObject.getResponse().getData() != null) { - decryptedPacket = CryptoUtil.decodeURLSafeBase64(responseObject.getResponse().getData()); + byte[] decryptedPacket = CryptoUtil.decodeURLSafeBase64(responseObject.getResponse().getData()); LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, "Successfully decrypted Packet"); + return decryptedPacket; } - } catch (IOException e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - ExceptionUtils.getStackTrace(e)); - throw new PacketDecryptionFailureException(IO_EXCEPTION, e); - } catch (DateTimeParseException e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - ExceptionUtils.getStackTrace(e)); - throw new PacketDecryptionFailureException(DATE_TIME_EXCEPTION); - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - ExceptionUtils.getStackTrace(e)); - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - throw new ApiNotAccessibleException(httpClientException.getResponseBodyAsString()); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - throw new ApiNotAccessibleException(httpServerException.getResponseBodyAsString()); - } else { - throw new PacketDecryptionFailureException(e); - } - - } - return decryptedPacket; - } - - @Override - public boolean verify(String refId, byte[] packet, byte[] signature) { - try { - String publicKey=getPublicKey(refId); - TpmSignVerifyRequestDto dto = new TpmSignVerifyRequestDto(); - dto.setData(CryptoUtil.encodeToURLSafeBase64(packet)); - dto.setSignature(CryptoUtil.encodeToURLSafeBase64(signature)); - dto.setPublicKey(publicKey); - RequestWrapper request = new RequestWrapper<>(); - request.setRequest(dto); - request.setMetadata(null); - DateTimeFormatter format = DateTimeFormatter.ofPattern(DATETIME_PATTERN); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(DATETIME_PATTERN), format); - request.setRequesttime(localdatetime); - HttpEntity> httpEntity = new HttpEntity<>(request); - 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) { - 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) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, - ExceptionUtils.getStackTrace(e)); - throw new SignatureException(e); - } catch( RestClientException e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, - ExceptionUtils.getStackTrace(e)); - throw new SignatureException(e); - } - } + throw new PacketDecryptionFailureException("Packet decrypted failed"); + } catch (IOException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + ExceptionUtils.getStackTrace(e)); + throw new PacketDecryptionFailureException(IO_EXCEPTION, e); + } catch (DateTimeParseException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + ExceptionUtils.getStackTrace(e)); + throw new PacketDecryptionFailureException(DATE_TIME_EXCEPTION); + } catch (Exception e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + ExceptionUtils.getStackTrace(e)); + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + throw new ApiNotAccessibleException(httpClientException.getResponseBodyAsString()); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + throw new ApiNotAccessibleException(httpServerException.getResponseBodyAsString()); + } else { + throw new PacketDecryptionFailureException(e); + } + } + } + + @Override + public boolean verify(String refId, byte[] packet, byte[] signature) { + try { + String publicKey = getPublicKey(refId); + TpmSignVerifyRequestDto dto = new TpmSignVerifyRequestDto(); + dto.setData(CryptoUtil.encodeToURLSafeBase64(packet)); + dto.setSignature(CryptoUtil.encodeToURLSafeBase64(signature)); + dto.setPublicKey(publicKey); + + RequestWrapper request = new RequestWrapper<>(); + request.setRequest(dto); + request.setMetadata(null); + request.setRequesttime(getCurrentUtcDateTime()); + + HttpEntity> httpEntity = new HttpEntity<>(request); + 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) { + 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; + } + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + "Failed to verify signature. Received error response from keymanager verify API."); + throw new SignatureException(); + } catch (IOException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, + ExceptionUtils.getStackTrace(e)); + throw new SignatureException(e); + } catch (RestClientException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, null, + ExceptionUtils.getStackTrace(e)); + throw new SignatureException(e); + } + } 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"); - else { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, - "Failed to get public key. Error Response : " + response.getBody()); - throw new SignatureException(); - } + String machineId = refId.split(SPLIT_UNDERSCORE)[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"); + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REFERENCEID, refId, + "Failed to get public key. Error Response : " + response.getBody()); + throw new SignatureException("Failed to retrieve TPM public key"); + } + + private LocalDateTime getCurrentUtcDateTime() { + return LocalDateTime.parse(DateUtils.getUTCCurrentDateTimeString(DATETIME_PATTERN), + DateTimeFormatter.ofPattern(DATETIME_PATTERN)); } -} +} \ No newline at end of file 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 90811dd75f..ffbd47bcc8 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 @@ -9,21 +9,16 @@ import static io.mosip.commons.packet.constants.PacketManagerConstants.TYPE; import static io.mosip.commons.packet.constants.PacketManagerConstants.VALUE; -import java.io.IOException; import java.io.InputStream; -import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.node.ObjectNode; -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; import org.apache.commons.collections4.ListUtils; import org.apache.commons.io.IOUtils; @@ -31,7 +26,6 @@ import org.apache.commons.lang3.StringUtils; import org.assertj.core.util.Lists; import org.json.JSONArray; -import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -40,34 +34,32 @@ import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; +import com.nimbusds.jose.util.StandardCharset; -import io.mosip.commons.packet.constants.PacketManagerConstants; import io.mosip.commons.packet.dto.Document; import io.mosip.commons.packet.dto.Packet; import io.mosip.commons.packet.dto.PacketInfo; -import io.mosip.commons.packet.exception.ApiNotAccessibleException; import io.mosip.commons.packet.exception.GetAllIdentityException; import io.mosip.commons.packet.exception.GetAllMetaInfoException; import io.mosip.commons.packet.exception.GetBiometricException; import io.mosip.commons.packet.exception.GetDocumentException; -import io.mosip.commons.packet.exception.PacketDecryptionFailureException; -import io.mosip.commons.packet.exception.PacketKeeperException; import io.mosip.commons.packet.exception.PacketValidationFailureException; +import io.mosip.commons.packet.facade.PacketReader; 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.PacketManagerHelper; import io.mosip.commons.packet.util.PacketManagerLogger; 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.entities.BIR; import io.mosip.kernel.biometrics.entities.BiometricRecord; import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.kernel.core.exception.BaseUncheckedException; import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; - +import io.mosip.kernel.core.util.JsonUtils; @RefreshScope @Component @@ -125,79 +117,53 @@ public boolean validatePacket(String id, String source, String process) { * @return */ @Override - @Cacheable(value = "packet", key="{'allFields'.concat('-').concat(#p0).concat('-').concat(#p2)}") + @Cacheable(value = "packet", key = "{'allFields'.concat('-').concat(#p0).concat('-').concat(#p2)}") public Map getAll(String id, String source, String process) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "Getting all fields :: enrtry"); + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "Getting all fields"); Map finalMap = new LinkedHashMap<>(); - String[] sourcePacketNames = packetNames.split(","); + for (String srcPacket : packetNames.split(",")) { + try (InputStream idJsonStream = ZipUtils.unzipAndGetFile( + packetKeeper.getPacket(getPacketInfo(id, srcPacket, source, process)).getPacket(), "ID")) { + if (idJsonStream != null) { + LinkedHashMap idMap = (LinkedHashMap) mapper + .readValue(new String(IOUtils.toByteArray(idJsonStream), StandardCharset.UTF_8), LinkedHashMap.class).get(IDENTITY); + for (Map.Entry entry : idMap.entrySet()) { + finalMap.putIfAbsent(entry.getKey(), normalize(entry.getValue())); + } + } + } catch (Exception e) { + handleException(e); + } + } + return finalMap; + } + private Object normalize(Object value) { + if (value == null) + return null; + if (value instanceof Number || value instanceof String) + return value.toString().replaceAll("(^\")|(\"$)", ""); try { - for (String srcPacket : sourcePacketNames) { - Packet packet = packetKeeper.getPacket(getPacketInfo(id, srcPacket, 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); - - currentIdMap.keySet().stream().forEach(key -> { - Object value = currentIdMap.get(key); - if (value != null && (value instanceof Number)) - finalMap.putIfAbsent(key, value); - else if (value != null && (value instanceof String)) - finalMap.putIfAbsent(key, value.toString().replaceAll("(^\")|(\"$)", "")); - else { - try { - finalMap.putIfAbsent(key, - value != null ? JsonUtils.javaObjectToJsonString(currentIdMap.get(key)) : null); - } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { - LOGGER.error(ExceptionUtils.getStackTrace(e)); - throw new GetAllIdentityException(e.getMessage()); - } - } - }); - } - } - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - ExceptionUtils.getStackTrace(e)); - if (e instanceof BaseCheckedException) { - BaseCheckedException ex = (BaseCheckedException) e; - throw new GetAllIdentityException(ex.getErrorCode(), ex.getErrorText()); - } else if (e instanceof BaseUncheckedException) { - BaseUncheckedException ex = (BaseUncheckedException) e; - throw new GetAllIdentityException(ex.getErrorCode(), ex.getErrorText()); - } - throw new GetAllIdentityException(e.getMessage()); - } - - return finalMap; + return JsonUtils.javaObjectToJsonString(value); + } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { + throw new GetAllIdentityException(e.getMessage()); + } } @Override public String getField(String id, String field, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "getField :: for - " + field); - Map allFields = getAll(id, source, process); - if (allFields != null) { - Object fieldObj = allFields.get(field); - return fieldObj != null ? fieldObj.toString() : null; - } - return null; + return Optional.ofNullable(getAll(id, source, process).get(field)).map(Object::toString).orElse(null); } @Override public Map getFields(String id, List fields, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "getFields :: for - " + fields.toString()); - Map result = new HashMap<>(); Map allFields = getAll(id, source, process); - fields.stream().forEach( - field -> result.put(field, allFields.get(field) != null ? allFields.get(field).toString() : null)); - - return result; + return fields.stream().collect(Collectors.toMap(f -> f, + f -> Optional.ofNullable(allFields.get(f)).map(Object::toString).orElse(null))); } @Override @@ -205,23 +171,22 @@ public Document getDocument(String id, String documentName, String source, Strin LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "getDocument :: for - " + 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); + String versionStr = packetReader.getField(id, idSchemaUtils.getIdschemaVersionFromMappingJson(), source, + process, false); + String docStr = packetReader.getField(id, documentName, source, process, false); + if (docStr != null && versionStr != null) { + JSONObject docJson = new JSONObject(docStr); + String packetName = idSchemaUtils.getSource(documentName, Double.valueOf(versionStr)); Packet packet = packetKeeper.getPacket(getPacketInfo(id, packetName, source, process)); - String value = documentMap.has(VALUE) ? documentMap.get(VALUE).toString() : null; - InputStream documentStream = ZipUtils.unzipAndGetFile(packet.getPacket(), value); - if (documentStream != null) { - Document document = new Document(); - document.setDocument(IOUtils.toByteArray(documentStream)); - document.setValue(value); - 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; + InputStream docStream = ZipUtils.unzipAndGetFile(packet.getPacket(), docJson.optString(VALUE)); + if (docStream != null) { + Document doc = new Document(); + doc.setDocument(IOUtils.toByteArray(docStream)); + doc.setValue(docJson.optString(VALUE)); + doc.setType(docJson.optString(TYPE)); + doc.setFormat(docJson.optString(FORMAT)); + doc.setRefNumber(docJson.optString(REFNUMBER)); + return doc; } } } catch (Exception e) { @@ -233,111 +198,75 @@ public Document getDocument(String id, String documentName, String source, Strin } @Override - public BiometricRecord getBiometric(String id, String biometricFieldName, List modalities, String source, - String process) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "getBiometric :: for - " + biometricFieldName); - BiometricRecord biometricRecord = null; - String packetName = null; - String fileName = null; - try { - String bioString = packetReader.getField(id, biometricFieldName, source, process, false);//(String) idobjectMap.get(biometricFieldName); - JSONObject biometricMap = null; - if (bioString != null) - biometricMap = new JSONObject(bioString); - if (bioString == null || biometricMap == null || biometricMap.isNull(VALUE)) { - // biometric file not present in idobject. Search in meta data. - Map metadataMap = getMetaInfo(id, source, process); - String operationsData = metadataMap.get(META_INFO_OPERATIONS_DATA); - if (StringUtils.isNotEmpty(operationsData)) { - JSONArray jsonArray = new JSONArray(operationsData); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject jsonObject = (JSONObject) jsonArray.get(i); - if (jsonObject.has(LABEL) - && jsonObject.get(LABEL).toString().equalsIgnoreCase(biometricFieldName)) { - packetName = ID; - fileName = jsonObject.isNull(VALUE) ? null : jsonObject.get(VALUE).toString(); - break; - } - } - } - } else { - String idSchemaVersion = packetReader.getField(id, - idSchemaUtils.getIdschemaVersionFromMappingJson(), source, process, false); - Double schemaVersion = idSchemaVersion != null ? Double.valueOf(idSchemaVersion) : null; - packetName = idSchemaUtils.getSource(biometricFieldName, schemaVersion); - fileName = biometricMap.get(VALUE).toString(); - } - - if (packetName == null || fileName == null) - return null; - - Packet packet = packetKeeper.getPacket(getPacketInfo(id, packetName, source, process)); - InputStream biometrics = ZipUtils.unzipAndGetFile(packet.getPacket(), fileName); - if (biometrics == null) - return null; - BIR bir = CbeffValidator.getBIRFromXML(IOUtils.toByteArray(biometrics)); - biometricRecord = new BiometricRecord(); - if(bir.getOthers() != null) { - HashMap others = new HashMap<>(); - bir.getOthers().entrySet().forEach(e -> { - others.put(e.getKey(), e.getValue()); - }); - biometricRecord.setOthers(others); - } - biometricRecord.setSegments(filterByModalities(modalities, bir.getBirs())); - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - ExceptionUtils.getStackTrace(e)); - if (e instanceof BaseCheckedException) { - BaseCheckedException ex = (BaseCheckedException) e; - throw new GetBiometricException(ex.getErrorCode(), ex.getMessage()); - } else if (e instanceof BaseUncheckedException) { - BaseUncheckedException ex = (BaseUncheckedException) e; - throw new GetBiometricException(ex.getErrorCode(), ex.getMessage()); - } - throw new GetBiometricException(e.getMessage()); - } + public BiometricRecord getBiometric(String id, String biometricFieldName, List modalities, String source, + String process) { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "getBiometric :: for - " + biometricFieldName); + try { + String bioStr = packetReader.getField(id, biometricFieldName, source, process, false); + JSONObject bioJson = bioStr != null ? new JSONObject(bioStr) : null; + String packetName = null, fileName = null; + + if (bioJson == null || bioJson.isNull(VALUE)) { + String operationsData = getMetaInfo(id, source, process).get(META_INFO_OPERATIONS_DATA); + if (StringUtils.isNotEmpty(operationsData)) { + JSONArray jsonArray = new JSONArray(operationsData); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject obj = jsonArray.getJSONObject(i); + if (biometricFieldName.equalsIgnoreCase(obj.optString(LABEL))) { + packetName = ID; + fileName = obj.optString(VALUE); + break; + } + } + } + } else { + String idSchemaVersion = packetReader.getField(id, idSchemaUtils.getIdschemaVersionFromMappingJson(), source, + process, false); + Double schemaVersion = idSchemaVersion != null ? Double.valueOf(idSchemaVersion) : null; + packetName = idSchemaUtils.getSource(biometricFieldName, schemaVersion); + fileName = bioJson.optString(VALUE); + } - return biometricRecord; - } + if (packetName == null || fileName == null) + return null; + InputStream stream = ZipUtils.unzipAndGetFile( + packetKeeper.getPacket(getPacketInfo(id, packetName, source, process)).getPacket(), fileName); + if (stream == null) + return null; + + BIR bir = CbeffValidator.getBIRFromXML(IOUtils.toByteArray(stream)); + BiometricRecord record = new BiometricRecord(); + if (bir.getOthers() != null) { + record.setOthers(new HashMap<>(bir.getOthers())); + } + record.setSegments(filterByModalities(modalities, bir.getBirs())); + return record; + } catch (Exception e) { + handleBiometricException(e); + return null; + } + } @Override public Map getMetaInfo(String id, String source, String process) { Map finalMap = new LinkedHashMap<>(); - String[] sourcePacketNames = packetNames.split(","); - - try { - for (String packetName : sourcePacketNames) { - Packet packet = packetKeeper.getPacket(getPacketInfo(id, packetName, source, process)); - InputStream idJsonStream = ZipUtils.unzipAndGetFile(packet.getPacket(), "PACKET_META_INFO"); - if (idJsonStream != null) { - byte[] bytearray = IOUtils.toByteArray(idJsonStream); - String jsonString = new String(bytearray); - LinkedHashMap currentIdMap = (LinkedHashMap) mapper - .readValue(jsonString, LinkedHashMap.class).get(IDENTITY); - - currentIdMap.keySet().stream().forEach(key -> { - try { - finalMap.putIfAbsent(key, - currentIdMap.get(key) != null ? JsonUtils - .javaObjectToJsonString(currentIdMap.get(key)).replaceAll("(^\")|(\"$)", "") - : null); - } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { - throw new GetAllMetaInfoException(e.getMessage()); - } - }); + for (String packetName : packetNames.split(",")) { + try (InputStream stream = ZipUtils.unzipAndGetFile( + packetKeeper.getPacket(getPacketInfo(id, packetName, source, process)).getPacket(), + "PACKET_META_INFO")) { + if (stream != null) { + byte[] arr = IOUtils.toByteArray(stream); + LinkedHashMap idMap = (LinkedHashMap) mapper + .readValue(new String(arr, StandardCharset.UTF_8), LinkedHashMap.class).get(IDENTITY); + for (Map.Entry entry : idMap.entrySet()) { + finalMap.putIfAbsent(entry.getKey(), + JsonUtils.javaObjectToJsonString(entry.getValue()).replaceAll("(^\")|(\"$)", "")); + } } + } catch (Exception e) { + handleAllMetaInfoException(e); } - } catch (Exception e) { - if (e instanceof BaseCheckedException) { - BaseCheckedException ex = (BaseCheckedException) e; - throw new GetAllMetaInfoException(ex.getErrorCode(), ex.getMessage()); - } else if (e instanceof BaseUncheckedException) { - BaseUncheckedException ex = (BaseUncheckedException) e; - throw new GetAllMetaInfoException(ex.getErrorCode(), ex.getMessage()); - } - throw new GetAllMetaInfoException(e.getMessage()); } return finalMap; } @@ -345,33 +274,18 @@ public Map getMetaInfo(String id, String source, String process) @Override public List> getAuditInfo(String id, String source, String process) { LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "getAuditInfo :: enrtry"); - List> finalMap = new ArrayList<>(); - String[] sourcePacketNames = packetNames.split(","); - try { - for (String srcPacket : sourcePacketNames) { - Packet packet = packetKeeper.getPacket(getPacketInfo(id, srcPacket, source, process)); - InputStream auditJson = ZipUtils.unzipAndGetFile(packet.getPacket(), "audit"); - if (auditJson != null) { - byte[] bytearray = IOUtils.toByteArray(auditJson); - String jsonString = new String(bytearray); - List> currentMap = (List>) mapper.readValue(jsonString, - List.class); - finalMap.addAll(currentMap); + List> allAudits = new ArrayList<>(); + for (String packetName : packetNames.split(",")) { + try (InputStream stream = ZipUtils.unzipAndGetFile( + packetKeeper.getPacket(getPacketInfo(id, packetName, source, process)).getPacket(), "audit")) { + if (stream != null) { + allAudits.addAll(mapper.readValue(new String(IOUtils.toByteArray(stream), StandardCharset.UTF_8), List.class)); } + } catch (Exception e) { + handleException(e); } - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - ExceptionUtils.getStackTrace(e)); - if (e instanceof BaseCheckedException) { - BaseCheckedException ex = (BaseCheckedException) e; - throw new GetAllIdentityException(ex.getErrorCode(), ex.getMessage()); - } else if (e instanceof BaseUncheckedException) { - BaseUncheckedException ex = (BaseUncheckedException) e; - throw new GetAllIdentityException(ex.getErrorCode(), ex.getMessage()); - } - throw new GetAllIdentityException(e.getMessage()); } - return finalMap; + return allAudits; } private PacketInfo getPacketInfo(String id, String packetName, String source, String process) { @@ -383,36 +297,46 @@ private PacketInfo getPacketInfo(String id, String packetName, String source, St return packetInfo; } - public List filterByModalities(List modalities, - List birList) { - List segments = new ArrayList<>(); - if (CollectionUtils.isEmpty(modalities)) { + public List filterByModalities(List modalities, List birList) { + if (CollectionUtils.isEmpty(modalities)) return birList; - } else { - // first search modalities in subtype and if not present search in type - for (BIR bir : birList) { - if (CollectionUtils.isNotEmpty(bir.getBdbInfo().getSubtype()) - && isModalityPresentInTypeSubtype(bir.getBdbInfo().getSubtype(), modalities)) { - segments.add(bir); - } else { - for (BiometricType type : bir.getBdbInfo().getType()) { - if (isModalityPresentInTypeSubtype(Lists.newArrayList(type.value()), modalities)) - segments.add(bir); - } - } - } - } - return segments; + return birList.stream() + .filter(bir -> (CollectionUtils.isNotEmpty(bir.getBdbInfo().getSubtype()) + && isModalityPresentInTypeSubtype(bir.getBdbInfo().getSubtype(), modalities)) + || bir.getBdbInfo().getType().stream().map(BiometricType::value) + .anyMatch(type -> isModalityPresentInTypeSubtype(Lists.newArrayList(type), modalities))) + .collect(Collectors.toList()); } private boolean isModalityPresentInTypeSubtype(List typeSubtype, List modalities) { - boolean isPresent = false; - for (String modality : modalities) { - String[] modalityArray = modality.split(" "); - if (ArrayUtils.isNotEmpty(modalityArray) && ListUtils.isEqualList(typeSubtype, Arrays.asList(modalityArray))) - isPresent = true; - } - return isPresent; + return modalities.stream().map(mod -> mod.split(" ")) + .anyMatch(arr -> ArrayUtils.isNotEmpty(arr) && ListUtils.isEqualList(typeSubtype, Arrays.asList(arr))); } -} + private void handleException(Exception e) { + LOGGER.error("Exception: {}", ExceptionUtils.getStackTrace(e)); + if (e instanceof BaseCheckedException ex) + throw new GetAllIdentityException(ex.getErrorCode(), ex.getErrorText()); + if (e instanceof BaseUncheckedException ex) + throw new GetAllIdentityException(ex.getErrorCode(), ex.getErrorText()); + throw new GetAllIdentityException(e.getMessage()); + } + + private void handleAllMetaInfoException(Exception e) { + LOGGER.error("Exception: {}", ExceptionUtils.getStackTrace(e)); + if (e instanceof BaseCheckedException ex) + throw new GetAllMetaInfoException(ex.getErrorCode(), ex.getErrorText()); + if (e instanceof BaseUncheckedException ex) + throw new GetAllMetaInfoException(ex.getErrorCode(), ex.getErrorText()); + throw new GetAllMetaInfoException(e.getMessage()); + } + + private void handleBiometricException(Exception e) { + LOGGER.error("Exception: {}", ExceptionUtils.getStackTrace(e)); + if (e instanceof BaseCheckedException ex) + throw new GetBiometricException(ex.getErrorCode(), ex.getErrorText()); + if (e instanceof BaseUncheckedException ex) + throw new GetBiometricException(ex.getErrorCode(), ex.getErrorText()); + throw new GetBiometricException(e.getMessage()); + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/PacketWriterImpl.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/PacketWriterImpl.java index fdad2118f9..d917d85b94 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/PacketWriterImpl.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/impl/PacketWriterImpl.java @@ -1,5 +1,28 @@ package io.mosip.commons.packet.impl; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.assertj.core.util.Lists; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + import io.mosip.commons.packet.constants.ErrorCode; import io.mosip.commons.packet.constants.LoggerFileConstant; import io.mosip.commons.packet.constants.PacketManagerConstants; @@ -22,436 +45,426 @@ import io.mosip.kernel.core.util.JsonUtils; import io.mosip.kernel.core.util.StringUtils; import io.mosip.kernel.core.util.exception.JsonProcessingException; -import org.assertj.core.util.Lists; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; @Component public class PacketWriterImpl implements IPacketWriter { - private static final Logger LOGGER = PacketManagerLogger.getLogger(PacketWriterImpl.class); - private static Map categorySubpacketMapping = new HashMap<>(); - private static final String UNDERSCORE = "_"; - private static final String HASHSEQUENCE1 = "hashSequence1"; - private static final String HASHSEQUENCE2 = "hashSequence2"; - - static { - categorySubpacketMapping.put("pvt", "id"); - categorySubpacketMapping.put("kyc", "id"); - categorySubpacketMapping.put("none", "id,evidence,optional"); - categorySubpacketMapping.put("evidence", "evidence"); - categorySubpacketMapping.put("optional", "optional"); - } - - @Autowired - private PacketManagerHelper packetManagerHelper; - - @Autowired - private PacketKeeper packetKeeper; - - @Value("${mosip.kernel.packet.default_subpacket_name:id}") - private String defaultSubpacketName; - - @Value("${default.provider.version:v1.0}") - private String defaultProviderVersion; - - @Value("${mosip.utc-datetime-pattern:yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}") - private String dateTimePattern; - - @Value("${packetmanager.zip.datetime.pattern:yyyyMMddHHmmss}") - private String zipDatetimePattern; - - private Map registrationPacketMap = new HashMap<>(); - - public RegistrationPacket initialize(String id) { - if (registrationPacketMap.get(id) == null) { - RegistrationPacket registrationPacket = new RegistrationPacket(dateTimePattern); - registrationPacket.setRegistrationId(id); - registrationPacketMap.put(id, registrationPacket); - } - return registrationPacketMap.get(id); - } - - @Override - public void setField(String id, String fieldName, String value) { - this.initialize(id).setField(fieldName, value); - } - - @Override - public void setFields(String id, Map fields) { - this.initialize(id).setFields(fields); - } - - @Override - public void setBiometric(String id, String fieldName, BiometricRecord value) { - this.initialize(id).setBiometricField(fieldName, value); - } - - @Override - public void setDocument(String id, String fieldName, Document value) { - this.initialize(id).setDocumentField(fieldName, value); - } - - - @Override - public void addAudits(String id, List> auditList) { - this.initialize(id).setAudits(auditList); - } - - @Override - public void addAudit(String id, Map audit) { - this.initialize(id).setAudit(audit); - } - - @Override - public void addMetaInfo(String id, Map metaInfo) { - this.initialize(id).setMetaData(metaInfo); - } - - @Override - public void addMetaInfo(String id, String key, String value) { - this.initialize(id).addMetaData(key, value); - } - - private List createPacket(String id, String version, String schemaJson, String source, String process, - String additionalInfoReqId, String refId, boolean offlineMode) throws PacketCreatorException { - LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), id, "Started packet creation"); - if (registrationPacketMap.get(id) == null) - throw new PacketCreatorException(ErrorCode.INITIALIZATION_ERROR.getErrorCode(), - ErrorCode.INITIALIZATION_ERROR.getErrorMessage()); - - List packetInfos = new ArrayList<>(); - - Map> identityProperties = loadSchemaFields(schemaJson); - - try { - int counter = 1; - String packetId = new StringBuilder() - .append(StringUtils.isNotBlank(additionalInfoReqId) ? additionalInfoReqId : id) - .append("-") - .append(refId) - .append("-") - .append(getcurrentTimeStamp()).toString(); - for (String subPacketName : identityProperties.keySet()) { - LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), - id, "Started Subpacket: " + subPacketName); - List schemaFields = identityProperties.get(subPacketName); - byte[] subpacketBytes = createSubpacket(Double.valueOf(version), schemaFields, defaultSubpacketName.equalsIgnoreCase(subPacketName), - id, offlineMode); - - PacketInfo packetInfo = new PacketInfo(); - packetInfo.setProviderName(this.getClass().getSimpleName()); - packetInfo.setSchemaVersion(new Double(version).toString()); - if (offlineMode) - packetInfo.setId(packetId); - else - packetInfo.setId(id); - packetInfo.setRefId(refId); - packetInfo.setSource(source); - packetInfo.setProcess(process); - packetInfo.setPacketName(id + UNDERSCORE + subPacketName); - packetInfo.setCreationDate(DateUtils.getUTCCurrentDateTimeString()); - packetInfo.setProviderVersion(defaultProviderVersion); - Packet packet = new Packet(); - packet.setPacketInfo(packetInfo); - packet.setPacket(subpacketBytes); - packetKeeper.putPacket(packet); - packetInfos.add(packetInfo); - LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), - id, "Completed Subpacket: " + subPacketName); - - if (counter == identityProperties.keySet().size()) { - boolean res = packetKeeper.pack(packetInfo.getId(), packetInfo.getSource(), - packetInfo.getProcess(), packetInfo.getRefId()); - if (!res) - packetKeeper.deletePacket(id, source, process); - } - - counter++; - } - - } catch (Exception e) { - LOGGER.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), - id, "Exception occured. Deleting the packet."); - packetKeeper.deletePacket(id, source, process); - throw new PacketCreatorException(ErrorCode.PKT_ZIP_ERROR.getErrorCode(), - ErrorCode.PKT_ZIP_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); - } finally { - this.registrationPacketMap.remove(id); - LOGGER.debug("registrationPacketMap size ====================================> " + registrationPacketMap.size()); - } - LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), - id, "Exiting packet creation"); - return packetInfos; - } - - @SuppressWarnings("unchecked") - private byte[] createSubpacket(double version, List schemaFields, boolean isDefault, String id, boolean offlineMode) - throws PacketCreatorException { - RegistrationPacket registrationPacket = registrationPacketMap.get(id); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try (ZipOutputStream subpacketZip = new ZipOutputStream(new BufferedOutputStream(out))) { - LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), - id, "Identified fields >>> " + schemaFields.size()); - Map identity = new HashMap(); - Map hashSequences = new HashMap<>(); - - identity.put(PacketManagerConstants.IDSCHEMA_VERSION, version); - registrationPacket.getMetaData().put(PacketManagerConstants.REGISTRATIONID, id); - registrationPacket.getMetaData().put(PacketManagerConstants.META_CREATION_DATE, registrationPacket.getCreationDate()); - - for (Object obj : schemaFields) { - Map field = (Map) obj; - String fieldName = (String) field.get(PacketManagerConstants.SCHEMA_ID); - LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), - id, "Adding field : " + fieldName); - switch ((String) field.get(PacketManagerConstants.SCHEMA_TYPE)) { - case PacketManagerConstants.BIOMETRICS_TYPE: - if (registrationPacket.getBiometrics().get(fieldName) != null) - addBiometricDetailsToZip(registrationPacket, fieldName, identity, subpacketZip, hashSequences, offlineMode); - break; - case PacketManagerConstants.DOCUMENTS_TYPE: - if (registrationPacket.getDocuments().get(fieldName) != null) - addDocumentDetailsToZip(registrationPacket, fieldName, identity, subpacketZip, hashSequences, offlineMode); - break; - default: - if (registrationPacket.getDemographics().get(fieldName) != null) - identity.put(fieldName, registrationPacket.getDemographics().get(fieldName)); - break; - } - } - - byte[] identityBytes = getIdentity(identity).getBytes(); - addEntryToZip(registrationPacket, PacketManagerConstants.IDENTITY_FILENAME_WITH_EXT, identityBytes, subpacketZip); - addHashSequenceWithSource(PacketManagerConstants.DEMOGRAPHIC_SEQ, PacketManagerConstants.IDENTITY_FILENAME, identityBytes, - hashSequences); - addOtherFilesToZip(registrationPacket, isDefault, subpacketZip, hashSequences, offlineMode); - - } catch (JsonProcessingException e) { - throw new PacketCreatorException(ErrorCode.OBJECT_TO_JSON_ERROR.getErrorCode(), - ErrorCode.BIR_TO_XML_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); - } catch (IOException | NoSuchAlgorithmException e) { - throw new PacketCreatorException(ErrorCode.PKT_ZIP_ERROR.getErrorCode(), - ErrorCode.PKT_ZIP_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); - } - return out.toByteArray(); - } - - private void addDocumentDetailsToZip(RegistrationPacket registrationPacket, String fieldName, Map identity, - ZipOutputStream zipOutputStream, Map hashSequences, boolean offlineMode) throws PacketCreatorException { - Document document = registrationPacket.getDocuments().get(fieldName); - //filename without extension must be set as value in ID.json - identity.put(fieldName, new DocumentType(fieldName, document.getType(), document.getFormat(), document.getRefNumber())); - String fileName = String.format("%s.%s", fieldName, document.getFormat()); - addEntryToZip(registrationPacket, fileName, document.getDocument(), zipOutputStream); - registrationPacket.getMetaData().put(fieldName, document.getType()); - - addHashSequenceWithSource(PacketManagerConstants.DEMOGRAPHIC_SEQ, fieldName, document.getDocument(), - hashSequences); - } - - private void addBiometricDetailsToZip(RegistrationPacket registrationPacket, String fieldName, Map identity, - ZipOutputStream zipOutputStream, Map hashSequences, boolean offlineMode) throws PacketCreatorException { - BiometricRecord birType = registrationPacket.getBiometrics().get(fieldName); - if (birType != null && birType.getSegments() != null && !birType.getSegments().isEmpty()) { - - byte[] xmlBytes; - try { - xmlBytes = packetManagerHelper.getXMLData(birType, offlineMode); - } catch (Exception e) { - throw new PacketCreatorException(ErrorCode.BIR_TO_XML_ERROR.getErrorCode(), - ErrorCode.BIR_TO_XML_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); - } - - addEntryToZip(registrationPacket, String.format(PacketManagerConstants.CBEFF_FILENAME_WITH_EXT, fieldName), xmlBytes, zipOutputStream); - identity.put(fieldName, new BiometricsType(PacketManagerConstants.CBEFF_FILE_FORMAT, - PacketManagerConstants.CBEFF_VERSION, String.format(PacketManagerConstants.CBEFF_FILENAME, fieldName))); - addHashSequenceWithSource(PacketManagerConstants.BIOMETRIC_SEQ, String.format(PacketManagerConstants.CBEFF_FILENAME, - fieldName), xmlBytes, hashSequences); - } - } - - private void addHashSequenceWithSource(String sequenceType, String name, byte[] bytes, - Map hashSequences) { - if (!hashSequences.containsKey(sequenceType)) - hashSequences.put(sequenceType, new HashSequenceMetaInfo(sequenceType)); - - hashSequences.get(sequenceType).addHashSource(name, bytes); - } - - private void addOtherFilesToZip(RegistrationPacket registrationPacket, boolean isDefault, ZipOutputStream zipOutputStream, - Map hashSequences, boolean offlineMode) throws JsonProcessingException, PacketCreatorException, IOException, NoSuchAlgorithmException { - - if (isDefault) { - addOperationsBiometricsToZip(registrationPacket, PacketManagerConstants.OFFICER, - zipOutputStream, hashSequences, offlineMode); - addOperationsBiometricsToZip(registrationPacket, PacketManagerConstants.SUPERVISOR, - zipOutputStream, hashSequences, offlineMode); - - if (registrationPacket.getAudits() == null || registrationPacket.getAudits().isEmpty()) - throw new PacketCreatorException(ErrorCode.AUDITS_REQUIRED.getErrorCode(), ErrorCode.AUDITS_REQUIRED.getErrorMessage()); - - byte[] auditBytes = JsonUtils.javaObjectToJsonString(registrationPacket.getAudits()).getBytes(); - addEntryToZip(registrationPacket, PacketManagerConstants.AUDIT_FILENAME_WITH_EXT, auditBytes, zipOutputStream); - addHashSequenceWithSource(PacketManagerConstants.OPERATIONS_SEQ, PacketManagerConstants.AUDIT_FILENAME, auditBytes, - hashSequences); - - HashSequenceMetaInfo hashSequenceMetaInfo = hashSequences.get(PacketManagerConstants.OPERATIONS_SEQ); - addEntryToZip(registrationPacket, PacketManagerConstants.PACKET_OPER_HASH_FILENAME, - PacketManagerHelper.generateHash(hashSequenceMetaInfo.getValue(), hashSequenceMetaInfo.getHashSource()), - zipOutputStream); - - registrationPacket.getMetaData().put(HASHSEQUENCE2, Lists.newArrayList(hashSequenceMetaInfo)); - } - - addPacketDataHash(registrationPacket, hashSequences, zipOutputStream); - addEntryToZip(registrationPacket, PacketManagerConstants.PACKET_META_FILENAME, getIdentity(registrationPacket.getMetaData()).getBytes(), zipOutputStream); - } - - private void addPacketDataHash(RegistrationPacket registrationPacket, Map hashSequences, - ZipOutputStream zipOutputStream) throws PacketCreatorException, IOException, NoSuchAlgorithmException { - - LinkedList sequence = new LinkedList(); - List hashSequenceMetaInfos = new ArrayList<>(); - Map data = new HashMap<>(); - if (hashSequences.containsKey(PacketManagerConstants.BIOMETRIC_SEQ)) { - sequence.addAll(hashSequences.get(PacketManagerConstants.BIOMETRIC_SEQ).getValue()); - data.putAll(hashSequences.get(PacketManagerConstants.BIOMETRIC_SEQ).getHashSource()); - hashSequenceMetaInfos.add(hashSequences.get(PacketManagerConstants.BIOMETRIC_SEQ)); - } - if (hashSequences.containsKey(PacketManagerConstants.DEMOGRAPHIC_SEQ)) { - sequence.addAll(hashSequences.get(PacketManagerConstants.DEMOGRAPHIC_SEQ).getValue()); - data.putAll(hashSequences.get(PacketManagerConstants.DEMOGRAPHIC_SEQ).getHashSource()); - hashSequenceMetaInfos.add(hashSequences.get(PacketManagerConstants.DEMOGRAPHIC_SEQ)); - } - if (hashSequenceMetaInfos.size() > 0) - registrationPacket.getMetaData().put(HASHSEQUENCE1, hashSequenceMetaInfos); - - addEntryToZip(registrationPacket, PacketManagerConstants.PACKET_DATA_HASH_FILENAME, PacketManagerHelper.generateHash(sequence, data), - zipOutputStream); - } - - private Map> loadSchemaFields(String schemaJson) throws PacketCreatorException { - Map> packetBasedMap = new HashMap>(); - - try { - JSONObject schema = new JSONObject(schemaJson); - schema = schema.getJSONObject(PacketManagerConstants.PROPERTIES); - schema = schema.getJSONObject(PacketManagerConstants.IDENTITY); - schema = schema.getJSONObject(PacketManagerConstants.PROPERTIES); - - JSONArray fieldNames = schema.names(); - for (int i = 0; i < fieldNames.length(); i++) { - String fieldName = fieldNames.getString(i); - JSONObject fieldDetail = schema.getJSONObject(fieldName); - String fieldCategory = fieldDetail.has(PacketManagerConstants.SCHEMA_CATEGORY) ? - fieldDetail.getString(PacketManagerConstants.SCHEMA_CATEGORY) : "none"; - String packets = categorySubpacketMapping.get(fieldCategory.toLowerCase()); - - String[] packetNames = packets.split(","); - for (String packetName : packetNames) { - if (!packetBasedMap.containsKey(packetName)) { - packetBasedMap.put(packetName, new ArrayList()); - } - - Map attributes = new HashMap<>(); - attributes.put(PacketManagerConstants.SCHEMA_ID, fieldName); - attributes.put(PacketManagerConstants.SCHEMA_TYPE, fieldDetail.has(PacketManagerConstants.SCHEMA_REF) ? - fieldDetail.getString(PacketManagerConstants.SCHEMA_REF) : fieldDetail.getString(PacketManagerConstants.SCHEMA_TYPE)); - packetBasedMap.get(packetName).add(attributes); - } - } - } catch (JSONException e) { - throw new PacketCreatorException(ErrorCode.JSON_PARSE_ERROR.getErrorCode(), - ErrorCode.JSON_PARSE_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); - } - return packetBasedMap; - } - - - private void addEntryToZip(RegistrationPacket registrationPacket, String fileName, byte[] data, ZipOutputStream zipOutputStream) - throws PacketCreatorException { - LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), - registrationPacket.getRegistrationId(), "Adding file : " + fileName); - try { - if (data != null) { - ZipEntry zipEntry = new ZipEntry(fileName); - zipOutputStream.putNextEntry(zipEntry); - zipOutputStream.write(data); - } - } catch (IOException e) { - throw new PacketCreatorException(ErrorCode.ADD_ZIP_ENTRY_ERROR.getErrorCode(), - ErrorCode.ADD_ZIP_ENTRY_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); - } - } - - private String getIdentity(Object object) throws JsonProcessingException { - return "{ \"identity\" : " + JsonUtils.javaObjectToJsonString(object) + " } "; - } - - private void addOperationsBiometricsToZip(RegistrationPacket registrationPacket, String operationType, - ZipOutputStream zipOutputStream, Map hashSequences, boolean offlineMode) throws PacketCreatorException { - - BiometricRecord biometrics = registrationPacket.getBiometrics().get(operationType); - - if (biometrics != null && biometrics.getSegments() != null && !biometrics.getSegments().isEmpty()) { - byte[] xmlBytes; - try { - xmlBytes = packetManagerHelper.getXMLData(biometrics, offlineMode); - } catch (Exception e) { - throw new PacketCreatorException(ErrorCode.BIR_TO_XML_ERROR.getErrorCode(), - ErrorCode.BIR_TO_XML_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); - } - - if (xmlBytes != null) { - String fileName = operationType + PacketManagerConstants.CBEFF_EXT; - addEntryToZip(registrationPacket, fileName, xmlBytes, zipOutputStream); - registrationPacket.getMetaData().put(String.format("%sBiometricFileName", operationType), fileName); - addHashSequenceWithSource(PacketManagerConstants.OPERATIONS_SEQ, operationType, xmlBytes, hashSequences); - } - } - } - - @Override - public List persistPacket(String id, String version, String schemaJson, String source, - String process, String additionalInfoReqId, String refId, boolean offlineMode) { - try { - return createPacket(id, version, schemaJson, source, process, additionalInfoReqId, refId, offlineMode); - } catch (PacketCreatorException e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, ExceptionUtils.getStackTrace(e)); - throw e; - } - } - - private String getcurrentTimeStamp() { - DateTimeFormatter format = DateTimeFormatter - .ofPattern(zipDatetimePattern); - return LocalDateTime.now(ZoneId.of("UTC")).format(format); - } - - @Override - public void removePacket(String id) { - if (registrationPacketMap.get(id) != null) - registrationPacketMap.remove(id); - } - -} + private static final Logger LOGGER = PacketManagerLogger.getLogger(PacketWriterImpl.class); + private static final String UNDERSCORE = "_"; + private static final String HYPEN = "-"; + private static final String HASHSEQUENCE1 = "hashSequence1"; + private static final String HASHSEQUENCE2 = "hashSequence2"; + + private static final Map categorySubpacketMapping = Map.of("pvt", "id", "kyc", "id", "none", + "id,evidence,optional", "evidence", "evidence", "optional", "optional"); + + @Autowired + private PacketManagerHelper packetManagerHelper; + + @Autowired + private PacketKeeper packetKeeper; + + @Value("${mosip.kernel.packet.default_subpacket_name:id}") + private String defaultSubpacketName; + + @Value("${default.provider.version:v1.0}") + private String defaultProviderVersion; + + @Value("${mosip.utc-datetime-pattern:yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}") + private String dateTimePattern; + + @Value("${packetmanager.zip.datetime.pattern:yyyyMMddHHmmss}") + private String zipDatetimePattern; + + private Map registrationPacketMap = new HashMap<>(); + + public RegistrationPacket initialize(String id) { + return registrationPacketMap.computeIfAbsent(id, k -> { + RegistrationPacket registrationPacket = new RegistrationPacket(dateTimePattern); + registrationPacket.setRegistrationId(id); + return registrationPacket; + }); + } + + @Override + public void setField(String id, String fieldName, String value) { + this.initialize(id).setField(fieldName, value); + } + + @Override + public void setFields(String id, Map fields) { + this.initialize(id).setFields(fields); + } + + @Override + public void setBiometric(String id, String fieldName, BiometricRecord value) { + this.initialize(id).setBiometricField(fieldName, value); + } + + @Override + public void setDocument(String id, String fieldName, Document value) { + this.initialize(id).setDocumentField(fieldName, value); + } + + @Override + public void addAudits(String id, List> auditList) { + this.initialize(id).setAudits(auditList); + } + + @Override + public void addAudit(String id, Map audit) { + this.initialize(id).setAudit(audit); + } + + @Override + public void addMetaInfo(String id, Map metaInfo) { + this.initialize(id).setMetaData(metaInfo); + } + + @Override + public void addMetaInfo(String id, String key, String value) { + this.initialize(id).addMetaData(key, value); + } + + private List createPacket(String id, String version, String schemaJson, String source, String process, + String additionalInfoReqId, String refId, boolean offlineMode) throws PacketCreatorException { + LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), id, + "Started packet creation"); + if (registrationPacketMap.get(id) == null) + throw new PacketCreatorException(ErrorCode.INITIALIZATION_ERROR.getErrorCode(), + ErrorCode.INITIALIZATION_ERROR.getErrorMessage()); + + List packetInfos = new ArrayList<>(); + + Map> identityProperties = loadSchemaFields(schemaJson); + + try { + int counter = 1; + String packetId = new StringBuilder() + .append(StringUtils.isNotBlank(additionalInfoReqId) ? additionalInfoReqId : id).append(HYPEN) + .append(refId).append(HYPEN).append(getcurrentTimeStamp()).toString(); + for (String subPacketName : identityProperties.keySet()) { + LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), id, + "Started Subpacket: " + subPacketName); + List schemaFields = identityProperties.get(subPacketName); + byte[] subpacketBytes = createSubpacket(Double.valueOf(version), schemaFields, + defaultSubpacketName.equalsIgnoreCase(subPacketName), id, offlineMode); + + PacketInfo packetInfo = new PacketInfo(); + packetInfo.setProviderName(this.getClass().getSimpleName()); + packetInfo.setSchemaVersion(Double.valueOf(version).toString()); + if (offlineMode) + packetInfo.setId(packetId); + else + packetInfo.setId(id); + packetInfo.setRefId(refId); + packetInfo.setSource(source); + packetInfo.setProcess(process); + packetInfo.setPacketName(id + UNDERSCORE + subPacketName); + packetInfo.setCreationDate(DateUtils.getUTCCurrentDateTimeString()); + packetInfo.setProviderVersion(defaultProviderVersion); + Packet packet = new Packet(); + packet.setPacketInfo(packetInfo); + packet.setPacket(subpacketBytes); + packetKeeper.putPacket(packet); + packetInfos.add(packetInfo); + LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), id, + "Completed Subpacket: " + subPacketName); + + if (counter == identityProperties.keySet().size()) { + boolean res = packetKeeper.pack(packetInfo.getId(), packetInfo.getSource(), packetInfo.getProcess(), + packetInfo.getRefId()); + if (!res) + packetKeeper.deletePacket(id, source, process); + } + + counter++; + } + + } catch (Exception e) { + LOGGER.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), id, + "Exception occured. Deleting the packet."); + packetKeeper.deletePacket(id, source, process); + throw new PacketCreatorException(ErrorCode.PKT_ZIP_ERROR.getErrorCode(), + ErrorCode.PKT_ZIP_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); + } finally { + this.registrationPacketMap.remove(id); + LOGGER.debug( + "registrationPacketMap size ====================================> " + registrationPacketMap.size()); + } + LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), id, + "Exiting packet creation"); + return packetInfos; + } + + @SuppressWarnings("unchecked") + private byte[] createSubpacket(double version, List schemaFields, boolean isDefault, String id, + boolean offlineMode) throws PacketCreatorException { + RegistrationPacket registrationPacket = registrationPacketMap.get(id); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (ZipOutputStream subpacketZip = new ZipOutputStream(new BufferedOutputStream(out))) { + LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), id, + "Identified fields >>> " + schemaFields.size()); + Map identity = new HashMap(); + Map hashSequences = new HashMap<>(); + + identity.put(PacketManagerConstants.IDSCHEMA_VERSION, version); + registrationPacket.getMetaData().put(PacketManagerConstants.REGISTRATIONID, id); + registrationPacket.getMetaData().put(PacketManagerConstants.META_CREATION_DATE, + registrationPacket.getCreationDate()); + + for (Object obj : schemaFields) { + Map field = (Map) obj; + String fieldName = (String) field.get(PacketManagerConstants.SCHEMA_ID); + LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), id, + "Adding field : " + fieldName); + switch ((String) field.get(PacketManagerConstants.SCHEMA_TYPE)) { + case PacketManagerConstants.BIOMETRICS_TYPE: + if (registrationPacket.getBiometrics().get(fieldName) != null) + addBiometricDetailsToZip(registrationPacket, fieldName, identity, subpacketZip, hashSequences, + offlineMode); + break; + case PacketManagerConstants.DOCUMENTS_TYPE: + if (registrationPacket.getDocuments().get(fieldName) != null) + addDocumentDetailsToZip(registrationPacket, fieldName, identity, subpacketZip, hashSequences, + offlineMode); + break; + default: + if (registrationPacket.getDemographics().get(fieldName) != null) + identity.put(fieldName, registrationPacket.getDemographics().get(fieldName)); + break; + } + } + + byte[] identityBytes = getIdentity(identity).getBytes(); + addEntryToZip(registrationPacket, PacketManagerConstants.IDENTITY_FILENAME_WITH_EXT, identityBytes, + subpacketZip); + addHashSequenceWithSource(PacketManagerConstants.DEMOGRAPHIC_SEQ, PacketManagerConstants.IDENTITY_FILENAME, + identityBytes, hashSequences); + addOtherFilesToZip(registrationPacket, isDefault, subpacketZip, hashSequences, offlineMode); + + } catch (JsonProcessingException e) { + throw new PacketCreatorException(ErrorCode.OBJECT_TO_JSON_ERROR.getErrorCode(), + ErrorCode.BIR_TO_XML_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); + } catch (IOException | NoSuchAlgorithmException e) { + throw new PacketCreatorException(ErrorCode.PKT_ZIP_ERROR.getErrorCode(), + ErrorCode.PKT_ZIP_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); + } + return out.toByteArray(); + } + + private void addDocumentDetailsToZip(RegistrationPacket registrationPacket, String fieldName, + Map identity, ZipOutputStream zipOutputStream, + Map hashSequences, boolean offlineMode) throws PacketCreatorException { + Document document = registrationPacket.getDocuments().get(fieldName); + // filename without extension must be set as value in ID.json + identity.put(fieldName, + new DocumentType(fieldName, document.getType(), document.getFormat(), document.getRefNumber())); + String fileName = String.format("%s.%s", fieldName, document.getFormat()); + addEntryToZip(registrationPacket, fileName, document.getDocument(), zipOutputStream); + registrationPacket.getMetaData().put(fieldName, document.getType()); + + addHashSequenceWithSource(PacketManagerConstants.DEMOGRAPHIC_SEQ, fieldName, document.getDocument(), + hashSequences); + } + + private void addBiometricDetailsToZip(RegistrationPacket registrationPacket, String fieldName, + Map identity, ZipOutputStream zipOutputStream, + Map hashSequences, boolean offlineMode) throws PacketCreatorException { + BiometricRecord birType = registrationPacket.getBiometrics().get(fieldName); + if (birType != null && birType.getSegments() != null && !birType.getSegments().isEmpty()) { + + byte[] xmlBytes; + try { + xmlBytes = packetManagerHelper.getXMLData(birType, offlineMode); + } catch (Exception e) { + throw new PacketCreatorException(ErrorCode.BIR_TO_XML_ERROR.getErrorCode(), + ErrorCode.BIR_TO_XML_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); + } + + addEntryToZip(registrationPacket, String.format(PacketManagerConstants.CBEFF_FILENAME_WITH_EXT, fieldName), + xmlBytes, zipOutputStream); + identity.put(fieldName, + new BiometricsType(PacketManagerConstants.CBEFF_FILE_FORMAT, PacketManagerConstants.CBEFF_VERSION, + String.format(PacketManagerConstants.CBEFF_FILENAME, fieldName))); + addHashSequenceWithSource(PacketManagerConstants.BIOMETRIC_SEQ, + String.format(PacketManagerConstants.CBEFF_FILENAME, fieldName), xmlBytes, hashSequences); + } + } + + private void addHashSequenceWithSource(String sequenceType, String name, byte[] bytes, + Map hashSequences) { + if (!hashSequences.containsKey(sequenceType)) + hashSequences.put(sequenceType, new HashSequenceMetaInfo(sequenceType)); + + hashSequences.get(sequenceType).addHashSource(name, bytes); + } + + private void addOtherFilesToZip(RegistrationPacket registrationPacket, boolean isDefault, + ZipOutputStream zipOutputStream, Map hashSequences, boolean offlineMode) + throws JsonProcessingException, PacketCreatorException, IOException, NoSuchAlgorithmException { + + if (isDefault) { + addOperationsBiometricsToZip(registrationPacket, PacketManagerConstants.OFFICER, zipOutputStream, + hashSequences, offlineMode); + addOperationsBiometricsToZip(registrationPacket, PacketManagerConstants.SUPERVISOR, zipOutputStream, + hashSequences, offlineMode); + + if (registrationPacket.getAudits() == null || registrationPacket.getAudits().isEmpty()) + throw new PacketCreatorException(ErrorCode.AUDITS_REQUIRED.getErrorCode(), + ErrorCode.AUDITS_REQUIRED.getErrorMessage()); + + byte[] auditBytes = JsonUtils.javaObjectToJsonString(registrationPacket.getAudits()).getBytes(); + addEntryToZip(registrationPacket, PacketManagerConstants.AUDIT_FILENAME_WITH_EXT, auditBytes, + zipOutputStream); + addHashSequenceWithSource(PacketManagerConstants.OPERATIONS_SEQ, PacketManagerConstants.AUDIT_FILENAME, + auditBytes, hashSequences); + + HashSequenceMetaInfo hashSequenceMetaInfo = hashSequences.get(PacketManagerConstants.OPERATIONS_SEQ); + addEntryToZip( + registrationPacket, PacketManagerConstants.PACKET_OPER_HASH_FILENAME, PacketManagerHelper + .generateHash(hashSequenceMetaInfo.getValue(), hashSequenceMetaInfo.getHashSource()), + zipOutputStream); + + registrationPacket.getMetaData().put(HASHSEQUENCE2, Lists.newArrayList(hashSequenceMetaInfo)); + } + + addPacketDataHash(registrationPacket, hashSequences, zipOutputStream); + addEntryToZip(registrationPacket, PacketManagerConstants.PACKET_META_FILENAME, + getIdentity(registrationPacket.getMetaData()).getBytes(), zipOutputStream); + } + + private void addPacketDataHash(RegistrationPacket registrationPacket, + Map hashSequences, ZipOutputStream zipOutputStream) + throws PacketCreatorException, IOException, NoSuchAlgorithmException { + + LinkedList sequence = new LinkedList(); + List hashSequenceMetaInfos = new ArrayList<>(); + Map data = new HashMap<>(); + if (hashSequences.containsKey(PacketManagerConstants.BIOMETRIC_SEQ)) { + sequence.addAll(hashSequences.get(PacketManagerConstants.BIOMETRIC_SEQ).getValue()); + data.putAll(hashSequences.get(PacketManagerConstants.BIOMETRIC_SEQ).getHashSource()); + hashSequenceMetaInfos.add(hashSequences.get(PacketManagerConstants.BIOMETRIC_SEQ)); + } + if (hashSequences.containsKey(PacketManagerConstants.DEMOGRAPHIC_SEQ)) { + sequence.addAll(hashSequences.get(PacketManagerConstants.DEMOGRAPHIC_SEQ).getValue()); + data.putAll(hashSequences.get(PacketManagerConstants.DEMOGRAPHIC_SEQ).getHashSource()); + hashSequenceMetaInfos.add(hashSequences.get(PacketManagerConstants.DEMOGRAPHIC_SEQ)); + } + if (hashSequenceMetaInfos.size() > 0) + registrationPacket.getMetaData().put(HASHSEQUENCE1, hashSequenceMetaInfos); + + addEntryToZip(registrationPacket, PacketManagerConstants.PACKET_DATA_HASH_FILENAME, + PacketManagerHelper.generateHash(sequence, data), zipOutputStream); + } + + private Map> loadSchemaFields(String schemaJson) throws PacketCreatorException { + Map> packetBasedMap = new HashMap>(); + + try { + JSONObject schema = new JSONObject(schemaJson); + schema = schema.getJSONObject(PacketManagerConstants.PROPERTIES); + schema = schema.getJSONObject(PacketManagerConstants.IDENTITY); + schema = schema.getJSONObject(PacketManagerConstants.PROPERTIES); + + JSONArray fieldNames = schema.names(); + for (int i = 0; i < fieldNames.length(); i++) { + String fieldName = fieldNames.getString(i); + JSONObject fieldDetail = schema.getJSONObject(fieldName); + String fieldCategory = fieldDetail.has(PacketManagerConstants.SCHEMA_CATEGORY) + ? fieldDetail.getString(PacketManagerConstants.SCHEMA_CATEGORY) + : "none"; + String packets = categorySubpacketMapping.get(fieldCategory.toLowerCase()); + + String[] packetNames = packets.split(","); + for (String packetName : packetNames) { + if (!packetBasedMap.containsKey(packetName)) { + packetBasedMap.put(packetName, new ArrayList()); + } + + Map attributes = new HashMap<>(); + attributes.put(PacketManagerConstants.SCHEMA_ID, fieldName); + attributes.put(PacketManagerConstants.SCHEMA_TYPE, + fieldDetail.has(PacketManagerConstants.SCHEMA_REF) + ? fieldDetail.getString(PacketManagerConstants.SCHEMA_REF) + : fieldDetail.getString(PacketManagerConstants.SCHEMA_TYPE)); + packetBasedMap.get(packetName).add(attributes); + } + } + } catch (JSONException e) { + throw new PacketCreatorException(ErrorCode.JSON_PARSE_ERROR.getErrorCode(), + ErrorCode.JSON_PARSE_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); + } + return packetBasedMap; + } + + private void addEntryToZip(RegistrationPacket registrationPacket, String fileName, byte[] data, + ZipOutputStream zipOutputStream) throws PacketCreatorException { + LOGGER.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.ID.toString(), + registrationPacket.getRegistrationId(), "Adding file : " + fileName); + try { + if (data != null) { + ZipEntry zipEntry = new ZipEntry(fileName); + zipOutputStream.putNextEntry(zipEntry); + zipOutputStream.write(data); + } + } catch (IOException e) { + throw new PacketCreatorException(ErrorCode.ADD_ZIP_ENTRY_ERROR.getErrorCode(), + ErrorCode.ADD_ZIP_ENTRY_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); + } + } + + private String getIdentity(Object object) throws JsonProcessingException { + return "{ \"identity\" : " + JsonUtils.javaObjectToJsonString(object) + " } "; + } + + private void addOperationsBiometricsToZip(RegistrationPacket registrationPacket, String operationType, + ZipOutputStream zipOutputStream, Map hashSequences, boolean offlineMode) + throws PacketCreatorException { + + BiometricRecord biometrics = registrationPacket.getBiometrics().get(operationType); + if (biometrics != null && biometrics.getSegments() != null && !biometrics.getSegments().isEmpty()) { + try { + byte[] xmlBytes = packetManagerHelper.getXMLData(biometrics, offlineMode); + if (xmlBytes == null || xmlBytes.length == 0) { + throw new PacketCreatorException(ErrorCode.BIR_TO_XML_ERROR.getErrorCode(), + ErrorCode.BIR_TO_XML_ERROR.getErrorMessage()); + } + + if (xmlBytes != null) { + String fileName = operationType + PacketManagerConstants.CBEFF_EXT; + addEntryToZip(registrationPacket, fileName, xmlBytes, zipOutputStream); + registrationPacket.getMetaData().put(String.format("%sBiometricFileName", operationType), fileName); + addHashSequenceWithSource(PacketManagerConstants.OPERATIONS_SEQ, operationType, xmlBytes, + hashSequences); + } + } catch (Exception e) { + throw new PacketCreatorException(ErrorCode.BIR_TO_XML_ERROR.getErrorCode(), + ErrorCode.BIR_TO_XML_ERROR.getErrorMessage().concat(ExceptionUtils.getStackTrace(e))); + } + } + } + + @Override + public List persistPacket(String id, String version, String schemaJson, String source, String process, + String additionalInfoReqId, String refId, boolean offlineMode) { + try { + return createPacket(id, version, schemaJson, source, process, additionalInfoReqId, refId, offlineMode); + } catch (PacketCreatorException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + ExceptionUtils.getStackTrace(e)); + throw e; + } + } + + private String getcurrentTimeStamp() { + DateTimeFormatter format = DateTimeFormatter.ofPattern(zipDatetimePattern); + return LocalDateTime.now(ZoneId.of("UTC")).format(format); + } + + @Override + public void removePacket(String id) { + if (registrationPacketMap.get(id) != null) + registrationPacketMap.remove(id); + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/keeper/PacketKeeper.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/keeper/PacketKeeper.java index 6d6ea1e45c..0ca8f83732 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/keeper/PacketKeeper.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/keeper/PacketKeeper.java @@ -5,8 +5,8 @@ import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; -import io.mosip.commons.packet.exception.ObjectDoesnotExistsException; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -22,6 +22,7 @@ import io.mosip.commons.packet.dto.TagDto; import io.mosip.commons.packet.dto.TagRequestDto; import io.mosip.commons.packet.exception.CryptoException; +import io.mosip.commons.packet.exception.ObjectDoesnotExistsException; import io.mosip.commons.packet.exception.ObjectStoreAdapterException; import io.mosip.commons.packet.exception.PacketIntegrityFailureException; import io.mosip.commons.packet.exception.PacketKeeperException; @@ -34,253 +35,308 @@ import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.CryptoUtil; import io.mosip.kernel.core.util.HMACUtils2; +import jakarta.annotation.PostConstruct; /** - * The packet keeper is used to store & retrieve packet, creation of audit, encrypt and sign packet. - * Packet keeper is used to get container information and list of sources from a packet. + * The packet keeper is used to store & retrieve packet, creation of audit, + * encrypt and sign packet. Packet keeper is used to get container information + * and list of sources from a packet. */ @Component public class PacketKeeper { - /** - * The reg proc logger. - */ - private static Logger LOGGER = PacketManagerLogger.getLogger(PacketKeeper.class); - private static final String OBJECT_DOESNOT_EXISTS = "The specified key does not exist"; - private static final String STATUS_404 = "Status Code: 404; Error Code: NoSuchKey"; + /** + * The reg proc logger. + */ + private static Logger LOGGER = PacketManagerLogger.getLogger(PacketKeeper.class); + + private static final String OBJECT_DOESNOT_EXISTS = "The specified key does not exist"; + private static final String STATUS_404 = "Status Code: 404; Error Code: NoSuchKey"; + private static final String UNDERSCORE = "_"; - @Value("${packet.manager.account.name}") - private String PACKET_MANAGER_ACCOUNT; + @Value("${packet.manager.account.name}") + private String PACKET_MANAGER_ACCOUNT; - @Autowired - @Qualifier("SwiftAdapter") - private ObjectStoreAdapter swiftAdapter; + @Autowired + @Qualifier("SwiftAdapter") + private ObjectStoreAdapter swiftAdapter; - @Autowired - @Qualifier("S3Adapter") - private ObjectStoreAdapter s3Adapter; + @Autowired + @Qualifier("S3Adapter") + private ObjectStoreAdapter s3Adapter; - @Autowired - @Qualifier("PosixAdapter") - private ObjectStoreAdapter posixAdapter; + @Autowired + @Qualifier("PosixAdapter") + private ObjectStoreAdapter posixAdapter; - @Value("${objectstore.adapter.name}") - private String adapterName; + @Value("${objectstore.adapter.name}") + private String adapterName; - @Value("${objectstore.crypto.name}") - private String cryptoName; - - @Value("${mosip.kernel.registrationcenterid.length}") + @Value("${objectstore.crypto.name}") + private String cryptoName; + + @Value("${mosip.kernel.registrationcenterid.length}") private int centerIdLength; @Value("${mosip.kernel.machineid.length}") private int machineIdLength; - + @Value("${packetmanager.packet.signature.disable-verification:false}") private boolean disablePacketSignatureVerification; - @Autowired - @Qualifier("OnlinePacketCryptoServiceImpl") - private IPacketCryptoService onlineCrypto; - - @Autowired - @Qualifier("OfflinePacketCryptoServiceImpl") - private IPacketCryptoService offlineCrypto; - - @Autowired - private PacketManagerHelper helper; - - private static final String UNDERSCORE = "_"; - - /** - * Check packet integrity. - * - * @param packetInfo : the packet information - * @return : boolean - */ - public boolean checkIntegrity(PacketInfo packetInfo, byte[] encryptedSubPacket) throws NoSuchAlgorithmException { - String hash = CryptoUtil.encodeToURLSafeBase64(HMACUtils2.generateHash(encryptedSubPacket)); - boolean result = hash.equals(packetInfo.getEncryptedHash()); - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, - getName(packetInfo.getId(), packetInfo.getPacketName()), "Integrity check : " + result); - return result; - } - - /** - * Check integrity and signature of the packet - * - * - * @param packet - * @param encryptedSubPacket - * @return - */ - public boolean checkSignature(Packet packet, byte[] encryptedSubPacket) throws NoSuchAlgorithmException { - boolean result = disablePacketSignatureVerification ? true : - getCryptoService().verify(helper.getRefId( - packet.getPacketInfo().getId(), packet.getPacketInfo().getRefId()), packet.getPacket() - , CryptoUtil.decodeURLSafeBase64(packet.getPacketInfo().getSignature())); - if (result) - result = checkIntegrity(packet.getPacketInfo(), encryptedSubPacket); - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, - getName(packet.getPacketInfo().getId(), packet.getPacketInfo().getPacketName()), "Integrity and signature check : " + result); - return result; - } - - /** - * Get packet - * - * @param packetInfo : packet info - * @return : Packet - */ - public Packet getPacket(PacketInfo packetInfo) throws PacketKeeperException { - try { - InputStream is = getAdapter().getObject(PACKET_MANAGER_ACCOUNT, packetInfo.getId(), packetInfo.getSource(), - packetInfo.getProcess(), getName(packetInfo.getId(), packetInfo.getPacketName())); - if (is == null) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, - getName(packetInfo.getId(), packetInfo.getPacketName()), packetInfo.getProcess() + " Packet is not present in packet store."); - throw new PacketKeeperException(ErrorCode.PACKET_NOT_FOUND.getErrorCode(), ErrorCode.PACKET_NOT_FOUND.getErrorMessage()); - } - byte[] encryptedSubPacket = IOUtils.toByteArray(is); - - Packet packet = new Packet(); - Map metaInfo = getAdapter().getMetaData(PACKET_MANAGER_ACCOUNT, packetInfo.getId(), - packetInfo.getSource(), packetInfo.getProcess(), getName(packetInfo.getId(), packetInfo.getPacketName())); - if (metaInfo != null && !metaInfo.isEmpty()) - packet.setPacketInfo(PacketManagerHelper.getPacketInfo(metaInfo)); - else { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, - getName(packetInfo.getId(), packetInfo.getPacketName()), "metainfo not found for this packet"); - packet.setPacketInfo(packetInfo); - } - byte[] subPacket = getCryptoService().decrypt(helper.getRefId( - packet.getPacketInfo().getId(), packet.getPacketInfo().getRefId()), encryptedSubPacket); - packet.setPacket(subPacket); - - - if (!checkSignature(packet, encryptedSubPacket)) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, - getName(packet.getPacketInfo().getId(), packetInfo.getPacketName()), "Packet Integrity and Signature check failed"); - throw new PacketIntegrityFailureException(); - } - - return packet; - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, packetInfo.getId(), ExceptionUtils.getStackTrace(e)); - if (e.getMessage() != null && e.getMessage().contains(OBJECT_DOESNOT_EXISTS) && e.getMessage().contains(STATUS_404)) - throw new ObjectDoesnotExistsException(); - else if (e instanceof BaseCheckedException) { - BaseCheckedException ex = (BaseCheckedException) e; - throw new PacketKeeperException(ex.getErrorCode(), ex.getMessage()); - } - else if (e instanceof BaseUncheckedException) { - BaseUncheckedException ex = (BaseUncheckedException) e; - throw new PacketKeeperException(ex.getErrorCode(), ex.getMessage()); - } else - throw new PacketKeeperException(PacketUtilityErrorCodes.PACKET_KEEPER_GET_ERROR.getErrorCode(), - "Exception occured reading packet : " + e.getMessage(), e); - } - } - - /** - * Put packet into storage/cache - * - * @param packet : the Packet - * @return PacketInfo - */ - public PacketInfo putPacket(Packet packet) throws PacketKeeperException { - try { - // encrypt packet - byte[] encryptedSubPacket = getCryptoService().encrypt(packet.getPacketInfo().getRefId(), packet.getPacket()); - - // put packet in object store - boolean response = getAdapter().putObject(PACKET_MANAGER_ACCOUNT, - packet.getPacketInfo().getId(), packet.getPacketInfo().getSource(), - packet.getPacketInfo().getProcess(), packet.getPacketInfo().getPacketName(), new ByteArrayInputStream(encryptedSubPacket)); - - if (response) { - PacketInfo packetInfo = packet.getPacketInfo(); - // sign encrypted packet - packetInfo.setSignature(CryptoUtil.encodeToURLSafeBase64(getCryptoService().sign(packet.getPacket()))); - // generate encrypted packet hash - packetInfo.setEncryptedHash(CryptoUtil.encodeToURLSafeBase64(HMACUtils2.generateHash(encryptedSubPacket))); - Map metaMap = PacketManagerHelper.getMetaMap(packetInfo); - metaMap = getAdapter().addObjectMetaData(PACKET_MANAGER_ACCOUNT, - packet.getPacketInfo().getId(), packet.getPacketInfo().getSource(), packet.getPacketInfo().getProcess(), packet.getPacketInfo().getPacketName(), metaMap); - return PacketManagerHelper.getPacketInfo(metaMap); - } else - throw new PacketKeeperException(PacketUtilityErrorCodes - .PACKET_KEEPER_PUT_ERROR.getErrorCode(), "Unable to store packet in object store"); - - - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, packet.getPacketInfo().getId(), ExceptionUtils.getStackTrace(e)); - if (e instanceof BaseCheckedException) { - BaseCheckedException ex = (BaseCheckedException) e; - throw new PacketKeeperException(ex.getErrorCode(), ex.getMessage()); - } else if (e instanceof BaseUncheckedException) { - BaseUncheckedException ex = (BaseUncheckedException) e; - throw new PacketKeeperException(ex.getErrorCode(), ex.getMessage()); - } - throw new PacketKeeperException(PacketUtilityErrorCodes.PACKET_KEEPER_PUT_ERROR.getErrorCode(), - "Failed to persist packet in object store : " + e.getMessage(), e); - } - } - - private ObjectStoreAdapter getAdapter() { - if (adapterName.equalsIgnoreCase(swiftAdapter.getClass().getSimpleName())) - return swiftAdapter; - else if (adapterName.equalsIgnoreCase(posixAdapter.getClass().getSimpleName())) - return posixAdapter; - else if (adapterName.equalsIgnoreCase(s3Adapter.getClass().getSimpleName())) - return s3Adapter; - else - throw new ObjectStoreAdapterException(); - } - - private IPacketCryptoService getCryptoService() { - if (cryptoName.equalsIgnoreCase(onlineCrypto.getClass().getSimpleName())) - return onlineCrypto; - else if (cryptoName.equalsIgnoreCase(offlineCrypto.getClass().getSimpleName())) - return offlineCrypto; - else - throw new CryptoException(); - } - - private static String getName(String id, String name) { - return id + UNDERSCORE + name; - } - - public boolean deletePacket(String id, String source, String process) { - return getAdapter().removeContainer(PACKET_MANAGER_ACCOUNT, id, source, process); - } - - public boolean pack(String id, String source, String process, String refId) { - return getAdapter().pack(PACKET_MANAGER_ACCOUNT, id, source, process, refId); - } + @Autowired + @Qualifier("OnlinePacketCryptoServiceImpl") + private IPacketCryptoService onlineCrypto; + + @Autowired + @Qualifier("OfflinePacketCryptoServiceImpl") + private IPacketCryptoService offlineCrypto; + + @Autowired + private PacketManagerHelper helper; + + private Map adapterRegistry = new ConcurrentHashMap<>(); + private Map cryptoRegistry = new ConcurrentHashMap<>(); + + @PostConstruct + private void initializeRegistries() { + adapterRegistry.put("SwiftAdapter", swiftAdapter); + adapterRegistry.put("S3Adapter", s3Adapter); + adapterRegistry.put("PosixAdapter", posixAdapter); + + cryptoRegistry.put("OnlinePacketCryptoServiceImpl", onlineCrypto); + cryptoRegistry.put("OfflinePacketCryptoServiceImpl", offlineCrypto); + + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, "PacketKeeper", + "Adapter and CryptoService registries initialized"); + } + + /** + * Check packet integrity using HMAC-SHA256 and compare with stored hash. + * + * @param packetInfo the packet information metadata + * @param encryptedSubPacket the encrypted byte content of the packet + * @return true if integrity verified, false otherwise + */ + public boolean checkIntegrity(PacketInfo packetInfo, byte[] encryptedSubPacket) throws NoSuchAlgorithmException { + long start = System.nanoTime(); + String computedHash = CryptoUtil.encodeToURLSafeBase64(HMACUtils2.generateHash(encryptedSubPacket)); + boolean result = computedHash.equals(packetInfo.getEncryptedHash()); + + // Keep original log structure + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, + getName(packetInfo.getId(), packetInfo.getPacketName()), "Integrity check : " + result); + + return result; + } + + /** + * Verify both digital signature and HMAC-based packet integrity. + * + * @param packet the Packet object + * @param encryptedSubPacket the encrypted byte content of the packet + * @return true if both signature and integrity are valid + */ + public boolean checkSignature(Packet packet, byte[] encryptedSubPacket) throws NoSuchAlgorithmException { + boolean result; + + if (disablePacketSignatureVerification) { + result = true; + } else { + result = getCryptoService().verify( + helper.getRefId(packet.getPacketInfo().getId(), packet.getPacketInfo().getRefId()), + packet.getPacket(), CryptoUtil.decodeURLSafeBase64(packet.getPacketInfo().getSignature())); + } + + if (result) { + result = checkIntegrity(packet.getPacketInfo(), encryptedSubPacket); + } + + // Keep original log structure + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, + getName(packet.getPacketInfo().getId(), packet.getPacketInfo().getPacketName()), + "Integrity and signature check : " + result); + + return result; + } + + /** + * Get packet from object store and validate its integrity and signature. + * + * @param packetInfo PacketInfo metadata to locate and verify packet + * @return Packet object containing decrypted packet and metadata + * @throws PacketKeeperException in case of errors or failed validation + */ + public Packet getPacket(PacketInfo packetInfo) throws PacketKeeperException { + String objectName = getName(packetInfo.getId(), packetInfo.getPacketName()); + + try { + // Step 1: Retrieve encrypted packet + InputStream inputStream = getAdapter().getObject(PACKET_MANAGER_ACCOUNT, packetInfo.getId(), + packetInfo.getSource(), packetInfo.getProcess(), objectName); + + if (inputStream == null) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, objectName, + packetInfo.getProcess() + " Packet is not present in packet store."); + throw new PacketKeeperException(ErrorCode.PACKET_NOT_FOUND.getErrorCode(), + ErrorCode.PACKET_NOT_FOUND.getErrorMessage()); + } + byte[] encryptedSubPacket = IOUtils.toByteArray(inputStream); + + // Step 2: Load metadata + Map metaInfo = getAdapter().getMetaData(PACKET_MANAGER_ACCOUNT, packetInfo.getId(), + packetInfo.getSource(), packetInfo.getProcess(), objectName); + Packet packet = new Packet(); + + if (metaInfo != null && !metaInfo.isEmpty()) { + packet.setPacketInfo(PacketManagerHelper.getPacketInfo(metaInfo)); + } else { + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, objectName, + "metainfo not found for this packet"); + packet.setPacketInfo(packetInfo); + } + + // Step 3: Decrypt packet + byte[] decrypted = getCryptoService().decrypt( + helper.getRefId(packet.getPacketInfo().getId(), packet.getPacketInfo().getRefId()), + encryptedSubPacket); + packet.setPacket(decrypted); + + // Optional: Step 4 - Verify signature and integrity + if (!checkSignature(packet, encryptedSubPacket)) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, objectName, + "Packet Integrity and Signature check failed"); + throw new PacketIntegrityFailureException(); + } + + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, objectName, + "Packet successfully retrieved and verified"); + + return packet; + + } catch (Exception e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, packetInfo.getId(), + ExceptionUtils.getStackTrace(e)); + + if (e.getMessage() != null && e.getMessage().contains(OBJECT_DOESNOT_EXISTS) + && e.getMessage().contains(STATUS_404)) { + throw new ObjectDoesnotExistsException(); + } else if (e instanceof BaseCheckedException baseChecked) { + throw new PacketKeeperException(baseChecked.getErrorCode(), baseChecked.getMessage()); + } else if (e instanceof BaseUncheckedException baseUnchecked) { + throw new PacketKeeperException(baseUnchecked.getErrorCode(), baseUnchecked.getMessage()); + } + + throw new PacketKeeperException(PacketUtilityErrorCodes.PACKET_KEEPER_GET_ERROR.getErrorCode(), + "Exception occured reading packet : " + e.getMessage(), e); + } + } + + + /** + * Put packet into storage/cache + * + * @param packet : the Packet + * @return PacketInfo + */ + public PacketInfo putPacket(Packet packet) throws PacketKeeperException { + try { + // encrypt packet + byte[] encryptedSubPacket = getCryptoService().encrypt(packet.getPacketInfo().getRefId(), + packet.getPacket()); + + // put packet in object store + boolean uploaded = getAdapter().putObject(PACKET_MANAGER_ACCOUNT, packet.getPacketInfo().getId(), + packet.getPacketInfo().getSource(), packet.getPacketInfo().getProcess(), + packet.getPacketInfo().getPacketName(), new ByteArrayInputStream(encryptedSubPacket)); + + if (!uploaded) { + throw new PacketKeeperException(PacketUtilityErrorCodes.PACKET_KEEPER_PUT_ERROR.getErrorCode(), + "Unable to store packet in object store"); + } + + PacketInfo packetInfo = packet.getPacketInfo(); + // sign encrypted packet + packetInfo.setSignature(CryptoUtil.encodeToURLSafeBase64(getCryptoService().sign(packet.getPacket()))); + // generate encrypted packet hash + packetInfo.setEncryptedHash(CryptoUtil.encodeToURLSafeBase64(HMACUtils2.generateHash(encryptedSubPacket))); + + Map metaMap = PacketManagerHelper.getMetaMap(packetInfo); + metaMap = getAdapter().addObjectMetaData(PACKET_MANAGER_ACCOUNT, packet.getPacketInfo().getId(), + packet.getPacketInfo().getSource(), packet.getPacketInfo().getProcess(), + packet.getPacketInfo().getPacketName(), metaMap); + + return PacketManagerHelper.getPacketInfo(metaMap); + } catch (Exception e) { + String packetId = packet.getPacketInfo().getId(); + + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, packetId, + ExceptionUtils.getStackTrace(e)); + if (e instanceof BaseCheckedException ex) { + throw new PacketKeeperException(ex.getErrorCode(), ex.getMessage()); + } else if (e instanceof BaseUncheckedException ex) { + throw new PacketKeeperException(ex.getErrorCode(), ex.getMessage()); + } + + throw new PacketKeeperException(PacketUtilityErrorCodes.PACKET_KEEPER_PUT_ERROR.getErrorCode(), + "Failed to persist packet in object store : " + e.getMessage(), e); + } + } + + private ObjectStoreAdapter getAdapter() { + ObjectStoreAdapter adapter = adapterRegistry.get(adapterName); + if (adapter == null) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, "PacketKeeper", + "Invalid adapter name: " + adapterName); + throw new ObjectStoreAdapterException("Invalid adapter name configured: " + adapterName); + } + return adapter; + } + + private IPacketCryptoService getCryptoService() { + IPacketCryptoService cryptoService = cryptoRegistry.get(cryptoName); + if (cryptoService == null) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, "PacketKeeper", + "Invalid crypto name: " + cryptoName); + throw new CryptoException("Invalid crypto name configured: " + cryptoName); + } + return cryptoService; + } + + private static String getName(String id, String name) { + return id + UNDERSCORE + name; + } + + public boolean deletePacket(String id, String source, String process) { + return getAdapter().removeContainer(PACKET_MANAGER_ACCOUNT, id, source, process); + } + + public boolean pack(String id, String source, String process, String refId) { + return getAdapter().pack(PACKET_MANAGER_ACCOUNT, id, source, process, refId); + } public Map addTags(TagDto tagDto) { - Map tags = getAdapter().addTags(PACKET_MANAGER_ACCOUNT, tagDto.getId(), tagDto.getTags()); + Map tags = getAdapter().addTags(PACKET_MANAGER_ACCOUNT, tagDto.getId(), tagDto.getTags()); return tags; } public Map addorUpdate(TagDto tagDto) { - Map tags = getAdapter().addTags(PACKET_MANAGER_ACCOUNT, tagDto.getId(), tagDto.getTags()); - return tags; + Map tags = getAdapter().addTags(PACKET_MANAGER_ACCOUNT, tagDto.getId(), tagDto.getTags()); + return tags; } public Map getTags(String id) { - Map existingTags = getAdapter().getTags(PACKET_MANAGER_ACCOUNT, id); - return existingTags; + Map existingTags = getAdapter().getTags(PACKET_MANAGER_ACCOUNT, id); + return existingTags; } - public List getAll(String id) { - List allObjects = getAdapter().getAllObjects(PACKET_MANAGER_ACCOUNT, id); - return allObjects; - } + public List getAll(String id) { + List allObjects = getAdapter().getAllObjects(PACKET_MANAGER_ACCOUNT, id); + return allObjects; + } public void deleteTags(TagRequestDto tagRequestDto) { getAdapter().deleteTags(PACKET_MANAGER_ACCOUNT, tagRequestDto.getId(), tagRequestDto.getTagNames()); } -} +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/IdObjectsSchemaValidationOperationMapper.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/IdObjectsSchemaValidationOperationMapper.java index 65cffa48a7..fdb78f7d23 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/IdObjectsSchemaValidationOperationMapper.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/IdObjectsSchemaValidationOperationMapper.java @@ -1,10 +1,23 @@ package io.mosip.commons.packet.util; -import io.mosip.kernel.core.logger.spi.Logger; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + import org.springframework.stereotype.Component; +import io.mosip.kernel.core.logger.spi.Logger; + @Component public class IdObjectsSchemaValidationOperationMapper { + /* + * @Value("${mosip.kernel.applicant.type.age.limit}") private String ageLimit; + */ + + /** The reg proc logger. */ + private static Logger LOGGER = PacketManagerLogger.getLogger(IdObjectsSchemaValidationOperationMapper.class); + private static final String ENTRY_LOG = "IdObjectsSchemaValidationOperationMapper::getOperation()::entry"; + private static final String EXIT_LOG_PREFIX = "IdObjectsSchemaValidationOperationMapper::getOperation()::exit-"; enum SyncTypeDto { @@ -17,7 +30,6 @@ enum SyncTypeDto { /** The lost uin. */ LOST("LOST"), - /** The activate uin. */ ACTIVATED("ACTIVATED"), @@ -31,14 +43,14 @@ enum SyncTypeDto { RES_REPRINT("RES_REPRINT"); /** The value. */ - private String value; + private final String value; /** * Instantiates a new sync type dto. * * @param value the value */ - private SyncTypeDto (String value) { + private SyncTypeDto(String value) { this.value = value; } @@ -73,72 +85,36 @@ public String getOperation() { } } - /*@Value("${mosip.kernel.applicant.type.age.limit}") - private String ageLimit;*/ - - /** The reg proc logger. */ - private static Logger LOGGER = PacketManagerLogger.getLogger(IdObjectsSchemaValidationOperationMapper.class); - - public static String getOperation(String process) { - LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", - "IdObjectsSchemaValidationOperationMapper::getOperation()::entry"); - - if(process.equalsIgnoreCase(SyncTypeDto.NEW.getValue())) { - /*int age = 20;//utility.getApplicantAge(id); - int ageThreshold = Integer.parseInt(ageLimit); - if (age < ageThreshold) { - LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", - "IdObjectsSchemaValidationOperationMapper::getOperation()::exit-NEW child"); - return IdObjectValidatorSupportedOperations.CHILD_REGISTRATION; - }*/ - LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", - "IdObjectsSchemaValidationOperationMapper::getOperation()::exit-NEW"); - return IdObjectValidatorSupportedOperations.NEW_REGISTRATION.getOperation(); - } - else if(process.equalsIgnoreCase(SyncTypeDto.LOST.getValue())) { - LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", - "IdObjectsSchemaValidationOperationMapper::getOperation()::exit-LOST"); - return IdObjectValidatorSupportedOperations.LOST.getOperation(); - } - else if(process.equalsIgnoreCase(SyncTypeDto.UPDATE.getValue())) { - LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", - "IdObjectsSchemaValidationOperationMapper::getOperation()::exit-UPDATE"); - return IdObjectValidatorSupportedOperations.OTHER.getOperation(); - } - else if(process.equalsIgnoreCase(SyncTypeDto.RES_UPDATE.getValue())) { - LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", - "IdObjectsSchemaValidationOperationMapper::getOperation()::exit-RES_UPDATE"); - return IdObjectValidatorSupportedOperations.OTHER.getOperation(); - } - else if(process.equalsIgnoreCase(SyncTypeDto.ACTIVATED.getValue())) { - LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", - "IdObjectsSchemaValidationOperationMapper::getOperation()::exit-ACTIVATED"); - return IdObjectValidatorSupportedOperations.OTHER.getOperation(); - } - else if(process.equalsIgnoreCase(SyncTypeDto.DEACTIVATED.getValue())) { - LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", - "IdObjectsSchemaValidationOperationMapper::getOperation()::exit-DEACTIVATED"); - return IdObjectValidatorSupportedOperations.OTHER.getOperation(); - } - return PacketHelper.getProcessWithoutIteration(process).toLowerCase(); - + private static final Map PROCESS_TO_OPERATION; + + static { + Map map = new HashMap<>(); + map.put(SyncTypeDto.NEW.getValue(), IdObjectValidatorSupportedOperations.NEW_REGISTRATION.getOperation()); + map.put(SyncTypeDto.LOST.getValue(), IdObjectValidatorSupportedOperations.LOST.getOperation()); + map.put(SyncTypeDto.UPDATE.getValue(), IdObjectValidatorSupportedOperations.OTHER.getOperation()); + map.put(SyncTypeDto.RES_UPDATE.getValue(), IdObjectValidatorSupportedOperations.OTHER.getOperation()); + map.put(SyncTypeDto.ACTIVATED.getValue(), IdObjectValidatorSupportedOperations.OTHER.getOperation()); + map.put(SyncTypeDto.DEACTIVATED.getValue(), IdObjectValidatorSupportedOperations.OTHER.getOperation()); + PROCESS_TO_OPERATION = Collections.unmodifiableMap(map); } - /*private int getApplicantAge(String registrationId) throws IOException, ApisResourceAccessException, - PacketDecryptionFailureException, io.mosip.kernel.core.exception.IOException, RegistrationProcessorCheckedException, ApiNotAccessibleException { - - JSONObject regProcessorIdentityJson = getRegistrationProcessorMappingJson(); - String ageKey = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.AGE), VALUE); - String dobKey = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.DOB), VALUE); - + public static String getOperation(String process) { + LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", + ENTRY_LOG); - String applicantDob = JsonUtil.getJSONValue(getDemographicIdentityJSONObject(registrationId,dobKey), dobKey); - Integer applicantAge = JsonUtil.getJSONValue(getDemographicIdentityJSONObject(registrationId,ageKey), ageKey); - if (applicantDob != null) { - return calculateAge(applicantDob); - } else if (applicantAge != null) { - return applicantAge; + String normalizedProcess = process.toUpperCase(); + String operation = PROCESS_TO_OPERATION.get(normalizedProcess); + if (operation != null) { + LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", + EXIT_LOG_PREFIX + normalizedProcess); + return operation; } - }*/ -} + + // fallback to legacy logic + String fallback = PacketHelper.getProcessWithoutIteration(process).toLowerCase(); + LOGGER.debug(PacketManagerLogger.SESSIONID.toString(), PacketManagerLogger.REGISTRATIONID.toString(), "", + EXIT_LOG_PREFIX + "FALLBACK-" + fallback); + return fallback; + } +} \ No newline at end of file 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 bfcfa33457..67fe4ee023 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 @@ -4,21 +4,18 @@ package io.mosip.commons.packet.util; import static io.mosip.commons.packet.constants.PacketManagerConstants.FIELDCATEGORY; -import static io.mosip.commons.packet.constants.PacketManagerConstants.IDENTITY; -import static io.mosip.commons.packet.constants.PacketManagerConstants.PROPERTIES; -import static io.mosip.commons.packet.constants.PacketManagerConstants.RESPONSE; -import static io.mosip.commons.packet.constants.PacketManagerConstants.SCHEMA_JSON; import java.io.IOException; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; -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; @@ -29,6 +26,8 @@ import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; +import com.fasterxml.jackson.databind.ObjectMapper; + import io.mosip.commons.packet.constants.PacketManagerConstants; import io.mosip.commons.packet.exception.ApiNotAccessibleException; @@ -42,234 +41,195 @@ @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; - - @Value("${schema.default.fieldCategory:pvt,none}") - private String defaultFieldCategory; - - @Value("${IDSCHEMAURL:null}") - private String idschemaUrl; - - @Autowired - private ObjectMapper objMapper; - - @Autowired - @Qualifier("selfTokenRestTemplate") - private RestTemplate restTemplate; - - - /** - * Gets the source field category from id schema - * - * @param fieldName the field name in schema - * @param idschemaVersion : the idschema version used to create packet - * @return the source - * @throws IOException - */ - public String getSource(String fieldName, Double idschemaVersion) throws IOException, ApiNotAccessibleException { - String idSchema = getIdSchema(idschemaVersion); - JSONObject properties = getJSONObjFromStr(idSchema, PROPERTIES); - JSONObject identity = getJSONObj(properties, IDENTITY); - JSONObject property = getJSONObj(identity, PROPERTIES); - JSONObject value = getJSONObj(property, fieldName); - String fieldCategory = getFieldCategory(value); - return fieldCategory; - } - - /** - * Get the id schema from syncdata service - * - * @return idschema as string - * @throws ApiNotAccessibleException - * @throws IOException - */ - public String getIdSchema(Double version) throws ApiNotAccessibleException, IOException { - if (idschema != null && !idschema.isEmpty() && idschema.get(version) != null) - return idschema.get(version); - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(idschemaUrl); - if (version != null) - builder.queryParam(PacketManagerConstants.SCHEMA_VERSION_QUERY_PARAM, version); - UriComponents uriComponents = builder.build(false).encode(); - - String response = restTemplate.getForObject(uriComponents.toUri(), String.class); - String responseString = null; - try { - JSONObject jsonObject = new JSONObject(response); - JSONObject respObj = (JSONObject) jsonObject.get(RESPONSE); - responseString = respObj != null ? (String) respObj.get(SCHEMA_JSON) : null; - } catch (JSONException e) { - throw new IOException(e); - } - - if (responseString != null) { - if (idschema == null) { - idschema = new HashMap<>(); - idschema.put(version, responseString); - } else - idschema.put(version, responseString); - } else - throw new ApiNotAccessibleException("Could not get id schema"); - - return idschema.get(version); - } - - /** - * Gets the field category. - * - * @param jsonObject the json object - * @return the field category - */ - private String getFieldCategory(JSONObject jsonObject) { - String fieldCategory = null; - try { - fieldCategory = jsonObject != null ? jsonObject.getString(FIELDCATEGORY) : null; - } catch (JSONException e) { - fieldCategory = null; - } - String[] defaultCategories = defaultFieldCategory != null ? defaultFieldCategory.split(",") : null; - if (fieldCategory != null && defaultCategories != null - && ArrayUtils.contains(defaultCategories, fieldCategory)) { - fieldCategory = defaultSource; - } - return fieldCategory; - } - - /** - * Search a field in json - * - * @param jsonObject - * @param id - * @return - */ - private JSONObject getJSONObj(JSONObject jsonObject, String id) { - try { - return (jsonObject == null) ? null : (JSONObject) jsonObject.get(id); - } catch (JSONException e) { - return null; - } - } - - /** - * Search a field in json string - * - * @param jsonString - * @param id - * @return - */ - private JSONObject getJSONObjFromStr(String jsonString, String id) { - try { - return (jsonString == null) ? null : (JSONObject) new JSONObject(jsonString).get(id); - } catch (JSONException e) { - 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; - } -} + private static Map categorySubpacketMapping = new HashMap<>(); + private static final Map idSchemaCache = new ConcurrentHashMap<>(); + + private org.json.simple.JSONObject mappingJsonObject = null; + 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; + + @Value("${schema.default.fieldCategory:pvt,none}") + private String defaultFieldCategory; + + @Value("${IDSCHEMAURL:null}") + private String idschemaUrl; + + @Autowired + private ObjectMapper objMapper; + + @Autowired + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + + /** + * Gets the source field category from id schema + * + * @param fieldName the field name in schema + * @param idschemaVersion : the idschema version used to create packet + * @return the source + * @throws IOException + */ + public String getSource(String fieldName, Double idschemaVersion) throws IOException, ApiNotAccessibleException { + String idSchema = getIdSchema(idschemaVersion); + JSONObject fieldObj; + try { + fieldObj = getFieldFromSchema(idSchema, fieldName); + } catch (JSONException e) { + throw new IOException(e); + } + return resolveFieldCategory(fieldObj); + } + + /** + * Get the id schema from syncdata service + * + * @return idschema as string + * @throws ApiNotAccessibleException + * @throws IOException + */ + public String getIdSchema(Double version) throws ApiNotAccessibleException, IOException { + if (idschema == null) { + idschema = new HashMap<>(); + } + + // Check cache first + if (idschema.containsKey(version)) { + return idschema.get(version); + } + + // Build URI with query param + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(idschemaUrl); + if (version != null) { + builder.queryParam(PacketManagerConstants.SCHEMA_VERSION_QUERY_PARAM, version); + } + UriComponents uriComponents = builder.build(false).encode(); + + // Make REST call + String response; + try { + response = restTemplate.getForObject(uriComponents.toUri(), String.class); + } catch (Exception e) { + throw new ApiNotAccessibleException("Failed to fetch ID schema from URL: " + uriComponents.toUri(), e); + } + + // Parse JSON + String responseString; + try { + JSONObject jsonObject = new JSONObject(response); + JSONObject respObj = jsonObject.optJSONObject(RESPONSE); + responseString = respObj != null ? respObj.optString(SCHEMA_JSON, null) : null; + } catch (JSONException e) { + throw new IOException("Invalid JSON received from ID Schema service", e); + } + + // Final validation and cache + if (responseString == null) { + throw new ApiNotAccessibleException("Could not get ID schema for version: " + version); + } + + idschema.put(version, responseString); + return responseString; + } + + private JSONObject getFieldFromSchema(String schemaJson, String fieldName) throws JSONException { + JSONObject schema = new JSONObject(schemaJson).getJSONObject(PROPERTIES).getJSONObject(IDENTITY) + .getJSONObject(PROPERTIES); + return schema.getJSONObject(fieldName); + } + + private String resolveFieldCategory(JSONObject jsonObject) { + String category = jsonObject.optString(FIELDCATEGORY, null); + if (category != null && defaultFieldCategory != null + && ArrayUtils.contains(defaultFieldCategory.split(","), category)) { + return defaultSource; + } + return category; + } + + public List getDefaultFields(Double schemaVersion) throws JSONException, IOException { + List> defaultFieldMaps = loadDefaultFields(schemaVersion); + List fieldIds = new ArrayList<>(defaultFieldMaps.size()); + defaultFieldMaps.forEach(map -> fieldIds.add(map.get(SCHEMA_ID))); + return fieldIds; + } + + public List> loadDefaultFields(Double schemaVersion) throws JSONException, IOException { + JSONObject identitySchema = getIdentityFieldsSchema(getIdSchema(schemaVersion)); + Map>> packetBasedMap = new HashMap<>(); + + Iterator fieldNames = identitySchema.keys(); + while (fieldNames.hasNext()) { + String fieldName = fieldNames.next(); + JSONObject fieldDetail = identitySchema.getJSONObject(fieldName); + String category = fieldDetail.optString(SCHEMA_CATEGORY, "none"); + String[] packets = categorySubpacketMapping.getOrDefault(category.toLowerCase(), "id").split(","); + + for (String packet : packets) { + packetBasedMap.computeIfAbsent(packet, k -> new ArrayList<>()); + Map attr = new HashMap<>(); + attr.put(SCHEMA_ID, fieldName); + attr.put(SCHEMA_TYPE, fieldDetail.has(SCHEMA_REF) ? fieldDetail.getString(SCHEMA_REF) + : fieldDetail.optString(SCHEMA_TYPE, "string")); // Default to "string" if missing + packetBasedMap.get(packet).add(attr); + } + } + + return packetBasedMap.getOrDefault("id", Collections.emptyList()); + } + + private JSONObject getIdentityFieldsSchema(String schemaJson) throws JSONException { + return new JSONObject(schemaJson).getJSONObject(PROPERTIES).getJSONObject(IDENTITY).getJSONObject(PROPERTIES); + } + + public String getIdschemaVersionFromMappingJson() throws IOException { + return getJSONValue(getJSONObject(getMappingJson(), PacketManagerConstants.IDSCHEMA_VERSION), + PacketManagerConstants.VALUE); + } + + 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, IDENTITY); + } + + public static org.json.simple.JSONObject getJSONObject(org.json.simple.JSONObject jsonObject, Object key) { + if (jsonObject == null) + return null; + LinkedHashMap map = (LinkedHashMap) jsonObject.get(key); + return map != null ? new org.json.simple.JSONObject(map) : null; + } + + public static T getJSONValue(org.json.simple.JSONObject jsonObject, String key) { + return (jsonObject != null) ? (T) jsonObject.get(key) : null; + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketHelper.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketHelper.java index 90241a8c9b..b86fb38b94 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketHelper.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketHelper.java @@ -1,148 +1,136 @@ package io.mosip.commons.packet.util; -import io.mosip.commons.packet.dto.packet.ProviderDto; -import io.mosip.commons.packet.exception.NoAvailableProviderException; -import org.apache.commons.lang3.StringUtils; - import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; + +import io.mosip.commons.packet.dto.packet.ProviderDto; +import io.mosip.commons.packet.exception.NoAvailableProviderException; + public class PacketHelper { - private static final String SOURCE = "source"; - private static final String PROCESS = "process"; - private static final String CLASSNAME = "classname"; - private static final String DASH = "-"; - - private static List readerProvider = null; - - private static List writerProvider = null; - - public enum Provider { - READER, WRITER; - } - - /** - * The providerConfig. - */ - private static Map readerConfiguration; - /** - * The providerConfig. - */ - private static Map writerConfiguration; - - public static Set getReaderProvider(Map readerConfig) { - readerConfiguration = readerConfig; - Set readerProvider = null; - List providerDtos = getReader(readerConfig); - if (providerDtos != null && !providerDtos.isEmpty()) { - readerProvider = providerDtos.stream().map(p -> p.getClassName()).collect(Collectors.toSet()); - } - return readerProvider; - } - - public static Set getWriterProvider(Map writerConfig) { - writerConfiguration = writerConfig; - Set writerProvider = null; - List providerDtos = getWriter(writerConfig); - if (providerDtos != null && !providerDtos.isEmpty()) { - writerProvider = providerDtos.stream().map(p -> p.getClassName()).collect(Collectors.toSet()); - } - return writerProvider; - } - - public static boolean isSourceAndProcessPresent(String providerName, String providerSource, String providerProcess, Provider providerEnum) { - List configurations = null; - - String process = PacketHelper.getProcessWithoutIteration(providerProcess); - - if (Provider.READER.equals(providerEnum)) - configurations = getReader(readerConfiguration); - else if (Provider.WRITER.equals(providerEnum)) - configurations = getWriter(writerConfiguration); - - if (configurations == null) - throw new NoAvailableProviderException(); - - Optional providerDto = configurations.stream().filter(dto -> dto.getSource().toUpperCase().contains(providerSource.toUpperCase()) - && dto.getProcess().toUpperCase().contains(process.toUpperCase())).findAny(); - return providerDto.isPresent() && providerDto.get() != null && providerName.contains(providerDto.get().getClassName()); - } - - private static List getReader(Map readerConfiguration) { - if (readerProvider == null) { - List providerDtos = new ArrayList<>(); - if (readerConfiguration != null && !readerConfiguration.isEmpty()) { - for (String value : readerConfiguration.values()) { - String[] values = value.split(","); - ProviderDto providerDto = new ProviderDto(); - for (String provider : values) { - if (provider != null) { - if (provider.startsWith(SOURCE)) - providerDto.setSource(provider.replace(SOURCE + ":", "")); - else if (provider.startsWith(PROCESS)) - providerDto.setProcess(provider.replace(PROCESS + ":", "")); - else if (provider.startsWith(CLASSNAME)) - providerDto.setClassName(provider.replace(CLASSNAME + ":", "")); - } - } - providerDtos.add(providerDto); - } - } - readerProvider = providerDtos; - } - - return readerProvider; - } - - private static List getWriter(Map writerConfiguration) { - if (writerProvider == null) { - List providerDtos = new ArrayList<>(); - if (writerConfiguration != null && !writerConfiguration.isEmpty()) { - for (String value : writerConfiguration.values()) { - String[] values = value.split(","); - ProviderDto providerDto = new ProviderDto(); - for (String provider : values) { - if (provider != null) { - if (provider.startsWith(SOURCE)) - providerDto.setSource(provider.replace(SOURCE + ":", "")); - else if (provider.startsWith(PROCESS)) - providerDto.setProcess(provider.replace(PROCESS + ":", "")); - else if (provider.startsWith(CLASSNAME)) - providerDto.setClassName(provider.replace(CLASSNAME + ":", "")); - } - } - providerDtos.add(providerDto); - } - } - writerProvider = providerDtos; - } - return writerProvider; - } - - /** - * This method returns process without iteration. It search iteration pattern at the end of the process string. - * If found then this method removes iteration and only returns process. - * - * @param process - * @return - */ - public static String getProcessWithoutIteration(String process) { - if (StringUtils.isNotEmpty(process)) { - // if number is present at the end preceded by '-' (DASH) - String[] processArr = process.split(DASH); - String lastElement = processArr[processArr.length - 1]; - if (StringUtils.isNumeric(lastElement)) { - StringBuffer sb = new StringBuffer(); - sb.append(DASH); - sb.append(lastElement); - process = process.replace(sb.toString(), ""); - } - } - return process; - } -} + private static final String SOURCE = "source"; + private static final String PROCESS = "process"; + private static final String CLASSNAME = "classname"; + private static final String DASH = "-"; + + private static List readerProvider = null; + private static List writerProvider = null; + + public enum Provider { + READER, WRITER; + } + + /** + * The providerConfig. + */ + private static Map readerConfiguration; + /** + * The providerConfig. + */ + private static Map writerConfiguration; + + public static Set getReaderProvider(Map config) { + readerConfiguration = config; + return getProviderClassNames(getReader(config)); + } + + public static Set getWriterProvider(Map config) { + writerConfiguration = config; + return getProviderClassNames(getWriter(config)); + } + + public static boolean isSourceAndProcessPresent(String providerName, String providerSource, String providerProcess, + Provider type) { + List configurations = switch (type) { + case READER -> getReader(readerConfiguration); + case WRITER -> getWriter(writerConfiguration); + }; + + if (configurations == null || configurations.isEmpty()) { + throw new NoAvailableProviderException(); + } + + String process = getProcessWithoutIteration(providerProcess); + String baseProviderName = getBaseClassName(providerName); + boolean matchFound = configurations.stream() + .anyMatch(dto -> StringUtils.containsIgnoreCase(dto.getSource(), providerSource) + && StringUtils.containsIgnoreCase(dto.getProcess(), process) + && StringUtils.containsIgnoreCase(baseProviderName, dto.getClassName())); + + return matchFound; + } + + private static String getBaseClassName(String providerName) { + int idx = providerName.indexOf("$$"); + return idx > 0 ? providerName.substring(0, idx) : providerName; + } + + private static List getReader(Map config) { + if (readerProvider == null) { + readerProvider = parseConfiguration(config); + } + return readerProvider; + } + + private static List getWriter(Map config) { + if (writerProvider == null) { + writerProvider = parseConfiguration(config); + } + return writerProvider; + } + + private static List parseConfiguration(Map config) { + List providers = new ArrayList<>(); + if (config != null && !config.isEmpty()) { + for (String value : config.values()) { + ProviderDto dto = new ProviderDto(); + for (String token : value.split(",")) { + token = token.trim(); // Trim whitespace + if (token.startsWith(SOURCE + ":")) { + dto.setSource(token.substring((SOURCE + ":").length()).trim()); + } else if (token.startsWith(PROCESS + ":")) { + dto.setProcess(token.substring((PROCESS + ":").length()).trim()); + } else if (token.startsWith(CLASSNAME + ":")) { + dto.setClassName(token.substring((CLASSNAME + ":").length()).trim()); + } + } + providers.add(dto); + } + } + return providers; + } + + private static Set getProviderClassNames(List providers) { + return providers == null ? Collections.emptySet() + : providers.stream().map(ProviderDto::getClassName).collect(Collectors.toSet()); + } + + /** + * This method returns process without iteration. It search iteration pattern at + * the end of the process string. If found then this method removes iteration + * and only returns process. + * + * @param process + * @return + */ + public static String getProcessWithoutIteration(String process) { + if (StringUtils.isNotEmpty(process)) { + // if number is present at the end preceded by '-' (DASH) + String[] processArr = process.split(DASH); + String lastElement = processArr[processArr.length - 1]; + if (StringUtils.isNumeric(lastElement)) { + StringBuffer sb = new StringBuffer(); + sb.append(DASH); + sb.append(lastElement); + process = process.replace(sb.toString(), ""); + } + } + return process; + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketManagerHelper.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketManagerHelper.java index 08dd5374ce..af75172899 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketManagerHelper.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketManagerHelper.java @@ -17,13 +17,10 @@ import java.io.InputStream; import java.net.URL; import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; -import io.mosip.kernel.biometrics.entities.*; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -31,112 +28,111 @@ import io.mosip.commons.packet.constants.PacketManagerConstants; import io.mosip.commons.packet.dto.PacketInfo; import io.mosip.kernel.biometrics.commons.CbeffValidator; -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.constant.ProcessedLevelType; -import io.mosip.kernel.biometrics.constant.PurposeType; -import io.mosip.kernel.biometrics.constant.QualityType; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; import io.mosip.kernel.cbeffutil.container.impl.CbeffContainerImpl; import io.mosip.kernel.core.util.HMACUtils2; @Component public class PacketManagerHelper { - /** - * The config server file storage URL. - */ - @Value("${mosip.kernel.xsdstorage-uri}") - private String configServerFileStorageURL; - - @Value("${mosip.kernel.registrationcenterid.length:5}") - private int centerIdLength; - - @Value("${mosip.kernel.machineid.length:5}") - private int machineIdLength; - - /* - * XSD file name - */ - - /** - * The schema name. - */ - @Value("${mosip.kernel.xsdfile}") - private String schemaName; - - - public byte[] getXMLData(BiometricRecord biometricRecord, boolean offlineMode) throws Exception { - try (InputStream xsd = (offlineMode) && getClass().getClassLoader().getResourceAsStream(PacketManagerConstants.CBEFF_SCHEMA_FILE_PATH) != null ? - getClass().getClassLoader().getResourceAsStream(PacketManagerConstants.CBEFF_SCHEMA_FILE_PATH) : - new URL(configServerFileStorageURL + schemaName).openStream()) { - CbeffContainerImpl cbeffContainer = new CbeffContainerImpl(); - BIR bir = cbeffContainer.createBIRType(biometricRecord.getSegments()); - HashMap entries = new HashMap(); - biometricRecord.getOthers().forEach((k, v) -> { - entries.put(k, v); - }); + private static final String UNDERSCORE = "_"; + + /** + * The config server file storage URL. + */ + @Value("${mosip.kernel.xsdstorage-uri}") + private String configServerFileStorageURL; + + @Value("${mosip.kernel.registrationcenterid.length:5}") + private int centerIdLength; + + @Value("${mosip.kernel.machineid.length:5}") + private int machineIdLength; + + /** + * The schema name. + */ + @Value("${mosip.kernel.xsdfile}") + private String schemaName; + + public byte[] getXMLData(BiometricRecord biometricRecord, boolean offlineMode) throws Exception { + try (InputStream xsd = getXsdStream(offlineMode)) { + CbeffContainerImpl cbeffContainer = new CbeffContainerImpl(); + BIR bir = cbeffContainer.createBIRType(biometricRecord.getSegments()); + HashMap entries = new HashMap<>(); + entries.putAll(biometricRecord.getOthers()); bir.setOthers(entries); - return CbeffValidator.createXMLBytes(bir, IOUtils.toByteArray(xsd)); + return CbeffValidator.createXMLBytes(bir, IOUtils.toByteArray(xsd)); + } + } + + private InputStream getXsdStream(boolean offlineMode) throws IOException { + InputStream resourceStream = null; + if (offlineMode) { + resourceStream = getClass().getClassLoader().getResourceAsStream(PacketManagerConstants.CBEFF_SCHEMA_FILE_PATH); } + return resourceStream != null ? resourceStream : new URL(configServerFileStorageURL + schemaName).openStream(); } - - public static byte[] generateHash(List order, Map data) throws IOException, NoSuchAlgorithmException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - if (order != null && !order.isEmpty()) { + + public static byte[] generateHash(List order, Map data) + throws IOException, NoSuchAlgorithmException { + if (order == null || order.isEmpty()) return null; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { for (String name : order) { - outputStream.write(data.get(name)); + byte[] value = data.get(name); + if (value != null) { + outputStream.write(value); + } } return HMACUtils2.digestAsPlainText(outputStream.toByteArray()).getBytes(); } - return null; - } - - public static Map getMetaMap(PacketInfo packetInfo) { - Map metaMap = new HashMap<>(); - metaMap.put(ID, packetInfo.getId()); - metaMap.put(PACKET_NAME, packetInfo.getPacketName()); - metaMap.put(SOURCE, packetInfo.getSource()); - metaMap.put(PROCESS, packetInfo.getProcess()); - metaMap.put(SCHEMA_VERSION, packetInfo.getSchemaVersion()); - metaMap.put(SIGNATURE, packetInfo.getSignature()); - metaMap.put(ENCRYPTED_HASH, packetInfo.getEncryptedHash()); - metaMap.put(PROVIDER_NAME, packetInfo.getProviderName()); - metaMap.put(PROVIDER_VERSION, packetInfo.getProviderVersion()); - metaMap.put(CREATION_DATE, packetInfo.getCreationDate()); - metaMap.put(REFID, packetInfo.getRefId()); - return metaMap; - } - - public static PacketInfo getPacketInfo(Map metaMap) { - PacketInfo packetInfo = new PacketInfo(); - packetInfo.setId((String) metaMap.get(ID)); - packetInfo.setPacketName((String) metaMap.get(PACKET_NAME)); - packetInfo.setSource((String) metaMap.get(SOURCE)); - packetInfo.setProcess((String) metaMap.get(PROCESS)); - packetInfo.setSchemaVersion((String) metaMap.get(SCHEMA_VERSION)); - packetInfo.setSignature((String) metaMap.get(SIGNATURE)); - packetInfo.setEncryptedHash((String) metaMap.get(ENCRYPTED_HASH)); - packetInfo.setProviderName((String) metaMap.get(PROVIDER_NAME)); - packetInfo.setProviderVersion((String) metaMap.get(PROVIDER_VERSION)); - packetInfo.setCreationDate((String) metaMap.get(CREATION_DATE)); - packetInfo.setRefId((String) metaMap.get(REFID)); - return packetInfo; - } - - /** - * This code is added for backward compatibility - * - * @param id - * @param refId - * @return - */ - public String getRefId(String id, String refId) { - if (refId != null) - return refId; - else { - String centerId = id.substring(0, centerIdLength); - String machineId = id.substring(centerIdLength, centerIdLength + machineIdLength); - return centerId + "_" + machineId; - } - } - -} + } + + public static Map getMetaMap(PacketInfo packetInfo) { + Map metaMap = new HashMap<>(); + metaMap.put(ID, packetInfo.getId()); + metaMap.put(PACKET_NAME, packetInfo.getPacketName()); + metaMap.put(SOURCE, packetInfo.getSource()); + metaMap.put(PROCESS, packetInfo.getProcess()); + metaMap.put(SCHEMA_VERSION, packetInfo.getSchemaVersion()); + metaMap.put(SIGNATURE, packetInfo.getSignature()); + metaMap.put(ENCRYPTED_HASH, packetInfo.getEncryptedHash()); + metaMap.put(PROVIDER_NAME, packetInfo.getProviderName()); + metaMap.put(PROVIDER_VERSION, packetInfo.getProviderVersion()); + metaMap.put(CREATION_DATE, packetInfo.getCreationDate()); + metaMap.put(REFID, packetInfo.getRefId()); + return metaMap; + } + + public static PacketInfo getPacketInfo(Map metaMap) { + PacketInfo packetInfo = new PacketInfo(); + packetInfo.setId((String) metaMap.get(ID)); + packetInfo.setPacketName((String) metaMap.get(PACKET_NAME)); + packetInfo.setSource((String) metaMap.get(SOURCE)); + packetInfo.setProcess((String) metaMap.get(PROCESS)); + packetInfo.setSchemaVersion((String) metaMap.get(SCHEMA_VERSION)); + packetInfo.setSignature((String) metaMap.get(SIGNATURE)); + packetInfo.setEncryptedHash((String) metaMap.get(ENCRYPTED_HASH)); + packetInfo.setProviderName((String) metaMap.get(PROVIDER_NAME)); + packetInfo.setProviderVersion((String) metaMap.get(PROVIDER_VERSION)); + packetInfo.setCreationDate((String) metaMap.get(CREATION_DATE)); + packetInfo.setRefId((String) metaMap.get(REFID)); + return packetInfo; + } + + /** + * This code is added for backward compatibility + * + * @param id + * @param refId + * @return + */ + public String getRefId(String id, String refId) { + if (refId != null && !refId.isEmpty()) return refId; + + String centerId = id.substring(0, centerIdLength); + String machineId = id.substring(centerIdLength, centerIdLength + machineIdLength); + return centerId + UNDERSCORE + machineId; + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketManagerLogger.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketManagerLogger.java index d6561b51db..8bd12ed72a 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketManagerLogger.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/PacketManagerLogger.java @@ -3,25 +3,29 @@ import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.logger.logback.factory.Logfactory; -public class PacketManagerLogger { +/** + * Utility class to provide pre-defined log keys and logger instance for Packet Manager. + */ +public final class PacketManagerLogger { public static final String SESSIONID = "SESSION_ID"; public static final String REGISTRATIONID = "REGISTRATION_ID"; public static final String REFERENCEID = "REFERENCE_ID"; - + /** - * Instantiates a new packet manager logger. + * Private constructor to prevent instantiation. */ private PacketManagerLogger() { + // Prevent instantiation } /** - * Gets the logger. + * Returns a logger for the given class using SLF4J implementation. * - * @param clazz the clazz - * @return the logger + * @param clazz the class for which the logger is to be created + * @return the logger instance */ public static Logger getLogger(Class clazz) { return Logfactory.getSlf4jLogger(clazz); } -} +} \ No newline at end of file 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 8b6ec394da..b316c4fd25 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 @@ -1,8 +1,8 @@ package io.mosip.commons.packet.util; import static io.mosip.commons.packet.constants.PacketManagerConstants.IDENTITY; -import static io.mosip.commons.packet.constants.PacketManagerConstants.IDSCHEMA_VERSION; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -11,324 +11,334 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Stream; -import com.fasterxml.jackson.core.type.TypeReference; -import io.mosip.commons.packet.facade.PacketReader; -import io.mosip.kernel.core.exception.ExceptionUtils; -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; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.nimbusds.jose.util.StandardCharset; import io.mosip.commons.packet.audit.AuditLogEntry; 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.packet.FieldValueArray; -import io.mosip.commons.packet.exception.GetAllMetaInfoException; import io.mosip.commons.packet.exception.PacketKeeperException; +import io.mosip.commons.packet.facade.PacketReader; import io.mosip.commons.packet.keeper.PacketKeeper; +import io.mosip.kernel.core.exception.ExceptionUtils; 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.idobjectvalidator.spi.IdObjectValidator; import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.HMACUtils2; import io.mosip.kernel.core.util.JsonUtils; import io.mosip.kernel.core.util.exception.JsonProcessingException; @Component public class PacketValidator { - @Value("${mosip.commons.packetnames:id}") - private String packetNames; - - @Value("${mosip.commons.packet.manager.schema.validator.convertIdSchemaToDouble:true}") - private boolean convertIdschemaToDouble; - - private static final Logger LOGGER = PacketManagerLogger.getLogger(PacketValidator.class); - private static final String FIELD_LIST = "mosip.kernel.idobjectvalidator.mandatory-attributes.reg-processor.%s"; - - private static final String eventId = "PACKET_MANAGER"; - private static final String eventName = "PACKET MANAGER"; - private static final String eventType = "SYSTEM"; - - @Autowired - private PacketReader reader; - - @Autowired - private Environment env; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private PacketKeeper packetKeeper; - - @Autowired - private IdObjectValidator idObjectValidator; - - @Autowired - private IdSchemaUtils idSchemaUtils; - - @Autowired - private AuditLogEntry auditLogEntry; - - - 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); - auditLogEntry.addAudit("Id object validation successful", eventId, eventName, eventType, null, null, id); - result = fileAndChecksumValidation(id, source, process); - } else { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "Id object validation failed for process name : " + process); - auditLogEntry.addAudit("Id object validation failed", eventId, eventName, eventType, null, null, id); - } - - return result; - } - - private boolean validateSchema(String id, String source, String process) throws IOException, InvalidIdSchemaException, IdObjectIOException, JSONException { - Map objectMap = new HashMap<>(); - try { - 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))); - if (fields != null) { - LinkedHashMap finalMap = new LinkedHashMap(); - 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(","))); - - } - + @Value("${mosip.commons.packetnames:id}") + private String packetNames; + + @Value("${mosip.commons.packet.manager.schema.validator.convertIdSchemaToDouble:true}") + private boolean convertIdschemaToDouble; + + private static final Logger LOGGER = PacketManagerLogger.getLogger(PacketValidator.class); + private static final String FIELD_LIST = "mosip.kernel.idobjectvalidator.mandatory-attributes.reg-processor.%s"; + private static final String eventId = "PACKET_MANAGER"; + private static final String eventName = "PACKET MANAGER"; + private static final String eventType = "SYSTEM"; + + @Autowired + private PacketReader reader; + + @Autowired + private Environment env; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private PacketKeeper packetKeeper; + + @Autowired + private IdObjectValidator idObjectValidator; + + @Autowired + private IdSchemaUtils idSchemaUtils; + + @Autowired + private AuditLogEntry auditLogEntry; + + public boolean validate(String id, String source, String process) + throws IdObjectIOException, InvalidIdSchemaException, IOException, JsonProcessingException, + PacketKeeperException, NoSuchAlgorithmException, JSONException { + boolean schemaResult = validateSchema(id, source, process); + String schemaLogMessage = schemaResult ? "Id object validation successful" : "Id object validation failed"; + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "{} for process: {}", + schemaLogMessage, process); + auditLogEntry.addAudit(schemaLogMessage, eventId, eventName, eventType, null, null, id); + + return schemaResult && fileAndChecksumValidation(id, source, process); + } + + private boolean validateSchema(String id, String source, String process) + throws IOException, InvalidIdSchemaException, IdObjectIOException, JSONException { + Map objectMap = new HashMap<>(); + try { + String idschemaKey = idSchemaUtils.getIdschemaVersionFromMappingJson(); + String idschemaVersion = reader.getField(id, idschemaKey, source, process, false); + List allFields = idSchemaUtils.getDefaultFields(Double.valueOf(idschemaVersion)); + Map fieldsMap = reader.getFields(id, allFields, source, process, false); + objectMap.putAll(fieldsMap); + + if (convertIdschemaToDouble && fieldsMap.get(idschemaKey) != null) { + objectMap.put(idschemaKey, Double.valueOf(fieldsMap.get(idschemaKey))); + } + + String mandatoryFields = env.getProperty( + String.format(FIELD_LIST, IdObjectsSchemaValidationOperationMapper.getOperation(process))); + if (mandatoryFields == null || mandatoryFields.isEmpty()) { + LOGGER.warn(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "No mandatory field configuration found for process: {}", process); + return false; + } + + LinkedHashMap finalMap = new LinkedHashMap<>(); + finalMap.put(IDENTITY, loadDemographicIdentity(objectMap)); + JSONObject finalIdObject = new JSONObject(finalMap); + + boolean result = idObjectValidator.validateIdObject( + idSchemaUtils.getIdSchema( + Double.valueOf(objectMap.get(PacketManagerConstants.IDSCHEMA_VERSION).toString())), + finalIdObject, Arrays.asList(mandatoryFields.split(","))); + + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "Schema validation result for process {}: {}", process, result); + return result; + } catch (IdObjectValidationFailedException e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "Id object masterdata validation failed with errors: {}", e.getErrorTexts()); return false; - } catch (IdObjectValidationFailedException e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, - "Id object masterdata validation failed with errors: " + e.getErrorTexts()); - return false; - } - - } - - /** - * Files validation. - * - * @param id - * the registration id - * @return true, if successful - * @throws IOException - */ - public boolean fileAndChecksumValidation(String id, String source, String process) throws IOException, JsonProcessingException, PacketKeeperException, NoSuchAlgorithmException { - boolean isValid = false; - // perform file and checksum validation for each source - for (String packetName : packetNames.split(",")) { - Packet packet = packetKeeper.getPacket(getPacketInfo(id, packetName, source, process)); - Map finalMap = getMetaInfoJson(packet); - if (!finalMap.isEmpty()) { - - List hashseq1List = finalMap.get("hashSequence1") != null ? mapper.readValue(finalMap.get("hashSequence1"), ArrayList.class) : null; - List hashseq2List = finalMap.get("hashSequence2") != null ? (ArrayList) mapper.readValue(finalMap.get("hashSequence2"), ArrayList.class) : null; - Map checksumMap = new HashMap<>(); - - boolean fileValidation = validateFiles(hashseq1List, hashseq2List, checksumMap, packet); - - if (fileValidation) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "File validation successful for packet name : " + packetName); - auditLogEntry.addAudit("File validation successful", eventId, eventName, eventType, null, null, id); - } else { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "File validation failed for packet name : " + packetName); - auditLogEntry.addAudit("File validation failed", eventId, eventName, eventType, null, null, id); - return false; - } - - boolean checksumValidation = checksumValidation(hashseq1List, hashseq2List, checksumMap, packet); - - if (checksumValidation) { - LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "Checksum validation successful for packet name : " + packetName); - auditLogEntry.addAudit("Checksum validation successful", eventId, eventName, eventType, null, null, id); - } else { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "Checksum validation failed for packet name : " + packetName); - auditLogEntry.addAudit("Checksum validation failed", eventId, eventName, eventType, null, null, id); - return false; - } - - isValid = true; - } - - } - return isValid; - } - - private PacketInfo getPacketInfo(String id, String packetName, String source, String process) { - PacketInfo packetInfo = new PacketInfo(); - packetInfo.setId(id); - packetInfo.setPacketName(packetName); - packetInfo.setProcess(process); - packetInfo.setSource(source); - return packetInfo; - } - - private byte[] generateHash(List hashSequence, Map checksumMap) throws NoSuchAlgorithmException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - for (FieldValueArray fieldValueArray : hashSequence) { - List hashValues = fieldValueArray.getValue(); - hashValues.forEach(value -> { - byte[] valuebyte = null; - try { - InputStream fileStream = checksumMap.get(value); - valuebyte = IOUtils.toByteArray(fileStream); - outputStream.write(valuebyte); - } catch (IOException e) { - LOGGER.error("Exception while generating hash " + ExceptionUtils.getStackTrace(e)); - } - }); - } - - return HMACUtils2.digestAsPlainText(outputStream.toByteArray()).getBytes(); - - } - - private Map getMetaInfoJson(Packet packet) throws PacketKeeperException, IOException { - Map finalMap = new HashMap<>(); - InputStream metaInfoJson = ZipUtils.unzipAndGetFile(packet.getPacket(), "PACKET_META_INFO"); - if (metaInfoJson != null) { - byte[] bytearray = IOUtils.toByteArray(metaInfoJson); - String jsonString = new String(bytearray); - LinkedHashMap currentIdMap = (LinkedHashMap) mapper.readValue(jsonString, LinkedHashMap.class).get(IDENTITY); - - currentIdMap.keySet().stream().forEach(key -> { - try { - finalMap.putIfAbsent(key, currentIdMap.get(key) != null ? JsonUtils.javaObjectToJsonString(currentIdMap.get(key)) : null); - } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { - throw new GetAllMetaInfoException(e.getMessage()); - } - }); - } - return finalMap; - } - - private boolean validateFiles(List hashseq1List, List hashseq2List, Map checksumMap, Packet packet) throws JsonProcessingException, IOException { - List allFileNames = new ArrayList<>(); - if (hashseq1List != null && !hashseq1List.isEmpty()) { - for (Object o : hashseq1List) { - FieldValueArray fieldValueArray = mapper.readValue(JsonUtils.javaObjectToJsonString(o), FieldValueArray.class); - allFileNames.addAll(fieldValueArray.getValue()); - } - } - - if (hashseq2List != null && !hashseq2List.isEmpty()) { - for (Object o : hashseq2List) { - FieldValueArray fieldValueArray = mapper.readValue(JsonUtils.javaObjectToJsonString(o), FieldValueArray.class); - allFileNames.addAll(fieldValueArray.getValue()); - } - } - - List notFoundFiles = new ArrayList<>(); - allFileNames.forEach(v -> notFoundFiles.add(v)); - for (String fileName : allFileNames) { - InputStream inputStream = ZipUtils.unzipAndGetFile(packet.getPacket(), fileName); - if (inputStream != null && inputStream.available() > 0) - checksumMap.put(fileName, inputStream); - notFoundFiles.remove(fileName); - } - - return (notFoundFiles.size() == 0); - } - - private boolean checksumValidation(List hashseq1List, List hashseq2List, Map checksumMap, Packet packet) throws JsonProcessingException, IOException, NoSuchAlgorithmException { - List hashSequence1 = new ArrayList<>(); - List hashSequence2 = new ArrayList<>(); - boolean isdataCheckSumEqual = false; - boolean isoperationsCheckSumEqual = false; - - if (hashseq1List != null && !hashseq1List.isEmpty()) { - for (Object o : hashseq1List) { - FieldValueArray fieldValueArray = mapper.readValue(JsonUtils.javaObjectToJsonString(o), FieldValueArray.class); - hashSequence1.add(fieldValueArray); - } - } - - if (hashseq2List != null && !hashseq2List.isEmpty()) { - for (Object o : hashseq2List) { - FieldValueArray fieldValueArray = mapper.readValue(JsonUtils.javaObjectToJsonString(o), FieldValueArray.class); - hashSequence2.add(fieldValueArray); - } - } - - // Getting hash bytes from packet - InputStream dataHashStream = ZipUtils.unzipAndGetFile(packet.getPacket(), "PACKET_DATA_HASH"); - InputStream operationsHashStream = ZipUtils.unzipAndGetFile(packet.getPacket(), "PACKET_OPERATIONS_HASH"); - - if (dataHashStream != null) { - byte[] dataHashByte = IOUtils.toByteArray(dataHashStream); - byte[] dataHash = generateHash(hashSequence1, checksumMap); - isdataCheckSumEqual = MessageDigest.isEqual(dataHash, dataHashByte); - } else - isdataCheckSumEqual = true; - - if (operationsHashStream != null) { - byte[] operationsHashByte = IOUtils.toByteArray(operationsHashStream); - byte[] operationsHash = generateHash(hashSequence2, checksumMap); - isoperationsCheckSumEqual = MessageDigest.isEqual(operationsHash, operationsHashByte); - } else - isoperationsCheckSumEqual = true; - - return (isdataCheckSumEqual && isoperationsCheckSumEqual); - - } - - private LinkedHashMap loadDemographicIdentity(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 = mapper.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); - jsonList.add(obj instanceof org.json.JSONObject ? mapper.readValue(obj.toString(), HashMap.class):obj); - } - demographicIdentity.putIfAbsent(e.getKey(), jsonList); - } else - demographicIdentity.putIfAbsent(e.getKey(), e.getValue()); - } else - demographicIdentity.putIfAbsent(e.getKey(), value); - } - } - return demographicIdentity; - } - - -} + } + } + + /** + * Files validation. + * + * @param id the registration id + * @return true, if successful + * @throws IOException + */ + public boolean fileAndChecksumValidation(String id, String source, String process) + throws IOException, JsonProcessingException, PacketKeeperException, NoSuchAlgorithmException { + + if (packetNames == null || packetNames.isEmpty()) { + LOGGER.warn(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "No packet names provided"); + return false; + } + + boolean isValid = false; + PacketInfo info = new PacketInfo(); + info.setId(id); + info.setSource(source); + info.setProcess(process); + + for (String packetName : packetNames.split(",")) { + if (packetName == null || packetName.isEmpty()) { + LOGGER.warn(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "Skipping empty packet name"); + continue; + } + + info.setPacketName(packetName); + Packet packet = packetKeeper.getPacket(info); + Map fileCache = ZipUtils.unzipAll(packet.getPacket()); // Caching all files once + + Map metaInfo = getMetaInfoJson(fileCache); + if (metaInfo.isEmpty()) { + LOGGER.warn(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + "Empty meta info for packet: {}", packetName); + return false; + } + + List hashseq1List = parseHashSequences(metaInfo.get("hashSequence1")); + List hashseq2List = parseHashSequences(metaInfo.get("hashSequence2")); + + Map checksumMap = new HashMap<>(32); + + boolean fileValid = validateFiles(hashseq1List, hashseq2List, checksumMap, fileCache); + logAudit(fileValid, "File validation", packetName, id); + if (!fileValid) return false; + + boolean checksumValid = checksumValidation(hashseq1List, hashseq2List, checksumMap, fileCache); + logAudit(checksumValid, "Checksum validation", packetName, id); + if (!checksumValid) return false; + + isValid = true; + } + + return isValid; + } + + @SuppressWarnings("unchecked") + private List parseHashSequences(String json) + throws JsonProcessingException, JsonMappingException, com.fasterxml.jackson.core.JsonProcessingException { + if (json == null || json.isEmpty()) + return null; + List rawList = mapper.readValue(json, List.class); + List result = new ArrayList<>(rawList.size()); + for (Object obj : rawList) { + result.add(mapper.convertValue(obj, FieldValueArray.class)); + } + return result; + } + + private byte[] generateHash(List hashSequence, Map checksumMap) + throws NoSuchAlgorithmException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (FieldValueArray fva : hashSequence) { + for (String file : fva.getValue()) { + try (InputStream input = checksumMap.get(file)) { + if (input != null) + output.write(IOUtils.toByteArray(input)); + } catch (IOException e) { + LOGGER.error("Error in hash generation: {}", ExceptionUtils.getStackTrace(e)); + } + } + } + return HMACUtils2.digestAsPlainText(output.toByteArray()).getBytes(); + } + + @SuppressWarnings("unchecked") + private Map getMetaInfoJson(Map fileCache) + throws IOException, JsonProcessingException { + Map finalMap = new HashMap<>(); + byte[] metaInfoBytes = getFileIgnoreCase (fileCache, "PACKET_META_INFO"); + if (metaInfoBytes != null) { + LinkedHashMap currentIdMap = (LinkedHashMap) mapper + .readValue(new String(metaInfoBytes, StandardCharset.UTF_8), LinkedHashMap.class).get(IDENTITY); + + for (Map.Entry entry : currentIdMap.entrySet()) { + finalMap.put(entry.getKey(), + entry.getValue() != null ? JsonUtils.javaObjectToJsonString(entry.getValue()) : null); + } + } + return finalMap; + } + + private boolean validateFiles(List hashseq1List, List hashseq2List, + Map checksumMap, Map fileCache) { + Set requiredFiles = new HashSet<>(); + Stream.of(hashseq1List, hashseq2List).filter(Objects::nonNull).flatMap(List::stream) + .forEach(fva -> requiredFiles.addAll(fva.getValue())); + + Set notFound = new HashSet<>(requiredFiles); + for (String file : requiredFiles) { + byte[] content = getFileIgnoreCase (fileCache, file); + if (content != null && content.length > 0) { + checksumMap.put(file, new ByteArrayInputStream(content)); + notFound.remove(file); + } + } + + return notFound.isEmpty(); + } + + private boolean checksumValidation(List hash1, List hash2, + Map checksumMap, Map fileCache) throws NoSuchAlgorithmException { + + boolean dataEqual = true, opsEqual = true; + + byte[] dataHashBytes = getFileIgnoreCase (fileCache, "PACKET_DATA_HASH"); + if (dataHashBytes != null) { + byte[] calculatedDataHash = generateHash(hash1, checksumMap); + dataEqual = MessageDigest.isEqual(dataHashBytes, calculatedDataHash); + } + + byte[] opsHashBytes = getFileIgnoreCase (fileCache, "PACKET_OPERATIONS_HASH"); + if (opsHashBytes != null) { + byte[] calculatedOpsHash = generateHash(hash2, checksumMap); + opsEqual = MessageDigest.isEqual(opsHashBytes, calculatedOpsHash); + } + + return dataEqual && opsEqual; + } + + private LinkedHashMap loadDemographicIdentity(Map fieldMap) throws IOException { + if (fieldMap == null) { + return new LinkedHashMap<>(); + } + + LinkedHashMap demographicIdentity = new LinkedHashMap<>(fieldMap.size()); + for (Map.Entry entry : fieldMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key == null || value == null) { + demographicIdentity.putIfAbsent(key, value); + continue; + } + + if (value instanceof String stringValue) { + try { + // Try parsing as JSON object + if (stringValue.startsWith("{")) { + Map jsonMap = mapper.readValue(stringValue, Map.class); + demographicIdentity.putIfAbsent(key, jsonMap); + } + // Try parsing as JSON array + else if (stringValue.startsWith("[")) { + List jsonList = new ArrayList<>(); + List rawList = mapper.readValue(stringValue, List.class); + for (Object obj : rawList) { + jsonList.add(obj instanceof Map ? obj : obj); + } + demographicIdentity.putIfAbsent(key, jsonList); + } + // Treat as simple string + else { + demographicIdentity.putIfAbsent(key, stringValue); + } + } catch (IOException e) { + // Fallback to raw string if JSON parsing fails + demographicIdentity.putIfAbsent(key, stringValue); + } + } else { + // Non-string values (e.g., Map, List, or primitives) + demographicIdentity.putIfAbsent(key, value); + } + } + return demographicIdentity; + } + + private void logAudit(boolean status, String type, String packetName, String id) { + String message = type + (status ? " successful" : " failed"); + LOGGER.info(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, "{} for packet name: {}", + message, packetName); + auditLogEntry.addAudit(message, eventId, eventName, eventType, null, null, id); + } + + private byte[] getFileIgnoreCase(Map fileCache, String targetFileBase) { + for (String key : fileCache.keySet()) { + if (key.equalsIgnoreCase(targetFileBase) || key.toLowerCase().startsWith(targetFileBase.toLowerCase())) { + return fileCache.get(key); + } + } + return null; + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/ZipUtils.java b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/ZipUtils.java index c761452ca0..915589e413 100644 --- a/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/ZipUtils.java +++ b/commons-packet/commons-packet-manager/src/main/java/io/mosip/commons/packet/util/ZipUtils.java @@ -1,62 +1,68 @@ package io.mosip.commons.packet.util; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOCase; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.IOCase; +import org.apache.commons.io.IOUtils; + /** - * Class to unzip the packets + * Utility class to unzip packets and extract specific files from them. */ public class ZipUtils { - /** - * Method to unzip the file in-memeory and search the required file and return - * it - * - * @param packet zip file to be unzipped - * @param file file to search within zip file - * @return return the corresponding file as inputStream - * @throws IOException if any error occored while unzipping the file - */ - public static InputStream unzipAndGetFile(byte[] packet, String file) throws IOException { - ByteArrayInputStream packetStream = new ByteArrayInputStream(packet); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - boolean flag = false; - byte[] buffer = new byte[2048]; - try (ZipInputStream zis = new ZipInputStream(packetStream)) { - ZipEntry ze = zis.getNextEntry(); - while (ze != null) { - String fileName = ze.getName(); - String fileNameWithOutExt = FilenameUtils.removeExtension(fileName); - if (FilenameUtils.equals(fileNameWithOutExt, file, true, IOCase.INSENSITIVE)) { - int len; - flag = true; - while ((len = zis.read(buffer)) > 0) { - out.write(buffer, 0, len); - } - break; - } - zis.closeEntry(); - ze = zis.getNextEntry(); - } - zis.closeEntry(); - } finally { - packetStream.close(); - out.close(); - } - if (flag) { - return new ByteArrayInputStream(out.toByteArray()); - } - - return null; - } -} + /** + * Unzips the in-memory zip packet and returns the specified file as an + * InputStream. + * + * @param packet the zip file as a byte array + * @param targetFileName the file name (without extension) to extract + * @return InputStream of the extracted file if found; otherwise null + * @throws IOException if any I/O error occurs during unzipping + */ + public static InputStream unzipAndGetFile(byte[] packet, String targetFileName) throws IOException { + try (ByteArrayInputStream packetStream = new ByteArrayInputStream(packet); + ZipInputStream zis = new ZipInputStream(packetStream)) { + ZipEntry ze; + byte[] buffer = new byte[2048]; + + while ((ze = zis.getNextEntry()) != null) { + String currentFileName = FilenameUtils.removeExtension(ze.getName()); + + if (FilenameUtils.equals(currentFileName, targetFileName, true, IOCase.INSENSITIVE)) { + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + int len; + while ((len = zis.read(buffer)) > 0) { + out.write(buffer, 0, len); + } + return new ByteArrayInputStream(out.toByteArray()); + } + } + + zis.closeEntry(); + } + } + + // File not found in ZIP + return null; + } + + public static Map unzipAll(byte[] zipBytes) throws IOException { + Map fileMap = new HashMap<>(); + try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes))) { + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + byte[] content = IOUtils.toByteArray(zis); + fileMap.put(entry.getName(), content); + } + } + return fileMap; + } +} \ No newline at end of file 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 3ddebc4fbe..fc266dcf44 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 @@ -10,11 +10,11 @@ import java.util.Arrays; import java.util.Date; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; @@ -29,10 +29,14 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.test.util.ReflectionTestUtils; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + 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.facade.PacketReaderProviderRegistry; import io.mosip.commons.packet.impl.PacketReaderImpl; import io.mosip.commons.packet.keeper.PacketKeeper; import io.mosip.commons.packet.spi.IPacketReader; @@ -45,199 +49,234 @@ 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.*"}) +@PrepareForTest({ PacketHelper.class }) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*" }) public class PacketReaderTest { - @InjectMocks - private PacketReader packetReader = new PacketReader(); + @InjectMocks + private PacketReader packetReader = new PacketReader(); + + @Mock + private PacketReaderImpl packetReaderProvider; - @Mock - private PacketReaderImpl packetReaderProvider; + @Mock + private PacketReaderProviderRegistry providerRegistry; - private Map allFields; + private Map allFields; - private static final String source = "reg-client"; - private static final String process = "NEW"; - private static final String id = "110111101120191111121111"; - - @Mock + private static final String source = "reg-client"; + private static final String process = "NEW"; + private static final String id = "110111101120191111121111"; + + @Mock private PacketKeeper packetKeeper; - @Spy - private ObjectMapper mapper = new ObjectMapper(); - @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() throws JsonProcessingException { - 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() throws JsonProcessingException { - 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)); - } + @Spy + private ObjectMapper mapper = new ObjectMapper(); + + @Before + public void setup() { + PowerMockito.mockStatic(PacketHelper.class); + PowerMockito.when(PacketHelper.isSourceAndProcessPresent(anyString(), anyString(), anyString(), any())) + .thenReturn(true); + + Mockito.when(providerRegistry.getReaderProvider(anyString(), anyString())).thenReturn(packetReaderProvider); + ReflectionTestUtils.setField(packetReader, "providerRegistry", providerRegistry); + + 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() throws JsonProcessingException { + 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() throws JsonProcessingException { + 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); - @Test - public void testGetMetaInfo() { - Map metaMap = new HashMap<>(); - metaMap.put("operationsData","officerid:1234"); + boolean result = packetReader.validatePacket(id, source, process); - Mockito.when(packetReaderProvider.getMetaInfo(anyString(), anyString(), anyString())).thenReturn(metaMap); + assertTrue(result); + } - Map result = packetReader.getMetaInfo(id, source, process, true); + @Test(expected = NoAvailableProviderException.class) + public void testProviderException() { + Mockito.when(providerRegistry.getReaderProvider(anyString(), anyString())) + .thenThrow(new NoAvailableProviderException()); - assertTrue(result.equals(metaMap)); - } + packetReader.validatePacket(id, source, process); + } - @Test - public void testGetAudits() { - Map auditMap = new HashMap<>(); - auditMap.put("audit","audit1"); - List> auditList = new ArrayList<>(); - auditList.add(auditMap); + @Test + public void testGetTags() { + Map tags = new HashMap<>(); + tags.put("test", "testValue"); - Mockito.when(packetReaderProvider.getAuditInfo(anyString(), anyString(), anyString())).thenReturn(auditList); + Mockito.when(packetKeeper.getTags(any())).thenReturn(tags); - List> result = packetReader.getAudits(id, source, process, true); + Map expectedTags = packetReader.getTags("id"); - assertTrue(result.equals(auditList)); - } + assertEquals(expectedTags, tags); + } - @Test - public void testValidatePacket() { - Map auditMap = new HashMap<>(); - auditMap.put("audit","audit1"); - List> auditList = new ArrayList<>(); - auditList.add(auditMap); + @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(packetReaderProvider.validatePacket(anyString(), anyString(), anyString())).thenReturn(true); - - boolean result = packetReader.validatePacket(id, source, process); + Mockito.when(packetKeeper.getAll(any())).thenReturn(objectDtos); - assertTrue(result); - } + List result = packetReader.info("id"); - @Test(expected = NoAvailableProviderException.class) - public void testProviderException() { - PowerMockito.when(PacketHelper.isSourceAndProcessPresent(anyString(),anyString(),anyString(),any())).thenReturn(false); + assertEquals(objectDtos.size(), result.size()); + } - packetReader.validatePacket(id, source, process); - } - - @Test - public void testGetTags() { - Map tags = new HashMap<>(); - tags.put("test", "testValue"); - - Mockito.when(packetKeeper.getTags(any())).thenReturn(tags); + @Test + public void testGetAllKeys() { + Set expectedKeys = new HashSet<>(Arrays.asList("name", "email", "phone")); + Mockito.when(packetReaderProvider.getAll(anyString(), anyString(), anyString())).thenReturn(allFields); - Map expectedTags= packetReader.getTags("id"); + Set result = packetReader.getAllKeys(id, source, process); - assertEquals(expectedTags,tags); - } + assertEquals(expectedKeys, result); + } - @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); + @Test + public void testGetAuditsCached() { + Map auditMap = new HashMap<>(); + auditMap.put("audit", "audit1"); + List> auditList = new ArrayList<>(); + auditList.add(auditMap); + Mockito.when(packetReaderProvider.getAuditInfo(anyString(), anyString(), anyString())).thenReturn(auditList); - Mockito.when(packetKeeper.getAll(any())).thenReturn(objectDtos); + List> result = packetReader.getAudits(id, source, process, false); - List result = packetReader.info("id"); - - assertEquals(objectDtos.size(), result.size()); - } -} + assertEquals(auditList, result); + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/facade/PacketWriterTest.java b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/facade/PacketWriterTest.java index f65cbae77b..a5746f8ac7 100644 --- a/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/facade/PacketWriterTest.java +++ b/commons-packet/commons-packet-manager/src/test/java/io/mosip/commons/packet/test/facade/PacketWriterTest.java @@ -34,6 +34,7 @@ import io.mosip.commons.packet.exception.NoAvailableProviderException; import io.mosip.commons.packet.exception.PacketCreatorException; import io.mosip.commons.packet.facade.PacketWriter; +import io.mosip.commons.packet.facade.PacketWriterProviderRegistry; import io.mosip.commons.packet.impl.PacketWriterImpl; import io.mosip.commons.packet.keeper.PacketKeeper; import io.mosip.commons.packet.spi.IPacketWriter; @@ -46,250 +47,253 @@ 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.*"}) +@PrepareForTest({ PacketHelper.class }) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*" }) public class PacketWriterTest { - @InjectMocks - private PacketWriter packetWriter = new PacketWriter(); + @InjectMocks + private PacketWriter packetWriter = new PacketWriter(); - @Mock - private PacketWriterImpl packetWriterProvider; + @Mock + private PacketWriterImpl packetWriterProvider; - private Map allFields; + @Mock + private PacketWriterProviderRegistry providerRegistry; - private static final String source = "reg-client"; - private static final String process = "NEW"; - private static final String id = "110111101120191111121111"; - + private Map allFields; - @Mock - private PacketKeeper packetKeeper; + 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 referenceWriterProviders = new ArrayList<>(); - referenceWriterProviders.add(packetWriterProvider); - ReflectionTestUtils.setField(packetWriter, "referenceWriterProviders", referenceWriterProviders); - } - - @Test - public void testSetField() { - Mockito.doNothing().when(packetWriterProvider).setField(anyString(),anyString(),anyString()); - - packetWriter.setField(id, "name", "mono", source, process); - } - - @Test - public void testSetFields() { - Map fields = new HashMap<>(); - Mockito.doNothing().when(packetWriterProvider).setFields(anyString(),anyMap()); - - packetWriter.setFields(id, fields, source, process); - } - - @Test - public void testSetDocument() { - Document document = new Document(); - document.setValue("document"); - Mockito.doNothing().when(packetWriterProvider).setDocument(anyString(), anyString(), any()); - - packetWriter.setDocument(id, "poa", document, source, process); - } - - @Test - public void testSetBiometrics() { - List birTypeList = new ArrayList<>(); - io.mosip.kernel.biometrics.entities.BIR birType1 = new BIR.BIRBuilder().build(); - io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); - io.mosip.kernel.biometrics.entities.RegistryIDType registryIDType = new RegistryIDType("Mosip", "257"); - io.mosip.kernel.biometrics.constant.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); - String source = "reg-client"; - String process = "NEW"; - String id = "110111101120191111121111"; - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - Mockito.doNothing().when(packetWriterProvider).setBiometric(anyString(), anyString(), any()); - - packetWriter.setBiometric(id, "individualBiometrics", biometricRecord, source, process); - } - - @Test - public void testAddMetaInfo() { - Map fields = new HashMap<>(); - Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(),anyMap()); - - packetWriter.addMetaInfo(id, fields, source, process); - } - - @Test - public void testAddMetaInfoKeyValue() { - Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(),anyString(),anyString()); - - packetWriter.addMetaInfo(id, "rid", "regid", source, process); - } - - @Test - public void testAddAudit() { - Map fields = new HashMap<>(); - Mockito.doNothing().when(packetWriterProvider).addAudit(anyString(),anyMap()); - - packetWriter.addAudit(id, fields, source, process); - } - - @Test - public void testAddAudits() { - Map auditMap = new HashMap<>(); - auditMap.put("audit","audit1"); - List> auditList = new ArrayList<>(); - auditList.add(auditMap); - Mockito.doNothing().when(packetWriterProvider).addAudits(anyString(),anyList()); - - packetWriter.addAudits(id, auditList, source, process); - } - - - @Test - public void testPersistPacket() { - List packetInfos = new ArrayList<>(); - Mockito.when(packetWriterProvider.persistPacket(id, "0.2", "schema", source, process, null, null, true)).thenReturn(packetInfos); - - List result = packetWriter.persistPacket(id, "0.2", "schema", source, process, null, null, true); - - assertTrue(result.equals(packetInfos)); - } - - @Test - public void testCreatePacket() { - PacketDto packetDto = new PacketDto(); - packetDto.setId(id); - packetDto.setProcess(process); - packetDto.setSource(source); - packetDto.setAudits(new ArrayList<>()); - packetDto.setBiometrics(new HashMap<>()); - packetDto.setDocuments(new HashMap<>()); - packetDto.setFields(new HashMap<>()); - packetDto.setMetaInfo(new HashMap<>()); - packetDto.setSchemaJson("schemajson"); - packetDto.setSchemaVersion("0.2"); - - PacketInfo packetInfo = new PacketInfo(); - packetInfo.setId(id); - packetInfo.setSource(source); - - List packetInfos = new ArrayList<>(); - packetInfos.add(packetInfo); - - Mockito.doNothing().when(packetWriterProvider).setField(anyString(),anyString(),anyString()); - Mockito.doNothing().when(packetWriterProvider).setFields(anyString(),anyMap()); - Mockito.doNothing().when(packetWriterProvider).setDocument(anyString(), anyString(), any()); - Mockito.doNothing().when(packetWriterProvider).setBiometric(anyString(), anyString(), any()); - Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(),anyString(),anyString()); - Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(),anyMap()); - Mockito.doNothing().when(packetWriterProvider).addAudit(anyString(),anyMap()); - Mockito.doNothing().when(packetWriterProvider).addAudits(anyString(),anyList()); - Mockito.when(packetWriterProvider.persistPacket(anyString(), anyString(), - anyString(), anyString(), anyString(), any(), any(), anyBoolean())).thenReturn(packetInfos); - - List result = packetWriter.createPacket(packetDto); - - assertTrue(result.equals(packetInfos)); - } - - @Test - public void testException() { - PacketDto packetDto = new PacketDto(); - packetDto.setId(id); - packetDto.setProcess(process); - packetDto.setSource(source); - packetDto.setAudits(new ArrayList<>()); - packetDto.setBiometrics(new HashMap<>()); - packetDto.setDocuments(new HashMap<>()); - packetDto.setFields(new HashMap<>()); - packetDto.setMetaInfo(new HashMap<>()); - packetDto.setSchemaJson("schemajson"); - packetDto.setSchemaVersion("0.2"); - - PacketInfo packetInfo = new PacketInfo(); - packetInfo.setId(id); - packetInfo.setSource(source); - - List packetInfos = new ArrayList<>(); - packetInfos.add(packetInfo); - - Mockito.doNothing().when(packetWriterProvider).setField(anyString(),anyString(),anyString()); - Mockito.doNothing().when(packetWriterProvider).setFields(anyString(),anyMap()); - Mockito.doNothing().when(packetWriterProvider).setDocument(anyString(), anyString(), any()); - Mockito.doNothing().when(packetWriterProvider).setBiometric(anyString(), anyString(), any()); - Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(),anyString(),anyString()); - Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(),anyMap()); - Mockito.doNothing().when(packetWriterProvider).addAudit(anyString(),anyMap()); - Mockito.doNothing().when(packetWriterProvider).addAudits(anyString(),anyList()); - Mockito.when(packetWriterProvider.persistPacket(anyString(), anyString(), - anyString(), anyString(), anyString(), any(), any(), anyBoolean())).thenThrow(new PacketCreatorException("","")); - - List result = packetWriter.createPacket(packetDto); - - assertTrue(result == null); - } - - @Test(expected = NoAvailableProviderException.class) - public void testProviderException() { - PowerMockito.when(PacketHelper.isSourceAndProcessPresent(anyString(),anyString(),anyString(),any())).thenReturn(false); - - packetWriter.setField(id, "name", "mono", source, process); - } - - @Test - public void testAddTags() { - TagDto tagDto=new TagDto(); - tagDto.setId(id); - Map tags = new HashMap<>(); - tags.put("test", "testValue"); - tagDto.setTags(tags); - Mockito.when(packetKeeper.addTags(any())).thenReturn(tags); - - Map expectedTags= packetWriter.addTags(tagDto,tagDto.getId()); - - assertEquals(expectedTags,tags); - } - @Test - public void testUpdateTags() { - TagDto tagDto=new TagDto(); - tagDto.setId(id); - Map tags = new HashMap<>(); - tags.put("test", "testValue"); - tagDto.setTags(tags); - Mockito.when(packetKeeper.addorUpdate(any())).thenReturn(tags); - - - Map expectedTags= packetWriter.addorUpdate(tagDto,tagDto.getId()); - - assertEquals(expectedTags,tags); - } - @Test - public void testDeleteTags() { - TagRequestDto tagDto=new TagRequestDto(); - tagDto.setId(id); - List tags = new ArrayList<>(); - tags.add("test"); - tagDto.setTagNames(tags); - packetWriter.deleteTags(tagDto,tagDto.getId()); - - } - -} + @Before + public void setup() { + PowerMockito.mockStatic(PacketHelper.class); + PowerMockito.when(PacketHelper.isSourceAndProcessPresent(anyString(), anyString(), anyString(), any())) + .thenReturn(true); + + Mockito.when(providerRegistry.getWriterProvider(anyString(), anyString())).thenReturn(packetWriterProvider); + ReflectionTestUtils.setField(packetWriter, "providerRegistry", providerRegistry); + } + + @Test + public void testSetField() { + Mockito.doNothing().when(packetWriterProvider).setField(anyString(), anyString(), anyString()); + + packetWriter.setField(id, "name", "mono", source, process); + } + + @Test + public void testSetFields() { + Map fields = new HashMap<>(); + Mockito.doNothing().when(packetWriterProvider).setFields(anyString(), anyMap()); + + packetWriter.setFields(id, fields, source, process); + } + + @Test + public void testSetDocument() { + Document document = new Document(); + document.setValue("document"); + Mockito.doNothing().when(packetWriterProvider).setDocument(anyString(), anyString(), any()); + + packetWriter.setDocument(id, "poa", document, source, process); + } + + @Test + public void testSetBiometrics() { + List birTypeList = new ArrayList<>(); + io.mosip.kernel.biometrics.entities.BIR birType1 = new BIR.BIRBuilder().build(); + io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); + io.mosip.kernel.biometrics.entities.RegistryIDType registryIDType = new RegistryIDType("Mosip", "257"); + io.mosip.kernel.biometrics.constant.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); + String source = "reg-client"; + String process = "NEW"; + String id = "110111101120191111121111"; + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + Mockito.doNothing().when(packetWriterProvider).setBiometric(anyString(), anyString(), any()); + + packetWriter.setBiometric(id, "individualBiometrics", biometricRecord, source, process); + } + + @Test + public void testAddMetaInfo() { + Map fields = new HashMap<>(); + Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(), anyMap()); + + packetWriter.addMetaInfo(id, fields, source, process); + } + + @Test + public void testAddMetaInfoKeyValue() { + Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(), anyString(), anyString()); + + packetWriter.addMetaInfo(id, "rid", "regid", source, process); + } + + @Test + public void testAddAudit() { + Map fields = new HashMap<>(); + Mockito.doNothing().when(packetWriterProvider).addAudit(anyString(), anyMap()); + + packetWriter.addAudit(id, fields, source, process); + } + + @Test + public void testAddAudits() { + Map auditMap = new HashMap<>(); + auditMap.put("audit", "audit1"); + List> auditList = new ArrayList<>(); + auditList.add(auditMap); + Mockito.doNothing().when(packetWriterProvider).addAudits(anyString(), anyList()); + + packetWriter.addAudits(id, auditList, source, process); + } + + @Test + public void testPersistPacket() { + List packetInfos = new ArrayList<>(); + Mockito.when(packetWriterProvider.persistPacket(id, "0.2", "schema", source, process, null, null, true)) + .thenReturn(packetInfos); + + List result = packetWriter.persistPacket(id, "0.2", "schema", source, process, null, null, true); + + assertTrue(result.equals(packetInfos)); + } + + @Test + public void testCreatePacket() { + PacketDto packetDto = new PacketDto(); + packetDto.setId(id); + packetDto.setProcess(process); + packetDto.setSource(source); + packetDto.setAudits(new ArrayList<>()); + packetDto.setBiometrics(new HashMap<>()); + packetDto.setDocuments(new HashMap<>()); + packetDto.setFields(new HashMap<>()); + packetDto.setMetaInfo(new HashMap<>()); + packetDto.setSchemaJson("schemajson"); + packetDto.setSchemaVersion("0.2"); + + PacketInfo packetInfo = new PacketInfo(); + packetInfo.setId(id); + packetInfo.setSource(source); + + List packetInfos = new ArrayList<>(); + packetInfos.add(packetInfo); + + Mockito.doNothing().when(packetWriterProvider).setField(anyString(), anyString(), anyString()); + Mockito.doNothing().when(packetWriterProvider).setFields(anyString(), anyMap()); + Mockito.doNothing().when(packetWriterProvider).setDocument(anyString(), anyString(), any()); + Mockito.doNothing().when(packetWriterProvider).setBiometric(anyString(), anyString(), any()); + Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(), anyString(), anyString()); + Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(), anyMap()); + Mockito.doNothing().when(packetWriterProvider).addAudit(anyString(), anyMap()); + Mockito.doNothing().when(packetWriterProvider).addAudits(anyString(), anyList()); + Mockito.when(packetWriterProvider.persistPacket(anyString(), anyString(), anyString(), anyString(), anyString(), + any(), any(), anyBoolean())).thenReturn(packetInfos); + + List result = packetWriter.createPacket(packetDto); + + assertTrue(result.equals(packetInfos)); + } + + @Test + public void testException() { + PacketDto packetDto = new PacketDto(); + packetDto.setId(id); + packetDto.setProcess(process); + packetDto.setSource(source); + packetDto.setAudits(new ArrayList<>()); + packetDto.setBiometrics(new HashMap<>()); + packetDto.setDocuments(new HashMap<>()); + packetDto.setFields(new HashMap<>()); + packetDto.setMetaInfo(new HashMap<>()); + packetDto.setSchemaJson("schemajson"); + packetDto.setSchemaVersion("0.2"); + + PacketInfo packetInfo = new PacketInfo(); + packetInfo.setId(id); + packetInfo.setSource(source); + + List packetInfos = new ArrayList<>(); + packetInfos.add(packetInfo); + + Mockito.doNothing().when(packetWriterProvider).setField(anyString(), anyString(), anyString()); + Mockito.doNothing().when(packetWriterProvider).setFields(anyString(), anyMap()); + Mockito.doNothing().when(packetWriterProvider).setDocument(anyString(), anyString(), any()); + Mockito.doNothing().when(packetWriterProvider).setBiometric(anyString(), anyString(), any()); + Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(), anyString(), anyString()); + Mockito.doNothing().when(packetWriterProvider).addMetaInfo(anyString(), anyMap()); + Mockito.doNothing().when(packetWriterProvider).addAudit(anyString(), anyMap()); + Mockito.doNothing().when(packetWriterProvider).addAudits(anyString(), anyList()); + Mockito.when(packetWriterProvider.persistPacket(anyString(), anyString(), anyString(), anyString(), anyString(), + any(), any(), anyBoolean())).thenThrow(new PacketCreatorException("", "")); + + List result = packetWriter.createPacket(packetDto); + + assertTrue(result == null); + } + + @Test(expected = NoAvailableProviderException.class) + public void testProviderException() { + Mockito.when(providerRegistry.getWriterProvider(anyString(), anyString())) + .thenThrow(new NoAvailableProviderException()); + + packetWriter.setField(id, "name", "mono", source, process); + } + + @Test + public void testAddTags() { + TagDto tagDto = new TagDto(); + tagDto.setId(id); + Map tags = new HashMap<>(); + tags.put("test", "testValue"); + tagDto.setTags(tags); + Mockito.when(packetKeeper.addTags(any())).thenReturn(tags); + + Map expectedTags = packetWriter.addTags(tagDto, tagDto.getId()); + + assertEquals(expectedTags, tags); + } + + @Test + public void testUpdateTags() { + TagDto tagDto = new TagDto(); + tagDto.setId(id); + Map tags = new HashMap<>(); + tags.put("test", "testValue"); + tagDto.setTags(tags); + Mockito.when(packetKeeper.addorUpdate(any())).thenReturn(tags); + + Map expectedTags = packetWriter.addorUpdate(tagDto, tagDto.getId()); + + assertEquals(expectedTags, tags); + } + + @Test + public void testDeleteTags() { + TagRequestDto tagDto = new TagRequestDto(); + tagDto.setId(id); + List tags = new ArrayList<>(); + tags.add("test"); + tagDto.setTagNames(tags); + packetWriter.deleteTags(tagDto, tagDto.getId()); + + } +} \ No newline at end of file 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 915002535b..96d445825f 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 @@ -9,6 +9,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.Charset; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; @@ -66,388 +67,316 @@ import io.mosip.kernel.core.util.exception.JsonProcessingException; @RunWith(PowerMockRunner.class) -@PrepareForTest({ZipUtils.class, IOUtils.class, JsonUtils.class, CbeffValidator.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.*"}) +@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" + - " \"selectedHandles\": [\n" + - " \"nrcId\"\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, PacketKeeperException { - 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(null); - - 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); - } + @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" + " \"selectedHandles\": [\n" + + " \"nrcId\"\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, PacketKeeperException { + 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(null); + + 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()); - @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()); + when(idSchemaUtils.getSource(any(), any())).thenThrow(new IOException("exception")); - Document result = iPacketReader.getDocument("id", docName, "source", "process"); + 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 { + @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; + 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"); + 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); + 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); + 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 JsonMappingException("exception")); - - iPacketReader.getMetaInfo("id", "source", "process"); - } - - @Test(expected = GetAllIdentityException.class) - public void getAuditExceptionTest() throws IOException { - when(objectMapper.readValue(anyString(), any(Class.class))).thenThrow(new JsonMappingException("exception")); - - iPacketReader.getAuditInfo("id", "source", "process"); - } + 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 JsonMappingException("exception")); + + iPacketReader.getMetaInfo("id", "source", "process"); + } + + @Test(expected = GetAllIdentityException.class) + public void getAuditExceptionTest() throws IOException { + when(objectMapper.readValue(anyString(), any(Class.class))).thenThrow(new JsonMappingException("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 b8d6c4cc15..12c84d5fca 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 @@ -12,8 +12,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; -import io.mosip.commons.packet.util.PacketManagerHelper; import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Ignore; @@ -36,207 +36,217 @@ import io.mosip.commons.packet.exception.PacketKeeperException; import io.mosip.commons.packet.keeper.PacketKeeper; import io.mosip.commons.packet.spi.IPacketCryptoService; +import io.mosip.commons.packet.util.PacketManagerHelper; 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); + @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() { + // Set correct string identifiers + ReflectionTestUtils.setField(packetKeeper, "adapterName", "SwiftAdapter"); + ReflectionTestUtils.setField(packetKeeper, "cryptoName", "OnlinePacketCryptoServiceImpl"); + + // Set other config fields + ReflectionTestUtils.setField(packetKeeper, "PACKET_MANAGER_ACCOUNT", "PACKET_MANAGER_ACCOUNT"); + ReflectionTestUtils.setField(packetKeeper, "centerIdLength", 5); + ReflectionTestUtils.setField(packetKeeper, "machineIdLength", 5); + ReflectionTestUtils.setField(packetKeeper, "disablePacketSignatureVerification", false); + + // Populate registries manually + Map adapterRegistry = new ConcurrentHashMap<>(); + adapterRegistry.put("SwiftAdapter", swiftAdapter); + adapterRegistry.put("S3Adapter", s3Adapter); + adapterRegistry.put("PosixAdapter", posixAdapter); + ReflectionTestUtils.setField(packetKeeper, "adapterRegistry", adapterRegistry); + + Map cryptoRegistry = new ConcurrentHashMap<>(); + cryptoRegistry.put("OnlinePacketCryptoServiceImpl", onlineCrypto); + ReflectionTestUtils.setField(packetKeeper, "cryptoRegistry", cryptoRegistry); + + 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); - } - - -} - - + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-service/pom.xml b/commons-packet/commons-packet-service/pom.xml index e9d83f3d21..d7a411758e 100644 --- a/commons-packet/commons-packet-service/pom.xml +++ b/commons-packet/commons-packet-service/pom.xml @@ -36,7 +36,7 @@ 1.2.1-SNAPSHOT 1.2.1-SNAPSHOT 1.2.1-SNAPSHOT - 1.2.1-SNAPSHOT + 1.2.2-SNAPSHOT 1.2.1-SNAPSHOT **/constant/**,**/config/**,**/httpfilter/**,**/cache/**,**/dto/**,**/entity/**,**/model/**,**/exception/**,**/repository/**,**/security/**,**/*Config.java,**/*BootApplication.java,**/*VertxApplication.java,**/cbeffutil/**,**/*Utils.java,**/*Validator.java,**/*Helper.java,**/verticle/**,**/VidWriter.java/**,**/masterdata/utils/**,**/spi/**,**/core/http/**,"**/LocationServiceImpl.java","**/RegistrationCenterMachineServiceImpl.java","**/RegistrationCenterServiceImpl.java","**/pridgenerator/**","**/idgenerator/prid","**/proxy/**","**/cryptosignature/**" **/dto/**,**/entity/**,**/config/** 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 07b3dd7108..2fad652fd2 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 @@ -4,8 +4,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; -import io.mosip.commons.packetmanager.dto.SourceProcessDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; @@ -13,8 +14,6 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; -import com.google.common.collect.Lists; - import io.mosip.commons.packet.dto.Document; import io.mosip.commons.packet.dto.TagRequestDto; import io.mosip.commons.packet.dto.TagResponseDto; @@ -27,6 +26,7 @@ import io.mosip.commons.packetmanager.dto.InfoDto; import io.mosip.commons.packetmanager.dto.InfoRequestDto; import io.mosip.commons.packetmanager.dto.InfoResponseDto; +import io.mosip.commons.packetmanager.dto.SourceProcessDto; import io.mosip.commons.packetmanager.dto.ValidatePacketResponse; import io.mosip.commons.packetmanager.service.PacketReaderService; import io.mosip.kernel.biometrics.entities.BiometricRecord; @@ -34,225 +34,229 @@ import io.mosip.kernel.core.http.ResponseFilter; import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.util.DateUtils; - import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; @RestController @Tag(name = "packet-reader-controller", description = "Packet Reader Controller") public class PacketReaderController { - @Autowired - private PacketReader packetReader; + @Autowired + private PacketReader packetReader; - @Autowired - private PacketReaderService packetReaderService; - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostsearchfield())") - @ResponseFilter - @PostMapping(path = "/searchField", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "searchField", description = "searchField", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper searchField(@RequestBody(required = true) RequestWrapper fieldDto) { - SourceProcessDto sourceProcessDto = packetReaderService.getSourceAndProcess(fieldDto.getRequest().getId(), - fieldDto.getRequest().getField(), fieldDto.getRequest().getSource(), fieldDto.getRequest().getProcess()); - String resultField = sourceProcessDto == null ? null : - packetReader.getField(fieldDto.getRequest().getId(), - fieldDto.getRequest().getField(), sourceProcessDto.getSource(), sourceProcessDto.getProcess(), fieldDto.getRequest().getBypassCache()); - ResponseWrapper response = new ResponseWrapper(); - Map responseMap = new HashMap<>(); - responseMap.put(fieldDto.getRequest().getField(), resultField); - FieldResponseDto fieldResponseDto = new FieldResponseDto(responseMap); + @Autowired + private PacketReaderService packetReaderService; - response.setResponse(fieldResponseDto); - return response; - } + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostsearchfield())") + @ResponseFilter + @PostMapping(path = "/searchField", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "searchField", description = "searchField", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) + public ResponseWrapper searchField( + @RequestBody(required = true) RequestWrapper fieldDto) { + FieldDto req = fieldDto.getRequest(); + String value = getSourceProcess(req.getId(), req.getField(), req.getSource(), req.getProcess()) + .map(sp -> packetReader.getField(req.getId(), req.getField(), sp.getSource(), sp.getProcess(), + req.getBypassCache())) + .orElse(null); + return wrapResponse(new FieldResponseDto(Map.of(req.getField(), value))); + } - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostsearchfields())") - @ResponseFilter - @PostMapping(path = "/searchFields", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "searchFields", description = "searchFields", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper searchFields(@RequestBody(required = true) RequestWrapper request) { - FieldDtos fieldDtos = request.getRequest(); - Map resultFields = new HashMap<>(); - if ((fieldDtos.getSource()) == null) { - for (String field : fieldDtos.getFields()) { - SourceProcessDto sourceProcessDto = packetReaderService.getSourceAndProcess(fieldDtos.getId(), - field, fieldDtos.getSource(), fieldDtos.getProcess()); + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostsearchfields())") + @ResponseFilter + @PostMapping(path = "/searchFields", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "searchFields", description = "searchFields", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) + public ResponseWrapper searchFields( + @RequestBody(required = true) RequestWrapper request) { + FieldDtos dto = request.getRequest(); + Map resultFields = new HashMap<>(); + if ((dto.getSource()) == null) { + for (String field : dto.getFields()) { + SourceProcessDto sourceProcessDto = packetReaderService.getSourceAndProcess(dto.getId(), + field, dto.getSource(), dto.getProcess()); String value = sourceProcessDto == null ? null : - packetReader.getField(fieldDtos.getId(), field, sourceProcessDto.getSource(), - sourceProcessDto.getProcess(), fieldDtos.getBypassCache()); + packetReader.getField(dto.getId(), field, sourceProcessDto.getSource(), + sourceProcessDto.getProcess(), dto.getBypassCache()); resultFields.put(field, value); } - } else - resultFields = packetReader.getFields(fieldDtos.getId(), fieldDtos.getFields(), fieldDtos.getSource(), fieldDtos.getProcess(), fieldDtos.getBypassCache()); - FieldResponseDto resultField = new FieldResponseDto(resultFields); - ResponseWrapper response = new ResponseWrapper(); - response.setResponse(resultField); - return response; - } + } else { + resultFields = packetReader.getFields(dto.getId(), dto.getFields(), dto.getSource(), dto.getProcess(), + dto.getBypassCache()); + } + + return wrapResponse(new FieldResponseDto(resultFields)); + } + + @ResponseFilter + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostdocument())") + @PostMapping(path = "/document", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "getDocument", description = "getDocument", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) + public ResponseWrapper getDocument(@RequestBody(required = true) RequestWrapper request) { + DocumentDto dto = request.getRequest(); + Document doc = getSourceProcess(dto.getId(), dto.getDocumentName(), dto.getSource(), dto.getProcess()).map( + sp -> packetReader.getDocument(dto.getId(), dto.getDocumentName(), sp.getSource(), sp.getProcess())) + .orElse(null); + return wrapResponse(doc); + } + + @ResponseFilter + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostbiometrics())") + @PostMapping(path = "/biometrics", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "getBiometrics", description = "getBiometrics", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) + public ResponseWrapper getBiometrics( + @RequestBody(required = true) RequestWrapper request) { + BiometricRequestDto dto = request.getRequest(); + List modalities = Optional.ofNullable(dto.getModalities()).orElseGet(ArrayList::new); + + BiometricRecord bio = getSourceProcess(dto.getId(), dto.getPerson(), dto.getSource(), dto.getProcess()) + .map(sp -> packetReader.getBiometric(dto.getId(), dto.getPerson(), modalities, sp.getSource(), + sp.getProcess(), dto.isBypassCache())) + .orElse(null); + return wrapResponse(bio); + } - @ResponseFilter - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostdocument())") - @PostMapping(path = "/document", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "getDocument", description = "getDocument", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper getDocument(@RequestBody(required = true) RequestWrapper request) { - DocumentDto documentDto = request.getRequest(); - SourceProcessDto sourceProcessDto = packetReaderService.getSourceAndProcess(documentDto.getId(), - documentDto.getDocumentName(), documentDto.getSource(), documentDto.getProcess()); - Document document = sourceProcessDto == null ? null : - packetReader.getDocument(documentDto.getId(), documentDto.getDocumentName(), - sourceProcessDto.getSource(), sourceProcessDto.getProcess()); - ResponseWrapper response = new ResponseWrapper(); - response.setResponse(document); - return response; - } + @ResponseFilter + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostmetainfo())") + @PostMapping(path = "/metaInfo", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "getMetaInfo", description = "getMetaInfo", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) + public ResponseWrapper getMetaInfo( + @RequestBody(required = true) RequestWrapper request) { + InfoDto metaDto = request.getRequest(); + Optional sourceProcessOpt = getSourceProcess(metaDto.getId(), metaDto.getSource(), + metaDto.getProcess()); - @ResponseFilter - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostbiometrics())") - @PostMapping(path = "/biometrics", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "getBiometrics", description = "getBiometrics", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper getBiometrics(@RequestBody(required = true) RequestWrapper request) { - BiometricRequestDto bioRequest = request.getRequest(); - SourceProcessDto sourceProcessDto = packetReaderService.getSourceAndProcess(bioRequest.getId(), - bioRequest.getPerson(), bioRequest.getSource(), bioRequest.getProcess()); - List modalities = bioRequest.getModalities() == null ? Lists.newArrayList() : bioRequest.getModalities(); - BiometricRecord responseDto = sourceProcessDto == null ? null : - packetReader.getBiometric(bioRequest.getId(), bioRequest.getPerson(), modalities, - sourceProcessDto.getSource(), sourceProcessDto.getProcess(), bioRequest.isBypassCache()); - ResponseWrapper response = getResponseWrapper(); - response.setResponse(responseDto); - return response; - } + if (sourceProcessOpt.isEmpty()) { + return wrapResponse(new FieldResponseDto(Map.of())); + } - @ResponseFilter - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostmetainfo())") - @PostMapping(path = "/metaInfo", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "getMetaInfo", description = "getMetaInfo", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper getMetaInfo(@RequestBody(required = true) RequestWrapper request) { - InfoDto metaDto = request.getRequest(); - SourceProcessDto sourceProcessDto = packetReaderService.getSourceAndProcess(metaDto.getId(), metaDto.getSource(), metaDto.getProcess()); - Map resultFields = packetReader.getMetaInfo(metaDto.getId(), - sourceProcessDto.getSource(), sourceProcessDto.getProcess(), metaDto.getBypassCache()); - FieldResponseDto resultField = new FieldResponseDto(resultFields); - ResponseWrapper response = getResponseWrapper(); - response.setResponse(resultField); - return response; - } + Map fields = packetReader.getMetaInfo(metaDto.getId(), sourceProcessOpt.get().getSource(), + sourceProcessOpt.get().getProcess(), metaDto.getBypassCache()); - @ResponseFilter - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostaudits())") - @PostMapping(path = "/audits", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "getAudits", description = "getAudits", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper> getAudits(@RequestBody(required = true) RequestWrapper request) { - InfoDto metaDto = request.getRequest(); - SourceProcessDto sourceProcessDto = packetReaderService.getSourceAndProcess(metaDto.getId(), metaDto.getSource(), metaDto.getProcess()); - List> resultFields = packetReader.getAudits(metaDto.getId(), - sourceProcessDto.getSource(), sourceProcessDto.getProcess(), metaDto.getBypassCache()); - List resultField = new ArrayList<>(); - if (resultFields != null && !resultFields.isEmpty()) { - resultFields.stream().forEach(e -> { - FieldResponseDto fieldResponseDto = new FieldResponseDto(e); - resultField.add(fieldResponseDto); - }); - } - ResponseWrapper> response = getResponseWrapper(); - response.setResponse(resultField); - return response; - } + return wrapResponse(new FieldResponseDto(fields)); + } + + @ResponseFilter + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostaudits())") + @PostMapping(path = "/audits", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "getAudits", description = "getAudits", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) + public ResponseWrapper> getAudits( + @RequestBody(required = true) RequestWrapper request) { + InfoDto metaDto = request.getRequest(); + Optional sourceProcessOpt = getSourceProcess(metaDto.getId(), metaDto.getSource(), + metaDto.getProcess()); + + if (sourceProcessOpt.isEmpty()) { + return wrapResponse(List.of()); + } + + List> audits = packetReader.getAudits(metaDto.getId(), sourceProcessOpt.get().getSource(), + sourceProcessOpt.get().getProcess(), metaDto.getBypassCache()); + + List auditList = Optional.ofNullable(audits).orElseGet(List::of).stream() + .map(FieldResponseDto::new).collect(Collectors.toList()); + + return wrapResponse(auditList); + } + + @ResponseFilter + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostvalidatepacket())") + @PostMapping(path = "/validatePacket", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @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 = "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) { + InfoDto dto = request.getRequest(); - @ResponseFilter - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostvalidatepacket())") - @PostMapping(path = "/validatePacket", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @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 = "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) { - InfoDto metaDto = request.getRequest(); - SourceProcessDto sourceProcessDto = packetReaderService.getSourceAndProcess(metaDto.getId(), metaDto.getSource(), metaDto.getProcess()); - boolean resultFields = packetReader.validatePacket(metaDto.getId(), sourceProcessDto.getSource(), sourceProcessDto.getProcess()); - ResponseWrapper response = getResponseWrapper(); - response.setResponse(new ValidatePacketResponse(resultFields)); - return response; - } + Optional sourceProcessOpt = getSourceProcess(dto.getId(), dto.getSource(), dto.getProcess()); - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostgettags())") - @ResponseFilter + boolean isValid = sourceProcessOpt + .map(sp -> packetReader.validatePacket(dto.getId(), sp.getSource(), sp.getProcess())).orElse(false); + + return wrapResponse(new ValidatePacketResponse(isValid)); + } + + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostgettags())") + @ResponseFilter @PostMapping(path = "/getTags", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "getTags", description = "getTags", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) + @Operation(summary = "getTags", description = "getTags", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public ResponseWrapper getTags( @RequestBody(required = true) RequestWrapper request) { + TagResponseDto tags = packetReaderService.getTags(request.getRequest()); + return wrapResponse(tags); + } - TagResponseDto tagResponseDto = packetReaderService.getTags(request.getRequest()); - ResponseWrapper response = getResponseWrapper(); - response.setResponse(tagResponseDto); + @ResponseFilter + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostinfo())") + @PostMapping(path = "/info", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "info", description = "info", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) + public ResponseWrapper info(@RequestBody(required = true) RequestWrapper request) { + InfoRequestDto dto = request.getRequest(); + InfoResponseDto info = (dto.getId() != null && !dto.getId().isEmpty()) ? packetReaderService.info(dto.getId()) + : null; + return wrapResponse(info); + } + + private ResponseWrapper wrapResponse(T data) { + ResponseWrapper response = new ResponseWrapper<>(); + response.setId("mosip.registration.packet.reader"); + response.setVersion("v1"); + response.setResponsetime(DateUtils.getUTCCurrentDateTime()); + response.setResponse(data); return response; } - @ResponseFilter - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostinfo())") - @PostMapping(path = "/info", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "info", description = "info", 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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper info(@RequestBody(required = true) RequestWrapper request) { - String id = request.getRequest().getId(); - InfoResponseDto resultFields = null; - if (id != null && !id.isEmpty()) - resultFields = packetReaderService.info(id); - ResponseWrapper response = getResponseWrapper(); - response.setResponse(resultFields); - return response; - } + private Optional getSourceProcess(String id, String field, String source, String process) { + return Optional.ofNullable(packetReaderService.getSourceAndProcess(id, field, source, process)); + } - private ResponseWrapper getResponseWrapper() { - ResponseWrapper response = new ResponseWrapper<>(); - response.setId("mosip.registration.packet.reader"); - response.setVersion("v1"); - response.setResponsetime(DateUtils.getUTCCurrentDateTime()); - return response; - } -} + private Optional getSourceProcess(String id, String source, String process) { + return Optional.ofNullable(packetReaderService.getSourceAndProcess(id, source, process)); + } +} \ No newline at end of file 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 4fa43684ab..c86b7e9fee 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 @@ -1,36 +1,34 @@ package io.mosip.commons.packetmanager.controller; -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.http.ResponseWrapper; +import java.util.List; + import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; -import java.util.ArrayList; -import java.util.List; +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.exception.ServiceError; +import io.mosip.kernel.core.http.ResponseWrapper; @RestControllerAdvice public class PacketServiceControllerAdvice { - @ExceptionHandler(BaseCheckedException.class) - public ResponseEntity baseCheckedException(BaseCheckedException e) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(getResponse(e.getErrorCode(), e.getErrorText())); - } + @ExceptionHandler(BaseCheckedException.class) + public ResponseEntity> handleBaseCheckedException(BaseCheckedException e) { + return buildResponse(e.getErrorCode(), e.getErrorText()); + } - @ExceptionHandler(BaseUncheckedException.class) - public ResponseEntity baseUnCheckedException(BaseUncheckedException e) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(getResponse(e.getErrorCode(), e.getErrorText())); - } + @ExceptionHandler(BaseUncheckedException.class) + public ResponseEntity> handleBaseUncheckedException(BaseUncheckedException e) { + return buildResponse(e.getErrorCode(), e.getErrorText()); + } - private ResponseWrapper getResponse(String errorCode, String message) { - ResponseWrapper response = new ResponseWrapper<>(); - ServiceError serviceError = new ServiceError(errorCode, message); - List errors = new ArrayList(); - errors.add(serviceError); - response.setErrors(errors); - return response; - } -} + private ResponseEntity> buildResponse(String errorCode, String message) { + ServiceError serviceError = new ServiceError(errorCode, message); + ResponseWrapper response = new ResponseWrapper<>(); + response.setErrors(List.of(serviceError)); + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(response); + } +} \ No newline at end of file diff --git a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketWriterController.java b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketWriterController.java index d9193d0099..c997420347 100644 --- a/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketWriterController.java +++ b/commons-packet/commons-packet-service/src/main/java/io/mosip/commons/packetmanager/controller/PacketWriterController.java @@ -22,50 +22,39 @@ import io.mosip.kernel.core.http.ResponseFilter; import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.util.DateUtils; - import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; @RestController @Tag(name = "packet-writer-controller", description = "Packet Writer Controller") public class PacketWriterController { - @Autowired - private PacketWriter packetWriter; + @Autowired + private PacketWriter packetWriter; + + @Autowired + private PacketWriterService packetWriterService; - @Autowired - private PacketWriterService packetWriterService; @PreAuthorize("hasAnyRole(@authorizedRoles.getPutcreatepacket())") - @ResponseFilter - @PutMapping(path = "/createPacket", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @ResponseFilter + @PutMapping(path = "/createPacket", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "createPacket", description = "createPacket", tags = { "packet-writer-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 = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper> createPacket(@RequestBody(required = true) RequestWrapper requestr) { - - List resultField = packetWriter.createPacket(requestr.getRequest()); - ResponseWrapper> response = getResponseWrapper(); - response.setResponse(resultField); - return response; - } - - private ResponseWrapper getResponseWrapper() { - ResponseWrapper response = new ResponseWrapper<>(); - response.setId("mosip.registration.packet.writer"); - response.setVersion("v1"); - response.setResponsetime(DateUtils.getUTCCurrentDateTime()); - return response; - } + public ResponseWrapper> createPacket( + @RequestBody(required = true) RequestWrapper request) { + List packets = packetWriter.createPacket(request.getRequest()); + return wrapResponse(packets); + } - //@PreAuthorize("hasAnyRole('REGISTRATION_PROCESSOR')") + // @PreAuthorize("hasAnyRole('REGISTRATION_PROCESSOR')") @PreAuthorize("hasAnyRole(@authorizedRoles.getPostaddtag())") @ResponseFilter @PostMapping(path = "/addTag", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @@ -75,16 +64,13 @@ private ResponseWrapper getResponseWrapper() { @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 setTags( - @RequestBody(required = true) RequestWrapper tagRequest) { - - TagResponseDto tagResponse = packetWriterService.addTags(tagRequest.getRequest()); - ResponseWrapper response = getResponseWrapper(); - response.setResponse(tagResponse); - return response; + public ResponseWrapper setTags(@RequestBody(required = true) RequestWrapper tagRequest) { + TagResponseDto responseDto = packetWriterService.addTags(tagRequest.getRequest()); + return wrapResponse(responseDto); } + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostaddorupdatetag())") - //@PreAuthorize("hasAnyRole('REGISTRATION_PROCESSOR')") + // @PreAuthorize("hasAnyRole('REGISTRATION_PROCESSOR')") @ResponseFilter @PostMapping(path = "/addOrUpdateTag", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "updateTags", description = "updateTags", tags = { "packet-writer-controller" }) @@ -94,13 +80,11 @@ public ResponseWrapper setTags( @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 updateTags(@RequestBody(required = true) RequestWrapper tagRequest) { - - TagResponseDto tagResponse = packetWriterService.updateTags(tagRequest.getRequest()); - ResponseWrapper response = getResponseWrapper(); - response.setResponse(tagResponse); - return response; + TagResponseDto responseDto = packetWriterService.updateTags(tagRequest.getRequest()); + return wrapResponse(responseDto); } - //@PreAuthorize("hasAnyRole('REGISTRATION_PROCESSOR')") + + // @PreAuthorize("hasAnyRole('REGISTRATION_PROCESSOR')") @ResponseFilter @PreAuthorize("hasAnyRole(@authorizedRoles.getPostdeletetag())") @PostMapping(path = "/deleteTag", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @@ -110,11 +94,18 @@ public ResponseWrapper updateTags(@RequestBody(required = 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 deleteTags(@RequestBody(required = true) RequestWrapper tagRequest) { + public ResponseWrapper deleteTags( + @RequestBody(required = true) RequestWrapper tagRequest) { + TagDeleteResponseDto responseDto = packetWriterService.deleteTags(tagRequest.getRequest()); + return wrapResponse(responseDto); + } - TagDeleteResponseDto tagResponse = packetWriterService.deleteTags(tagRequest.getRequest()); - ResponseWrapper response = getResponseWrapper(); - response.setResponse(tagResponse); + private ResponseWrapper wrapResponse(T data) { + ResponseWrapper response = new ResponseWrapper<>(); + response.setId("mosip.registration.packet.writer"); + response.setVersion("v1"); + response.setResponsetime(DateUtils.getUTCCurrentDateTime()); + response.setResponse(data); return response; } -} +} \ No newline at end of file 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 ec43a4e66b..bc453068ea 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 @@ -49,348 +49,361 @@ @Component public class PacketReaderService { - private static Logger LOGGER = PacketManagerLogger.getLogger(PacketReaderService.class); - private static final String VALUE = "value"; - private static final String INDIVIDUAL_BIOMETRICS = "individualBiometrics"; - private static final String IDENTITY = "identity"; - private static final String DOCUMENTS = "documents"; - public static final String META_INFO = "metaInfo"; - public static final String AUDITS = "audits"; - private static final String SOURCE = "source"; - private static final String PROCESS = "process"; - private static final String PROVIDER = "provider"; - private String key = null; - private static final String sourceInitial = "source:"; - private static final String processInitial = "process:"; - private JSONObject mappingJson = null; - - @Value("${config.server.file.storage.uri}") - private String configServerUrl; - - @Value("${registration.processor.identityjson}") - private String mappingjsonFileName; - - @Value("${packetmanager.default.read.strategy}") - private String defaultStrategy; - - @Value("${packetmanager.default.priority}") - private String defaultPriority; - - @Autowired - private PacketReader packetReader; - - @Autowired - @Qualifier("selfTokenRestTemplate") - private RestTemplate restTemplate; - - @Value("#{T(java.util.Arrays).asList('${packetmanager.additional.fields.search.from.metainfo:officerBiometricFileName,supervisorBiometricFileName}')}") - private List additionalFieldsSearch; - - @Autowired - private ObjectMapper objectMapper; - - public InfoResponseDto info(String id) { - return mergeProcessWithMultipleIteration(infoInternal(id)); - } - - private InfoResponseDto infoInternal(String id) { - try { - List allObjects = packetReader.info(id); - List containerInfoDtos = new ArrayList<>(); - for (ObjectDto o : allObjects) { - if (!containerInfoDtos.stream().anyMatch(info -> info.getSource().equalsIgnoreCase(o.getSource()) && info.getProcess().equalsIgnoreCase(o.getProcess()))) { - ContainerInfoDto containerInfo = new ContainerInfoDto(); - containerInfo.setSource(o.getSource()); - containerInfo.setProcess(o.getProcess()); - containerInfo.setLastModified(o.getLastModified()); - - //get demographic fields - Set demographics = packetReader.getAllKeys(id, containerInfo.getSource(), containerInfo.getProcess()); - // get biometrics - List biometrics = null; - BiometricRecord br = packetReader.getBiometric(id, getKey(), Lists.newArrayList(), o.getSource(), o.getProcess(), false); - if (br != null && !CollectionUtils.isEmpty(br.getSegments())) { - Map> biomap = new HashMap<>(); - for (BIR b : br.getSegments()) { - String key = b.getBdbInfo().getType().iterator().next().value(); + private static Logger LOGGER = PacketManagerLogger.getLogger(PacketReaderService.class); + private static final String VALUE = "value"; + private static final String INDIVIDUAL_BIOMETRICS = "individualBiometrics"; + private static final String IDENTITY = "identity"; + private static final String DOCUMENTS = "documents"; + public static final String META_INFO = "metaInfo"; + public static final String AUDITS = "audits"; + private static final String SOURCE = "source"; + private static final String PROCESS = "process"; + private static final String PROVIDER = "provider"; + private String key = null; + private static final String sourceInitial = "source:"; + private static final String processInitial = "process:"; + private JSONObject mappingJson = null; + + @Value("${config.server.file.storage.uri}") + private String configServerUrl; + + @Value("${registration.processor.identityjson}") + private String mappingjsonFileName; + + @Value("${packetmanager.default.read.strategy}") + private String defaultStrategy; + + @Value("${packetmanager.default.priority}") + private String defaultPriority; + + @Autowired + private PacketReader packetReader; + + @Autowired + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + + @Value("#{T(java.util.Arrays).asList('${packetmanager.additional.fields.search.from.metainfo:officerBiometricFileName,supervisorBiometricFileName}')}") + private List additionalFieldsSearch; + + @Autowired + private ObjectMapper objectMapper; + + public InfoResponseDto info(String id) { + return mergeProcessWithMultipleIteration(infoInternal(id)); + } + + private InfoResponseDto infoInternal(String id) { + try { + List allObjects = packetReader.info(id); + List containerInfoDtos = new ArrayList<>(); + for (ObjectDto o : allObjects) { + if (!containerInfoDtos.stream().anyMatch(info -> info.getSource().equalsIgnoreCase(o.getSource()) + && info.getProcess().equalsIgnoreCase(o.getProcess()))) { + ContainerInfoDto containerInfo = new ContainerInfoDto(); + containerInfo.setSource(o.getSource()); + containerInfo.setProcess(o.getProcess()); + containerInfo.setLastModified(o.getLastModified()); + + // get demographic fields + Set demographics = packetReader.getAllKeys(id, containerInfo.getSource(), + containerInfo.getProcess()); + // get biometrics + List biometrics = null; + BiometricRecord br = packetReader.getBiometric(id, getKey(), Lists.newArrayList(), o.getSource(), + o.getProcess(), false); + if (br != null && !CollectionUtils.isEmpty(br.getSegments())) { + Map> biomap = new HashMap<>(); + for (BIR b : br.getSegments()) { + String key = b.getBdbInfo().getType().iterator().next().value(); String subtype = null; if (b.getBdbInfo().getSubtype() != null) { subtype = b.getBdbInfo().getSubtype().stream().collect(Collectors.joining(" ")).strip(); } - if (biomap.get(key) == null) - biomap.put(key, StringUtils.isNotEmpty(subtype) ? Lists.newArrayList(subtype) : null); - else { - List finalVal = biomap.get(key); - finalVal.add(subtype); - biomap.put(key, finalVal); - } - } - biometrics = new ArrayList<>(); - for (Map.Entry> b : biomap.entrySet()) { - BiometricsDto bioDto = new BiometricsDto(); - bioDto.setType(b.getKey()); - bioDto.setSubtypes(b.getValue()); - biometrics.add(bioDto); - } - } - - containerInfo.setDemographics(demographics); - containerInfo.setBiometrics(biometrics); - containerInfoDtos.add(containerInfo); - } - } - // get tags - Map tags = packetReader.getTags(id); - - InfoResponseDto infoResponseDto = new InfoResponseDto(); - infoResponseDto.setApplicationId(id); - infoResponseDto.setPacketId(id); - infoResponseDto.setInfo(containerInfoDtos); + if (biomap.get(key) == null) + biomap.put(key, StringUtils.isNotEmpty(subtype) ? Lists.newArrayList(subtype) : null); + else { + List finalVal = biomap.get(key); + finalVal.add(subtype); + biomap.put(key, finalVal); + } + } + biometrics = new ArrayList<>(); + for (Map.Entry> b : biomap.entrySet()) { + BiometricsDto bioDto = new BiometricsDto(); + bioDto.setType(b.getKey()); + bioDto.setSubtypes(b.getValue()); + biometrics.add(bioDto); + } + } + + containerInfo.setDemographics(demographics); + containerInfo.setBiometrics(biometrics); + containerInfoDtos.add(containerInfo); + } + } + // get tags + Map tags = packetReader.getTags(id); + + InfoResponseDto infoResponseDto = new InfoResponseDto(); + infoResponseDto.setApplicationId(id); + infoResponseDto.setPacketId(id); + infoResponseDto.setInfo(containerInfoDtos); infoResponseDto.setTags(tags); - return infoResponseDto; - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, ExceptionUtils.getStackTrace(e)); - - if (e instanceof BaseUncheckedException) { - BaseUncheckedException ex = (BaseUncheckedException) e; - throw ex; - } - else if (e instanceof BaseCheckedException) { - BaseCheckedException ex = (BaseCheckedException) e; - throw new BaseUncheckedException(ex.getErrorCode(), ex.getMessage(), ex); - } - else - throw new BaseUncheckedException(PacketUtilityErrorCodes.UNKNOWN_EXCEPTION.getErrorCode(), e.getMessage(), e); - } - } - - private String getKey() throws IOException { - - JSONObject jsonObject = getMappingJsonFile(); - if(jsonObject != null) { - LinkedHashMap individualBio = (LinkedHashMap) jsonObject.get(INDIVIDUAL_BIOMETRICS); - key = individualBio.get(VALUE); - return key; - } - return null; - - } - - - public SourceProcessDto getSourceAndProcess(String id, String source, String process) { - if (StringUtils.isEmpty(source)) { - try { - if (defaultStrategy.equalsIgnoreCase(DefaultStrategy.DEFAULT_PRIORITY.getValue())) { - source = getDefaultSource(process); - } else { - throw new SourceNotPresentException(); - } - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, ExceptionUtils.getStackTrace(e)); - throw new SourceNotPresentException(e); - } - } - ObjectDto objectDto = searchProcessWithLatestIteration(id, source, process); - return new SourceProcessDto(objectDto.getSource(), objectDto.getProcess()); - } - - public SourceProcessDto getSourceAndProcess(String id, String field, String source, String process) { - SourceProcessDto sourceProcessDto = null; - InfoResponseDto infoResponseDto = infoInternal(id); - List info = infoResponseDto.getInfo(); - // sorting in reverse order by process name to search from latest iteration first. - Collections.sort(info, (i1, i2) -> extractInt(i2.getProcess()) - (extractInt(i1.getProcess()))); - if (StringUtils.isEmpty(source)) { - try { - if (defaultStrategy.equalsIgnoreCase(DefaultStrategy.DEFAULT_PRIORITY.getValue())) { - ContainerInfoDto containerInfoDto = findPriority(field, info); - if (containerInfoDto == null) - return null; - sourceProcessDto = new SourceProcessDto(containerInfoDto.getSource(), containerInfoDto.getProcess()); - } - } catch (Exception e) { - LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, ExceptionUtils.getStackTrace(e)); - throw new SourceNotPresentException(e); - } - - } else { - ContainerInfoDto containerInfoDto = getContainerInfoBySourceAndProcess(field, source, process, info); - sourceProcessDto = containerInfoDto != null ? - new SourceProcessDto(containerInfoDto.getSource(), containerInfoDto.getProcess()) : null; - } - return sourceProcessDto; - } - - public ContainerInfoDto findPriority(String field, List info) { - if (info.size() == 1) - return info.iterator().next(); - else - return getContainerInfoByDefaultPriority(field, info); - } - - private ContainerInfoDto getContainerInfoByDefaultPriority(String field, List info) { - if (StringUtils.isNotEmpty(defaultPriority)) { - String[] val = defaultPriority.split(","); - if (val != null && val.length > 0) { - for (String value : val) { - String[] str = value.split("/"); - if (str != null && str.length > 0 && str[0].startsWith(sourceInitial)) { - String sourceStr = str[0].substring(sourceInitial.length()); - String processStr = str[1].substring(processInitial.length()); - for (String process : processStr.split("\\|")) { - Optional containerDto = info.stream().filter(infoDto -> - isFieldPresent(field, infoDto) && infoDto.getSource().equalsIgnoreCase(sourceStr) - && PacketHelper.getProcessWithoutIteration(infoDto.getProcess()).equalsIgnoreCase(process)).findAny(); - // if container is not present then continue searching - if (containerDto.isPresent()) { - return containerDto.get(); - } else - continue; - } - } - } - } - } - return null; - } - - private boolean isFieldPresent(String field, ContainerInfoDto infoDto) { - if (additionalFieldsSearch.contains(field)) - return true; - else - return infoDto.getDemographics() != null && infoDto.getDemographics().contains(field); - } - - private ContainerInfoDto getContainerInfoBySourceAndProcess(String field, String source, String process, List info) { - Optional containerDto = info.stream().filter(infoDto -> - infoDto.getDemographics() != null && infoDto.getDemographics().contains(field) && infoDto.getSource().equalsIgnoreCase(source) - && PacketHelper.getProcessWithoutIteration(infoDto.getProcess()).equalsIgnoreCase(process)).findAny(); - - return containerDto.isPresent() ? containerDto.get() : null; - } - - private String getDefaultSource(String process) { - if (StringUtils.isNotEmpty(defaultPriority)) { - String[] val = defaultPriority.split(","); - if (val != null && val.length > 0) { - for (String value : val) { - String[] str = value.split("/"); - if (str != null && str.length > 0 && str[0].startsWith(sourceInitial)) { - String sourceStr = str[0].substring(sourceInitial.length()); - String processStr = str[1].substring(processInitial.length()); - String[] processes = processStr.split("\\|"); - if (Arrays.stream(processes).filter(p -> p.equalsIgnoreCase(process)).findAny().isPresent()) - return sourceStr; - } - } - } - } else - throw new SourceNotPresentException(); - return null; - } - - private ObjectDto searchProcessWithLatestIteration(String id, String source, String process) { - List allObjects = packetReader.info(id); - Collections.sort(allObjects, (i1, i2) -> extractInt(i2.getProcess()) - (extractInt(i1.getProcess()))); - - Optional objectDto = allObjects.stream().filter(obj -> - obj.getSource().equals(source) - && PacketHelper.getProcessWithoutIteration(obj.getProcess()).equalsIgnoreCase(process)).findAny(); - - return objectDto.isPresent() ? objectDto.get() : getObjectDto(source, process); - } - - public String getSourceFromIdField(String process, String idField) throws IOException { - JSONObject jsonObject = getMappingJsonFile(); - for (Object key : jsonObject.keySet()) { - LinkedHashMap hMap = (LinkedHashMap) jsonObject.get(key); - String value = (String) hMap.get(VALUE); - if (value != null && value.contains(idField)) { - return getSource(jsonObject, process, key.toString()); - } - } - 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(); - for (Object key : jsonObject.keySet()) { - LinkedHashMap hMap = (LinkedHashMap) jsonObject.get(key); - String value = (String) hMap.get(VALUE); - if (value != null && value.contains(idField)) { - return getSource(jsonObject, process, key.toString()); - } - } - } - return null; - } - - private String getSource(JSONObject jsonObject, String process, String field) { - String source = null; - Object obj = field == null ? jsonObject.get(PROVIDER) : getField(jsonObject, field); - if (obj != null && obj instanceof ArrayList) { - List providerList = (List) obj; - for (String value : providerList) { - String[] values = value.split(","); - for (String provider : values) { - if (provider != null) { - if (provider.startsWith(PROCESS) && provider.contains(process)) { - for (String val : values) { - if (val.startsWith(SOURCE)) { - return val.replace(SOURCE + ":", "").trim(); - } - } - } - } - } - } - } - - return source; - } - - private Object getField(JSONObject jsonObject, String field) { - LinkedHashMap lm = (LinkedHashMap) jsonObject.get(field); - return lm.get(PROVIDER); - } - - private static JSONObject getJSONObject(JSONObject jsonObject, Object key) { - if(jsonObject == null) - return null; - LinkedHashMap identity = (LinkedHashMap) jsonObject.get(key); - return identity != null ? new JSONObject(identity) : null; - } - - private JSONObject getMappingJsonFile() throws IOException { - if (mappingJson != null) - return mappingJson; - - String mappingJsonString = restTemplate.getForObject(configServerUrl + "/" + mappingjsonFileName, String.class); - JSONObject jsonObject = objectMapper.readValue(mappingJsonString, JSONObject.class); - LinkedHashMap combinedMap = new LinkedHashMap(); - combinedMap.putAll((Map) jsonObject.get(IDENTITY)); - combinedMap.putAll((Map) jsonObject.get(DOCUMENTS)); - combinedMap.put(META_INFO, jsonObject.get(META_INFO)); - combinedMap.put(AUDITS, jsonObject.get(AUDITS)); - mappingJson = new JSONObject(combinedMap); - return mappingJson; - } - - public TagResponseDto getTags(TagRequestDto tagRequestDto) { - try { + return infoResponseDto; + } catch (Exception e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + ExceptionUtils.getStackTrace(e)); + + if (e instanceof BaseUncheckedException) { + BaseUncheckedException ex = (BaseUncheckedException) e; + throw ex; + } else if (e instanceof BaseCheckedException) { + BaseCheckedException ex = (BaseCheckedException) e; + throw new BaseUncheckedException(ex.getErrorCode(), ex.getMessage(), ex); + } else + throw new BaseUncheckedException(PacketUtilityErrorCodes.UNKNOWN_EXCEPTION.getErrorCode(), + e.getMessage(), e); + } + } + + private String getKey() throws IOException { + + JSONObject jsonObject = getMappingJsonFile(); + if (jsonObject != null) { + LinkedHashMap individualBio = (LinkedHashMap) jsonObject.get(INDIVIDUAL_BIOMETRICS); + key = individualBio.get(VALUE); + return key; + } + return null; + } + + public SourceProcessDto getSourceAndProcess(String id, String source, String process) { + if (StringUtils.isEmpty(source)) { + try { + if (defaultStrategy.equalsIgnoreCase(DefaultStrategy.DEFAULT_PRIORITY.getValue())) { + source = getDefaultSource(process); + } else { + throw new SourceNotPresentException(); + } + } catch (Exception e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + ExceptionUtils.getStackTrace(e)); + throw new SourceNotPresentException(e); + } + } + ObjectDto objectDto = searchProcessWithLatestIteration(id, source, process); + return new SourceProcessDto(objectDto.getSource(), objectDto.getProcess()); + } + + public SourceProcessDto getSourceAndProcess(String id, String field, String source, String process) { + SourceProcessDto sourceProcessDto = null; + InfoResponseDto infoResponseDto = infoInternal(id); + List info = infoResponseDto.getInfo(); + // sorting in reverse order by process name to search from latest iteration + // first. + Collections.sort(info, (i1, i2) -> extractInt(i2.getProcess()) - (extractInt(i1.getProcess()))); + if (StringUtils.isEmpty(source)) { + try { + if (defaultStrategy.equalsIgnoreCase(DefaultStrategy.DEFAULT_PRIORITY.getValue())) { + ContainerInfoDto containerInfoDto = findPriority(field, info); + if (containerInfoDto == null) + return null; + sourceProcessDto = new SourceProcessDto(containerInfoDto.getSource(), + containerInfoDto.getProcess()); + } + } catch (Exception e) { + LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, id, + ExceptionUtils.getStackTrace(e)); + throw new SourceNotPresentException(e); + } + + } else { + ContainerInfoDto containerInfoDto = getContainerInfoBySourceAndProcess(field, source, process, info); + sourceProcessDto = containerInfoDto != null + ? new SourceProcessDto(containerInfoDto.getSource(), containerInfoDto.getProcess()) + : null; + } + return sourceProcessDto; + } + + public ContainerInfoDto findPriority(String field, List info) { + if (info.size() == 1) + return info.iterator().next(); + else + return getContainerInfoByDefaultPriority(field, info); + } + + private ContainerInfoDto getContainerInfoByDefaultPriority(String field, List info) { + if (StringUtils.isNotEmpty(defaultPriority)) { + String[] val = defaultPriority.split(","); + if (val != null && val.length > 0) { + for (String value : val) { + String[] str = value.split("/"); + if (str != null && str.length > 0 && str[0].startsWith(sourceInitial)) { + String sourceStr = str[0].substring(sourceInitial.length()); + String processStr = str[1].substring(processInitial.length()); + for (String process : processStr.split("\\|")) { + Optional containerDto = info.stream() + .filter(infoDto -> isFieldPresent(field, infoDto) + && infoDto.getSource().equalsIgnoreCase(sourceStr) + && PacketHelper.getProcessWithoutIteration(infoDto.getProcess()) + .equalsIgnoreCase(process)) + .findAny(); + // if container is not present then continue searching + if (containerDto.isPresent()) { + return containerDto.get(); + } else + continue; + } + } + } + } + } + return null; + } + + private boolean isFieldPresent(String field, ContainerInfoDto infoDto) { + if (additionalFieldsSearch.contains(field)) + return true; + else + return infoDto.getDemographics() != null && infoDto.getDemographics().contains(field); + } + + private ContainerInfoDto getContainerInfoBySourceAndProcess(String field, String source, String process, + List info) { + Optional containerDto = info.stream() + .filter(infoDto -> infoDto.getDemographics() != null && infoDto.getDemographics().contains(field) + && infoDto.getSource().equalsIgnoreCase(source) + && PacketHelper.getProcessWithoutIteration(infoDto.getProcess()).equalsIgnoreCase(process)) + .findAny(); + + return containerDto.isPresent() ? containerDto.get() : null; + } + + private String getDefaultSource(String process) { + if (StringUtils.isNotEmpty(defaultPriority)) { + String[] val = defaultPriority.split(","); + if (val != null && val.length > 0) { + for (String value : val) { + String[] str = value.split("/"); + if (str != null && str.length > 0 && str[0].startsWith(sourceInitial)) { + String sourceStr = str[0].substring(sourceInitial.length()); + String processStr = str[1].substring(processInitial.length()); + String[] processes = processStr.split("\\|"); + if (Arrays.stream(processes).filter(p -> p.equalsIgnoreCase(process)).findAny().isPresent()) + return sourceStr; + } + } + } + } else + throw new SourceNotPresentException(); + return null; + } + + private ObjectDto searchProcessWithLatestIteration(String id, String source, String process) { + List allObjects = packetReader.info(id); + Collections.sort(allObjects, (i1, i2) -> extractInt(i2.getProcess()) - (extractInt(i1.getProcess()))); + + Optional objectDto = allObjects.stream() + .filter(obj -> obj.getSource().equals(source) + && PacketHelper.getProcessWithoutIteration(obj.getProcess()).equalsIgnoreCase(process)) + .findAny(); + + return objectDto.isPresent() ? objectDto.get() : getObjectDto(source, process); + } + + public String getSourceFromIdField(String process, String idField) throws IOException { + JSONObject jsonObject = getMappingJsonFile(); + for (Object key : jsonObject.keySet()) { + LinkedHashMap hMap = (LinkedHashMap) jsonObject.get(key); + String value = (String) hMap.get(VALUE); + if (value != null && value.contains(idField)) { + return getSource(jsonObject, process, key.toString()); + } + } + 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(); + for (Object key : jsonObject.keySet()) { + LinkedHashMap hMap = (LinkedHashMap) jsonObject.get(key); + String value = (String) hMap.get(VALUE); + if (value != null && value.contains(idField)) { + return getSource(jsonObject, process, key.toString()); + } + } + } + return null; + } + + private String getSource(JSONObject jsonObject, String process, String field) { + String source = null; + Object obj = field == null ? jsonObject.get(PROVIDER) : getField(jsonObject, field); + if (obj != null && obj instanceof ArrayList) { + List providerList = (List) obj; + for (String value : providerList) { + String[] values = value.split(","); + for (String provider : values) { + if (provider != null) { + if (provider.startsWith(PROCESS) && provider.contains(process)) { + for (String val : values) { + if (val.startsWith(SOURCE)) { + return val.replace(SOURCE + ":", "").trim(); + } + } + } + } + } + } + } + + return source; + } + + private Object getField(JSONObject jsonObject, String field) { + LinkedHashMap lm = (LinkedHashMap) jsonObject.get(field); + return lm.get(PROVIDER); + } + + private static JSONObject getJSONObject(JSONObject jsonObject, Object key) { + if (jsonObject == null) + return null; + LinkedHashMap identity = (LinkedHashMap) jsonObject.get(key); + return identity != null ? new JSONObject(identity) : null; + } + + private JSONObject getMappingJsonFile() throws IOException { + if (mappingJson != null) + return mappingJson; + + String mappingJsonString = restTemplate.getForObject(configServerUrl + "/" + mappingjsonFileName, String.class); + JSONObject jsonObject = objectMapper.readValue(mappingJsonString, JSONObject.class); + LinkedHashMap combinedMap = new LinkedHashMap(); + combinedMap.putAll((Map) jsonObject.get(IDENTITY)); + combinedMap.putAll((Map) jsonObject.get(DOCUMENTS)); + combinedMap.put(META_INFO, jsonObject.get(META_INFO)); + combinedMap.put(AUDITS, jsonObject.get(AUDITS)); + mappingJson = new JSONObject(combinedMap); + return mappingJson; + } + + public TagResponseDto getTags(TagRequestDto tagRequestDto) { + try { Map tags = new HashMap(); Map existingTags = packetReader.getTags(tagRequestDto.getId()); - List tagNames=tagRequestDto.getTagNames(); - TagResponseDto tagResponseDto = new TagResponseDto(); + List tagNames = tagRequestDto.getTagNames(); + TagResponseDto tagResponseDto = new TagResponseDto(); if (tagNames != null && !tagNames.isEmpty()) { for (String tag : tagNames) { if (existingTags.containsKey(tag)) { @@ -404,7 +417,7 @@ public TagResponseDto getTags(TagRequestDto tagRequestDto) { } else { tagResponseDto.setTags(existingTags); } - return tagResponseDto; + return tagResponseDto; } catch (Exception e) { LOGGER.error(PacketManagerLogger.SESSIONID, PacketManagerLogger.REGISTRATIONID, tagRequestDto.getId(), ExceptionUtils.getStackTrace(e)); @@ -419,49 +432,52 @@ public TagResponseDto getTags(TagRequestDto tagRequestDto) { } - } - - /** - * If there are processes with multiple iteration then this method will merge these processes into one. - * (Ex - if there are containers with processes - CORRECTION-1,CORRECTION-2,CORRECTION-3 - * then this method will merge 3 container into 1 container with process name - 'CORRECTION') - * - * @param infoResponseDto - * @return InfoResponseDto - */ - private InfoResponseDto mergeProcessWithMultipleIteration(InfoResponseDto infoResponseDto) { - List finalInfos = new ArrayList<>(); - // map contains unique source process without iteration. - Map> sourceProcessMap = new HashMap<>(); - - for (ContainerInfoDto info : infoResponseDto.getInfo()) { - String process = PacketHelper.getProcessWithoutIteration(info.getProcess()); - if (sourceProcessMap.containsKey(info.getSource()) && sourceProcessMap.get(info.getSource()).contains(process)) { - // merge container info for same source process with multiple iteration - ContainerInfoDto finalInfo = setContainerInfo(finalInfos, info, process); - - finalInfo.setDemographics(mergeDemographics(finalInfo, info)); - finalInfo.setBiometrics(mergeBiometrics(finalInfo, info)); - finalInfo.setDocuments(mergeDocuments(finalInfo, info)); - - finalInfos.add(finalInfo); - - } else { - // add unique source process in the sourceProcessMap - List processes = sourceProcessMap.get(info.getSource()) == null ? - Lists.newArrayList() : sourceProcessMap.get(info.getSource()); - processes.add(process); - sourceProcessMap.put(info.getSource(), processes); - // add container to info response for unique source process - info.setProcess(process); - finalInfos.add(info); - } - } - infoResponseDto.setInfo(finalInfos); - return infoResponseDto; - } - - private ContainerInfoDto setContainerInfo(List finalInfos, ContainerInfoDto info, String process) { + } + + /** + * If there are processes with multiple iteration then this method will merge + * these processes into one. (Ex - if there are containers with processes - + * CORRECTION-1,CORRECTION-2,CORRECTION-3 then this method will merge 3 + * container into 1 container with process name - 'CORRECTION') + * + * @param infoResponseDto + * @return InfoResponseDto + */ + private InfoResponseDto mergeProcessWithMultipleIteration(InfoResponseDto infoResponseDto) { + List finalInfos = new ArrayList<>(); + // map contains unique source process without iteration. + Map> sourceProcessMap = new HashMap<>(); + + for (ContainerInfoDto info : infoResponseDto.getInfo()) { + String process = PacketHelper.getProcessWithoutIteration(info.getProcess()); + if (sourceProcessMap.containsKey(info.getSource()) + && sourceProcessMap.get(info.getSource()).contains(process)) { + // merge container info for same source process with multiple iteration + ContainerInfoDto finalInfo = setContainerInfo(finalInfos, info, process); + + finalInfo.setDemographics(mergeDemographics(finalInfo, info)); + finalInfo.setBiometrics(mergeBiometrics(finalInfo, info)); + finalInfo.setDocuments(mergeDocuments(finalInfo, info)); + + finalInfos.add(finalInfo); + + } else { + // add unique source process in the sourceProcessMap + List processes = sourceProcessMap.get(info.getSource()) == null ? Lists.newArrayList() + : sourceProcessMap.get(info.getSource()); + processes.add(process); + sourceProcessMap.put(info.getSource(), processes); + // add container to info response for unique source process + info.setProcess(process); + finalInfos.add(info); + } + } + infoResponseDto.setInfo(finalInfos); + return infoResponseDto; + } + + private ContainerInfoDto setContainerInfo(List finalInfos, ContainerInfoDto info, + String process) { Optional optionalInfo = finalInfos.stream() .filter(i -> i.getSource().equals(info.getSource()) && i.getProcess().equals(process)).findAny(); @@ -482,59 +498,60 @@ private ContainerInfoDto setContainerInfo(List finalInfos, Con } - - private Set mergeDemographics(ContainerInfoDto existingInfo, ContainerInfoDto newInfo) { - if (newInfo.getDemographics() == null) - return existingInfo.getDemographics(); - - Set existingDemographics = existingInfo.getDemographics(); - for (String demoKey : newInfo.getDemographics()) - if (!existingDemographics.contains(demoKey)) - existingDemographics.add(demoKey); - - return existingDemographics; - } - - private List mergeBiometrics(ContainerInfoDto existingInfo, ContainerInfoDto newInfo) { - if (newInfo.getBiometrics() == null) - return existingInfo.getBiometrics(); - - List mergedBiometrics = new ArrayList<>(); - List newInfoBiometrics = newInfo.getBiometrics(); - List existingBiometrics = existingInfo.getBiometrics(); - for (BiometricsDto biometric : newInfoBiometrics) { - Optional existingBio = existingBiometrics.stream().filter(b -> b.getType().equals(biometric.getType())).findAny(); - // if type is already present in existing biometrics then merge all new subtypes - if (existingBio.isPresent() && biometric.getSubtypes() != null && existingBio.get().getSubtypes() != null - && !existingBio.get().getSubtypes().containsAll(biometric.getSubtypes())) { - BiometricsDto mergedBio = existingBio.get(); - mergedBio.getSubtypes().addAll(biometric.getSubtypes()); - mergedBiometrics.add(mergedBio); - } else - // else just add new biometrics - mergedBiometrics.add(biometric); - } - return mergedBiometrics; - } - - private Map mergeDocuments(ContainerInfoDto existingInfo, ContainerInfoDto newInfo) { - if (newInfo.getDocuments() == null) - return existingInfo.getDocuments(); - - // merged documents is initialized with existing documents - Map mergedDocuments = existingInfo.getDocuments() != null ? existingInfo.getDocuments() : Maps.newHashMap(); - - for (String key : newInfo.getDocuments().keySet()) { - if (!existingInfo.getDocuments().containsKey(key)) - mergedDocuments.put(key, newInfo.getDocuments().get(key)); - } - - return mergedDocuments; - } - - private int extractInt(String s) { - String num = s.replaceAll("\\D", ""); - // return 0 if no digits found - return num.isEmpty() ? 0 : Integer.parseInt(num); - } + private Set mergeDemographics(ContainerInfoDto existingInfo, ContainerInfoDto newInfo) { + if (newInfo.getDemographics() == null) + return existingInfo.getDemographics(); + + Set existingDemographics = existingInfo.getDemographics(); + for (String demoKey : newInfo.getDemographics()) + if (!existingDemographics.contains(demoKey)) + existingDemographics.add(demoKey); + + return existingDemographics; + } + + private List mergeBiometrics(ContainerInfoDto existingInfo, ContainerInfoDto newInfo) { + if (newInfo.getBiometrics() == null) + return existingInfo.getBiometrics(); + + List mergedBiometrics = new ArrayList<>(); + List newInfoBiometrics = newInfo.getBiometrics(); + List existingBiometrics = existingInfo.getBiometrics(); + for (BiometricsDto biometric : newInfoBiometrics) { + Optional existingBio = existingBiometrics.stream() + .filter(b -> b.getType().equals(biometric.getType())).findAny(); + // if type is already present in existing biometrics then merge all new subtypes + if (existingBio.isPresent() && biometric.getSubtypes() != null && existingBio.get().getSubtypes() != null + && !existingBio.get().getSubtypes().containsAll(biometric.getSubtypes())) { + BiometricsDto mergedBio = existingBio.get(); + mergedBio.getSubtypes().addAll(biometric.getSubtypes()); + mergedBiometrics.add(mergedBio); + } else + // else just add new biometrics + mergedBiometrics.add(biometric); + } + return mergedBiometrics; + } + + private Map mergeDocuments(ContainerInfoDto existingInfo, ContainerInfoDto newInfo) { + if (newInfo.getDocuments() == null) + return existingInfo.getDocuments(); + + // merged documents is initialized with existing documents + Map mergedDocuments = existingInfo.getDocuments() != null ? existingInfo.getDocuments() + : Maps.newHashMap(); + + for (String key : newInfo.getDocuments().keySet()) { + if (!existingInfo.getDocuments().containsKey(key)) + mergedDocuments.put(key, newInfo.getDocuments().get(key)); + } + + return mergedDocuments; + } + + private int extractInt(String s) { + String num = s.replaceAll("\\D", ""); + // return 0 if no digits found + return num.isEmpty() ? 0 : Integer.parseInt(num); + } }