diff --git a/DEPENDENCIES_FRONTEND b/DEPENDENCIES_FRONTEND index 374507842..88c13a1c0 100644 --- a/DEPENDENCIES_FRONTEND +++ b/DEPENDENCIES_FRONTEND @@ -35,7 +35,7 @@ npm/npmjs/-/browserslist/4.21.4, MIT, approved, #7034 npm/npmjs/-/buffer-crc32/0.2.13, MIT, approved, clearlydefined npm/npmjs/-/buffer/5.7.1, MIT, approved, clearlydefined npm/npmjs/-/cachedir/2.3.0, MIT, approved, clearlydefined -npm/npmjs/-/call-bind/1.0.2, MIT, approved, clearlydefined +npm/npmjs/-/call-bind/1.0.2, MIT, approved, #11092 npm/npmjs/-/callforth/0.3.1, MIT, approved, clearlydefined npm/npmjs/-/callsites/3.1.0, MIT, approved, clearlydefined npm/npmjs/-/caniuse-lite/1.0.30001449, CC-BY-4.0, approved, #1196 diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/Application.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/Application.java index 7bc26e141..74fc21483 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/Application.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/Application.java @@ -23,33 +23,26 @@ package org.eclipse.tractusx.productpass; -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn; import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; import io.swagger.v3.oas.annotations.security.SecurityScheme; import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; -import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.media.StringSchema; -import jakarta.servlet.http.HttpServletRequest; -import org.eclipse.tractusx.productpass.models.http.Response; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.info.BuildProperties; -import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.EnableAsync; -import utils.LogUtil; - -import java.util.Map; +/** + * This class is the main class of the Application, where the main method is to start it with Spring boot. + **/ @SpringBootApplication(scanBasePackages={ "utils", "org.eclipse.tractusx.productpass"}) @EnableAsync @@ -74,6 +67,7 @@ public static void main(String[] args) { application.run(args); } + @Bean public OpenAPI openApiConfig(){ return new OpenAPI().info(getApiInfo()); diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/AppConfig.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/AppConfig.java index fa5d13617..6a914847a 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/AppConfig.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/AppConfig.java @@ -29,6 +29,11 @@ import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +/** + * This class consists exclusively to define the attributes and methods needed for the Application configuration. + **/ + +@SuppressWarnings("Unused") @Configuration public class AppConfig { @Bean diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/DiscoveryConfig.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/DiscoveryConfig.java index 043c67159..5954f0c47 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/DiscoveryConfig.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/DiscoveryConfig.java @@ -28,69 +28,81 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; +/** + * This class consists exclusively to define the attributes and methods needed for the Discovery configuration. + **/ @Configuration @ConfigurationProperties(prefix="configuration.discovery") public class DiscoveryConfig { + + /** ATTRIBUTES **/ String endpoint; BPNConfig bpn; EDCConfig edc; + /** GETTERS AND SETTERS **/ public BPNConfig getBpn() { return bpn; } - public void setBpn(BPNConfig bpn) { this.bpn = bpn; } - public EDCConfig getEdc() { return edc; } - public void setEdc(EDCConfig edc) { this.edc = edc; } + public String getEndpoint() { + return endpoint; + } + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } - public static class BPNConfig{ + /** INNER CLASSES **/ + + /** + * This class consists exclusively to define the attributes and methods needed for the BPN configuration. + **/ + public static class BPNConfig { + + /** ATTRIBUTES **/ String key; String searchPath; + /** GETTERS AND SETTERS **/ public String getKey() { return key; } - public void setKey(String key) { this.key = key; } - public String getSearchPath() { return searchPath; } - + @SuppressWarnings("Unused") public void setSearchPath(String searchPath) { this.searchPath = searchPath; } } - public static class EDCConfig{ + /** + * This class consists exclusively to define the attributes and methods needed for the EDC configuration. + **/ + public static class EDCConfig { + + /** ATTRIBUTES **/ String key; + /** GETTERS AND SETTERS **/ public String getKey() { return key; } - public void setKey(String key) { this.key = key; } } - public String getEndpoint() { - return endpoint; - } - - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } - } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/DtrConfig.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/DtrConfig.java index 1fca2bbc8..28eaea104 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/DtrConfig.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/DtrConfig.java @@ -31,21 +31,29 @@ import java.sql.Time; import java.util.Map; +/** + * This class consists exclusively to define the attributes and methods needed for the Digital Twin Registry (DTR) configuration. + **/ @Configuration @ConfigurationProperties(prefix="configuration.dtr") public class DtrConfig { + + /** ATTRIBUTES **/ Boolean central; String centralUrl; String internalDtr; - Timeouts timeouts; - Boolean temporaryStorage; DecentralApis decentralApis; String assetId; - String endpointInterface; String dspEndpointKey; + + /** CONSTRUCTOR(S) **/ + public DtrConfig() { + } + + /** GETTERS AND SETTERS **/ public DecentralApis getDecentralApis() { return decentralApis; } @@ -55,93 +63,110 @@ public void setDecentralApis(DecentralApis decentralApis) { public DtrConfig(Boolean central) { this.central = central; } - public String getInternalDtr() { return internalDtr; } - public void setInternalDtr(String internalDtr) { this.internalDtr = internalDtr; } - - public Boolean getTemporaryStorage() { return temporaryStorage; } - public void setTemporaryStorage(Boolean temporaryStorage) { this.temporaryStorage = temporaryStorage; } - public Timeouts getTimeouts() { return timeouts; } - public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; } - public String getEndpointInterface() { return endpointInterface; } - public void setEndpointInterface(String endpointInterface) { this.endpointInterface = endpointInterface; } - public String getDspEndpointKey() { return dspEndpointKey; } - public void setDspEndpointKey(String dspEndpointKey) { this.dspEndpointKey = dspEndpointKey; } + public Boolean getCentral() { + return central; + } + public void setCentral(Boolean central) { + this.central = central; + } + public String getCentralUrl() { + return centralUrl; + } + @SuppressWarnings("Unused") + public void setCentralUrl(String centralUrl) { + this.centralUrl = centralUrl; + } + public String getAssetId() { + return assetId; + } + public void setAssetId(String assetId) { + this.assetId = assetId; + } + + /** INNER CLASSES **/ + /** + * This class consists exclusively to define the attributes and methods needed for the DTR's timeouts configuration. + **/ public static class Timeouts{ + + /** ATTRIBUTES **/ Integer search; Integer negotiation; Integer transfer; Integer digitalTwin; + /** GETTERS AND SETTERS **/ public Integer getSearch() { return search; } - public void setSearch(Integer search) { this.search = search; } - public Integer getNegotiation() { return negotiation; } - public void setNegotiation(Integer negotiation) { this.negotiation = negotiation; } - public Integer getTransfer() { return transfer; } - public void setTransfer(Integer transfer) { this.transfer = transfer; } - public Integer getDigitalTwin() { return digitalTwin; } - + @SuppressWarnings("Unused") public void setDigitalTwin(Integer digitalTwin) { this.digitalTwin = digitalTwin; } } + /** + * This class consists exclusively to define the attributes and methods needed for the decentralize APIs configuration. + **/ public static class DecentralApis{ + + /** ATTRIBUTES **/ String prefix; String search; String digitalTwin; String subModel; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public DecentralApis(String prefix, String search, String digitalTwin, String subModel) { this.prefix = prefix; this.search = search; @@ -149,66 +174,39 @@ public DecentralApis(String prefix, String search, String digitalTwin, String su this.subModel = subModel; } + @SuppressWarnings("Unused") public DecentralApis() { } + /** GETTERS AND SETTERS **/ public String getPrefix() { return prefix; } - + @SuppressWarnings("Unused") public void setPrefix(String prefix) { this.prefix = prefix; } - public String getSearch() { return search; } - public void setSearch(String search) { this.search = search; } - + @SuppressWarnings("Unused") public String getDigitalTwin() { return digitalTwin; } - + @SuppressWarnings("Unused") public void setDigitalTwin(String digitalTwin) { this.digitalTwin = digitalTwin; } - + @SuppressWarnings("Unused") public String getSubModel() { return subModel; } - + @SuppressWarnings("Unused") public void setSubModel(String subModel) { this.subModel = subModel; } } - public DtrConfig() { - } - - - public Boolean getCentral() { - return central; - } - - public void setCentral(Boolean central) { - this.central = central; - } - - public String getCentralUrl() { - return centralUrl; - } - - public void setCentralUrl(String centralUrl) { - this.centralUrl = centralUrl; - } - - public String getAssetId() { - return assetId; - } - - public void setAssetId(String assetId) { - this.assetId = assetId; - } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/PassportConfig.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/PassportConfig.java index 62edb047c..6e844c1ee 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/PassportConfig.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/PassportConfig.java @@ -28,19 +28,101 @@ import java.util.List; +/** + * This class consists exclusively to define the attributes and methods needed for the Passport configuration. + **/ @Configuration @ConfigurationProperties(prefix="configuration.passport") public class PassportConfig { - private List versions; + /** ATTRIBUTES **/ + private BatteryPass batteryPass; + private DigitalProductPass digitalProductPass; + /** GETTERS AND SETTERS **/ + public BatteryPass getBatteryPass() { + return batteryPass; + } + public void setBatteryPass(BatteryPass batteryPass) { + this.batteryPass = batteryPass; + } + public DigitalProductPass getDigitalProductPass() { + return digitalProductPass; + } + public void setDigitalProductPass(DigitalProductPass digitalProductPass) { + this.digitalProductPass = digitalProductPass; + } + + /** INNER CLASSES **/ - public List getVersions() { - return this.versions; + /** + * This class consists exclusively to define the attributes and methods needed for the BatterPass configuration. + **/ + public static class BatteryPass extends DigitalProductPass { } - public void setVersions(List versions) { - this.versions = versions; + /** + * This class consists exclusively to define the attributes and methods needed for the DigitalProductPass configuration. + **/ + public static class DigitalProductPass { + + /** ATTRIBUTES **/ + private List versions; + private String semanticId; + private String aspectId; + private String fullSemanticId; + + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") + public DigitalProductPass(List versions, String semanticId, String aspectId) { + this.versions = versions; + this.semanticId = semanticId; + this.aspectId = aspectId; + } + + public DigitalProductPass() { + } + + /** GETTERS AND SETTERS **/ + public List getVersions() { + return this.versions; + } + public void setVersions(List versions) { + this.versions = versions; + } + public String getSemanticId() { + return semanticId; + } + public void setSemanticId(String semanticId) { + this.semanticId = semanticId; + } + @SuppressWarnings("Unused") + public String getAspectId() { + return aspectId; + } + @SuppressWarnings("Unused") + public void setAspectId(String aspectId) { + this.aspectId = aspectId; + } + + /** METHODS **/ + + /** + * Builds the semanticId to search the submodel inside the Digital twin. + * It concatenates the semanticId, the passport version and the aspectId. + *

+ * @param version + * the {@code String} intended passport's version . + * + * @return this {@code String} with the built semanticId. + * + */ + public String getFullSemanticId(String version) { + if (this.fullSemanticId == null) { + this.fullSemanticId = semanticId + ":" + versions.stream().filter(v -> v.equalsIgnoreCase(version)).findFirst().get() + "#" + aspectId; + } + return fullSemanticId; + } } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/ProcessConfig.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/ProcessConfig.java index a2af5300d..e00df7b85 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/ProcessConfig.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/ProcessConfig.java @@ -30,48 +30,41 @@ import java.util.List; +/** + * This class consists exclusively to define the attributes and methods needed for the Process service configuration. + **/ @Configuration @ConfigurationProperties(prefix="configuration.process") public class ProcessConfig { + /** ATTRIBUTES **/ private Boolean store = true; - - private String dir; - private Boolean indent = true; - - private String signToken; + + /** GETTERS AND SETTERS **/ public String getSignToken() { return signToken; } - public void setSignToken(String signToken) { this.signToken = signToken; } - public Boolean getIndent() { return indent; } - public void setIndent(Boolean indent) { this.indent = indent; } - - public Boolean getStore() { return store; } - public void setStore(Boolean store) { this.store = store; } - public String getDir() { return dir; } - public void setDir(String dir) { this.dir = dir; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/ThreadConfig.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/ThreadConfig.java index a6ee2bdf1..9400763d5 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/ThreadConfig.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/ThreadConfig.java @@ -29,10 +29,15 @@ import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +/** + * This class consists exclusively to define the attributes and methods needed for the Thread service configuration. + **/ +@SuppressWarnings("Unused") @Configuration public class ThreadConfig { + @SuppressWarnings("Unused") @Bean public TaskExecutor threadPoolTaskExecutor() { diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/VaultConfig.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/VaultConfig.java index 427e2cd68..42761d99f 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/VaultConfig.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/VaultConfig.java @@ -28,23 +28,23 @@ import java.util.List; +/** + * This class consists exclusively to define the attributes and methods needed for the Vault service configuration. + **/ @Configuration @ConfigurationProperties(prefix="configuration.vault") public class VaultConfig { + /** ATTRIBUTES **/ private String type; - private String file; private String pathSep; - private Boolean prettyPrint; - private String defaultValue; - private Integer indent; - private List attributes; + /** GETTERS AND SETTERS **/ public String getDefaultValue() { return defaultValue; } @@ -100,4 +100,5 @@ public List getAttributes() { public void setAttributes(List attributes) { this.attributes = attributes; } + } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/WebConfig.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/WebConfig.java index aed54ec0e..a759722d7 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/WebConfig.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/config/WebConfig.java @@ -23,21 +23,23 @@ package org.eclipse.tractusx.productpass.config; -import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; -import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; +/** + * This class consists exclusively to define the attributes and methods needed for the Web configuration. + **/ + +@SuppressWarnings("Unused") @Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ConfigException.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ConfigException.java index f48f6bdb4..0854bda31 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ConfigException.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ConfigException.java @@ -23,19 +23,45 @@ package org.eclipse.tractusx.productpass.exceptions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import utils.LogUtil; -public class ConfigException extends RuntimeException{ - public ConfigException(String configuration, String errorMessage) { - super("["+configuration+"] " + errorMessage); - LogUtil.printException(this, "["+configuration+"] " + errorMessage); - } - public ConfigException(String configuration, Exception e, String errorMessage) { - super("["+configuration+"] " + errorMessage+", "+e.getMessage()); - LogUtil.printException(this, "["+configuration+"] " + errorMessage); - } +/** + * This class consists exclusively to define methods to handle and log exceptions caused in the Configuration classes. + **/ +@SuppressWarnings("Unused") +public class ConfigException extends RuntimeException { + + /** + * Logs the given configuration name and error message. + *

+ * @param configurationName + * the {@code String} configurationName name (e.g: the class name where the exception occurred). + * @param errorMessage + * the {@code String} error message. + * + */ + @SuppressWarnings("Unused") + public ConfigException(String configurationName, String errorMessage) { + super("["+configurationName+"] " + errorMessage); + LogUtil.printException(this, "["+configurationName+"] " + errorMessage); + } + + /** + * Logs the given configuration name, the {@code Exception} object and the error message. + *

+ * @param configurationName + * the {@code String} configuration name (e.g: the class name where the exception occurred). + * @param e + * the {@code Exception} object thrown. + * @param errorMessage + * the {@code String} error message. + * + */ + @SuppressWarnings("Unused") + public ConfigException(String configurationName, Exception e, String errorMessage) { + super("["+configurationName+"] " + errorMessage+", "+e.getMessage()); + LogUtil.printException(this, "["+configurationName+"] " + errorMessage); + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ControllerException.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ControllerException.java index 7e5094244..a05ccfc47 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ControllerException.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ControllerException.java @@ -23,18 +23,41 @@ package org.eclipse.tractusx.productpass.exceptions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import utils.LogUtil; +/** + * This class consists exclusively to define methods to handle and log exceptions caused in the Controller classes. + **/ public class ControllerException extends Exception{ - public ControllerException(String controllerName, String errorMessage) { - super("["+controllerName+"] " + errorMessage); - LogUtil.printException(this, "["+controllerName+"] " + errorMessage); - } - public ControllerException(String controllerName, Exception e, String errorMessage) { - super("["+controllerName+"] " + errorMessage+", "+e.getMessage()); - LogUtil.printException(this, "["+controllerName+"] " + errorMessage); - } + + /** + * Logs the given controller name and error message. + *

+ * @param controllerName + * the {@code String} controller name (e.g: the class name where the exception occurred). + * @param errorMessage + * the {@code String} error message. + * + */ + public ControllerException(String controllerName, String errorMessage) { + super("["+controllerName+"] " + errorMessage); + LogUtil.printException(this, "["+controllerName+"] " + errorMessage); + } + + /** + * Logs the given controller name, the {@code Exception} object and the error message. + *

+ * @param controllerName + * the {@code String} controller name (e.g: the class name where the exception occurred). + * @param e + * the {@code Exception} object thrown. + * @param errorMessage + * the {@code String} error message. + * + */ + public ControllerException(String controllerName, Exception e, String errorMessage) { + super("["+controllerName+"] " + errorMessage+", "+e.getMessage()); + LogUtil.printException(this, "["+controllerName+"] " + errorMessage); + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/DataModelException.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/DataModelException.java index b4da28a28..93b1aff17 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/DataModelException.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/DataModelException.java @@ -25,15 +25,40 @@ import utils.LogUtil; + +/** + * This class consists exclusively to define methods to handle and log exceptions caused in the Data Model classes. + **/ public class DataModelException extends RuntimeException{ - public DataModelException(String configuration, String errorMessage) { - super("["+configuration+"] " + errorMessage); - LogUtil.printException(this, "["+configuration+"] " + errorMessage); - } - public DataModelException(String configuration, Exception e, String errorMessage) { - super("["+configuration+"] " + errorMessage+", "+e.getMessage()); - LogUtil.printException(this, "["+configuration+"] " + errorMessage); - } + /** + * Logs the given data model name and error message. + *

+ * @param dataModelName + * the {@code String} data model name (e.g: the class name where the exception occurred). + * @param errorMessage + * the {@code String} error message. + * + */ + public DataModelException(String dataModelName, String errorMessage) { + super("["+dataModelName+"] " + errorMessage); + LogUtil.printException(this, "["+dataModelName+"] " + errorMessage); + } + + /** + * Logs the given data model name, the {@code Exception} object and the error message. + *

+ * @param dataModelName + * the {@code String} data model name (e.g: the class name where the exception occurred). + * @param e + * the {@code Exception} object thrown. + * @param errorMessage + * the {@code String} error message. + * + */ + public DataModelException(String dataModelName, Exception e, String errorMessage) { + super("["+dataModelName+"] " + errorMessage+", "+e.getMessage()); + LogUtil.printException(this, "["+dataModelName+"] " + errorMessage); + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ManagerException.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ManagerException.java index 98b537b4a..0de3ea0ff 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ManagerException.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ManagerException.java @@ -25,15 +25,39 @@ import utils.LogUtil; +/** + * This class consists exclusively to define methods to handle and log exceptions caused in the Manager classes. + **/ public class ManagerException extends RuntimeException{ - public ManagerException(String serviceName, String errorMessage) { - super("["+serviceName+"] " + errorMessage); - LogUtil.printException(this, "["+serviceName+"] " + errorMessage); - } - public ManagerException(String serviceName, Exception e, String errorMessage) { - super("["+serviceName+"] " + errorMessage+", "+e.getMessage()); - LogUtil.printException(this, "["+serviceName+"] " + errorMessage); - } + /** + * Logs the given manager name and error message. + *

+ * @param managerName + * the {@code String} manager name (e.g: the class name where the exception occurred). + * @param errorMessage + * the {@code String} error message. + * + */ + public ManagerException(String managerName, String errorMessage) { + super("["+managerName+"] " + errorMessage); + LogUtil.printException(this, "["+managerName+"] " + errorMessage); + } + + /** + * Logs the given manager name, the {@code Exception} object and the error message. + *

+ * @param managerName + * the {@code String} manager name (e.g: the class name where the exception occurred). + * @param e + * the {@code Exception} object thrown. + * @param errorMessage + * the {@code String} error message. + * + */ + public ManagerException(String managerName, Exception e, String errorMessage) { + super("["+managerName+"] " + errorMessage+", "+e.getMessage()); + LogUtil.printException(this, "["+managerName+"] " + errorMessage); + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ServiceException.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ServiceException.java index 14cbfcdd1..ea57d9df6 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ServiceException.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ServiceException.java @@ -23,19 +23,41 @@ package org.eclipse.tractusx.productpass.exceptions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import utils.LogUtil; +/** + * This class consists exclusively to define methods to handle and log exceptions caused in the Service classes. + **/ public class ServiceException extends RuntimeException{ - public ServiceException(String serviceName, String errorMessage) { - super("["+serviceName+"] " + errorMessage); - LogUtil.printException(this, "["+serviceName+"] " + errorMessage); - } - public ServiceException(String serviceName,Exception e, String errorMessage) { - super("["+serviceName+"] " + errorMessage+", "+e.getMessage()); - LogUtil.printException(this, "["+serviceName+"] " + errorMessage); - } + /** + * Logs the given service name and error message. + *

+ * @param serviceName + * the {@code String} service name (e.g: the class name where the exception occurred). + * @param errorMessage + * the {@code String} error message. + * + */ + public ServiceException(String serviceName, String errorMessage) { + super("["+serviceName+"] " + errorMessage); + LogUtil.printException(this, "["+serviceName+"] " + errorMessage); + } + + /** + * Logs the given service name, the {@code Exception} object and the error message. + *

+ * @param serviceName + * the {@code String} service name (e.g: the class name where the exception occurred). + * @param e + * the {@code Exception} object thrown. + * @param errorMessage + * the {@code String} error message. + * + */ + public ServiceException(String serviceName,Exception e, String errorMessage) { + super("["+serviceName+"] " + errorMessage+", "+e.getMessage()); + LogUtil.printException(this, "["+serviceName+"] " + errorMessage); + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ServiceInitializationException.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ServiceInitializationException.java index 67c851878..88b5e2695 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ServiceInitializationException.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/exceptions/ServiceInitializationException.java @@ -23,19 +23,41 @@ package org.eclipse.tractusx.productpass.exceptions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import utils.LogUtil; +/** + * This class consists exclusively to define methods to handle and log exceptions caused in the Service Initialization classes. + **/ public class ServiceInitializationException extends Exception{ - public ServiceInitializationException(String serviceName, String errorMessage) { - super("["+serviceName+"] " + errorMessage); - LogUtil.printException(this, "["+serviceName+"] " + errorMessage); - } - public ServiceInitializationException(String serviceName, Exception e, String errorMessage) { - super("["+serviceName+"] " + errorMessage+", "+e.getMessage()); - LogUtil.printException(this, "["+serviceName+"] " + errorMessage); - } + /** + * Logs the given service name and error message. + *

+ * @param serviceName + * the {@code String} service name (e.g: the class name where the exception occurred). + * @param errorMessage + * the {@code String} error message. + * + */ + public ServiceInitializationException(String serviceName, String errorMessage) { + super("["+serviceName+"] " + errorMessage); + LogUtil.printException(this, "["+serviceName+"] " + errorMessage); + } + /** + * Logs the given service name, the {@code Exception} object and the error message. + *

+ * @param serviceName + * the {@code String} service name (e.g: the class name where the exception occurred). + * @param e + * the {@code Exception} object thrown. + * @param errorMessage + * the {@code String} error message. + * + */ + @SuppressWarnings("Unused") + public ServiceInitializationException(String serviceName, Exception e, String errorMessage) { + super("["+serviceName+"] " + errorMessage+", "+e.getMessage()); + LogUtil.printException(this, "["+serviceName+"] " + errorMessage); + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/AppController.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/AppController.java index 228d1370a..9a031afc8 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/AppController.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/AppController.java @@ -23,20 +23,24 @@ package org.eclipse.tractusx.productpass.http.controllers; -import com.fasterxml.jackson.databind.JsonNode; import io.swagger.v3.oas.annotations.Hidden; 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.tags.Tag; -import org.apache.juli.logging.Log; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.eclipse.tractusx.productpass.config.DtrConfig; import org.eclipse.tractusx.productpass.config.ProcessConfig; import org.eclipse.tractusx.productpass.exceptions.ControllerException; +import org.eclipse.tractusx.productpass.exceptions.DataModelException; +import org.eclipse.tractusx.productpass.exceptions.ServiceException; import org.eclipse.tractusx.productpass.managers.ProcessManager; import org.eclipse.tractusx.productpass.models.catenax.Dtr; -import org.eclipse.tractusx.productpass.models.dtregistry.*; +import org.eclipse.tractusx.productpass.models.dtregistry.DigitalTwin3; +import org.eclipse.tractusx.productpass.models.dtregistry.EndPoint3; +import org.eclipse.tractusx.productpass.models.dtregistry.SubModel3; import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; import org.eclipse.tractusx.productpass.models.edc.Jwt; import org.eclipse.tractusx.productpass.models.http.Response; @@ -47,47 +51,49 @@ import org.eclipse.tractusx.productpass.models.passports.Passport; import org.eclipse.tractusx.productpass.services.AasService; import org.eclipse.tractusx.productpass.services.DataPlaneService; -import org.sonarsource.scanner.api.internal.shaded.minimaljson.Json; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.*; import utils.*; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -import java.util.List; import java.util.Map; +/** + * This class consists exclusively to define the HTTP methods of the Application's controller. + **/ @RestController @Tag(name = "Public Controller") public class AppController { + /** ATTRIBUTES **/ + @SuppressWarnings("Unused") private @Autowired HttpServletRequest httpRequest; private @Autowired HttpServletResponse httpResponse; - @Autowired HttpUtil httpUtil; @Autowired EdcUtil edcUtil; + @SuppressWarnings("Unused") @Autowired JsonUtil jsonUtil; + @SuppressWarnings("Unused") @Autowired Environment env; + @SuppressWarnings("Unused") @Autowired PassportUtil passportUtil; @Autowired AasService aasService; @Autowired DataPlaneService dataPlaneService; - @Autowired ProcessManager processManager; - @Autowired DtrConfig dtrConfig; + @SuppressWarnings("Unused") private @Autowired ProcessConfig processConfig; + /** METHODS **/ @GetMapping("/") @Hidden // hides this endpoint from api documentation - swagger-ui public Response index() { @@ -95,7 +101,13 @@ public Response index() { return httpUtil.getResponse("Redirect to UI"); } - + /** + * Checks the backend health status. + *

+ * + * @return a {@code Response} HTTP response with the status. + * + */ @GetMapping("/health") @Operation(summary = "Returns the backend health status", responses = { @ApiResponse(description = "Gets the application health", responseCode = "200", content = @Content(mediaType = "application/json", @@ -110,6 +122,17 @@ public Response health() { return response; } + /** + * HTTP POST method to get the Digital Twin for the given processId and endpointId in the URL. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param endpointId + * the {@code String} id of the endpoint. + * + * @return this {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/endpoint/{processId}/{endpointId}", method = RequestMethod.POST) @Operation(summary = "Receives the EDR for the EDC Consumer and queries for the dDTR") public Response getDigitalTwin(@RequestBody Object body, @PathVariable String processId, @PathVariable String endpointId) { @@ -198,6 +221,18 @@ public Response getDigitalTwin(@RequestBody Object body, @PathVariable String pr return httpUtil.buildResponse(httpUtil.getResponse("ok"), httpResponse); } + /** + * Gets the {@code DataPlaneEndpoint} data from the given body of the HTTP request. + *

+ * @param body + * the {@code Object} body from the HTTP request. + * + * @return the {@code DataPlaneEndpoint} object. + * + * @throws ControllerException + * if the unable to get the data plane endpoint. + * + */ public DataPlaneEndpoint getEndpointData(Object body) throws ControllerException { DataPlaneEndpoint endpointData = edcUtil.parseDataPlaneEndpoint(body); if (endpointData == null) { @@ -223,6 +258,15 @@ public DataPlaneEndpoint getEndpointData(Object body) throws ControllerException return endpointData; } + /** + * HTTP POST method to get the Passport for the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return this {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/endpoint/{processId}", method = RequestMethod.POST) @Operation(summary = "Receives the EDR from the EDC Consumer and get the passport json") public Response endpoint(@RequestBody Object body, @PathVariable String processId) { diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/api/ApiController.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/api/ApiController.java index 9ce588e3e..ea59c2aac 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/api/ApiController.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/api/ApiController.java @@ -30,20 +30,17 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; -import org.bouncycastle.pqc.crypto.lms.LMOtsParameters; import org.eclipse.tractusx.productpass.config.PassportConfig; -import org.eclipse.tractusx.productpass.exceptions.ControllerException; import org.eclipse.tractusx.productpass.managers.ProcessManager; -import org.eclipse.tractusx.productpass.models.dtregistry.DigitalTwin; -import org.eclipse.tractusx.productpass.models.dtregistry.SubModel; import org.eclipse.tractusx.productpass.models.http.Response; import org.eclipse.tractusx.productpass.models.http.requests.TokenRequest; -import org.eclipse.tractusx.productpass.models.http.responses.IdResponse; import org.eclipse.tractusx.productpass.models.manager.History; import org.eclipse.tractusx.productpass.models.manager.Process; import org.eclipse.tractusx.productpass.models.manager.Status; -import org.eclipse.tractusx.productpass.models.negotiation.*; +import org.eclipse.tractusx.productpass.models.negotiation.Dataset; import org.eclipse.tractusx.productpass.models.passports.Passport; import org.eclipse.tractusx.productpass.models.passports.PassportResponse; import org.eclipse.tractusx.productpass.models.passports.PassportV3; @@ -52,23 +49,27 @@ import org.eclipse.tractusx.productpass.services.DataTransferService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.web.bind.annotation.*; -import utils.*; - -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import utils.HttpUtil; +import utils.JsonUtil; -import javax.xml.crypto.Data; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; + +/** + * This class consists exclusively to define the HTTP methods needed for the API controller. + **/ @RestController @RequestMapping("/api") @Tag(name = "API Controller") @SecurityRequirement(name = "BearerAuthentication") public class ApiController { + + /** ATTRIBUTES **/ private @Autowired HttpServletRequest httpRequest; private @Autowired HttpServletResponse httpResponse; private @Autowired DataTransferService dataService; @@ -78,9 +79,10 @@ public class ApiController { private @Autowired PassportConfig passportConfig; private @Autowired HttpUtil httpUtil; private @Autowired JsonUtil jsonUtil; - private @Autowired ProcessManager processManager; + /** METHODS **/ + @RequestMapping(value = "/api/*", method = RequestMethod.GET) @Hidden // hide this endpoint from api documentation - swagger-ui @@ -89,6 +91,15 @@ Response index() throws Exception { return httpUtil.getResponse("Redirect to UI"); } + /** + * HTTP POST method to retrieve the Passport. + *

+ * @param tokenRequestBody + * the {@code TokenRequest} object with the processId, contractId and the authentication token. + * + * @return this {@code Response} HTTP response with status. + * + */ @RequestMapping(value = "/passport", method = {RequestMethod.POST}) @Operation(summary = "Returns versioned product passport by id", responses = { @ApiResponse(description = "Default Response Structure", content = @Content(mediaType = "application/json", @@ -171,8 +182,13 @@ public Response getPassport(@Valid @RequestBody TokenRequest tokenRequestBody) { return httpUtil.buildResponse(response, httpResponse); } + Passport passport; + if (process.getIsDigitalProductPass()) { + passport = processManager.loadDigitalProductPassport(processId); + } else { + passport = processManager.loadPassport(processId); + } - PassportV3 passport = processManager.loadPassport(processId); if (passport == null) { response = httpUtil.getNotFound("Failed to load passport!"); diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractController.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractController.java index f92f03ad6..f0de061da 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractController.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractController.java @@ -33,15 +33,12 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; -import org.checkerframework.checker.units.qual.A; import org.eclipse.tractusx.productpass.config.DiscoveryConfig; import org.eclipse.tractusx.productpass.config.DtrConfig; import org.eclipse.tractusx.productpass.config.PassportConfig; import org.eclipse.tractusx.productpass.config.ProcessConfig; import org.eclipse.tractusx.productpass.exceptions.ControllerException; -import org.eclipse.tractusx.productpass.exceptions.DataModelException; import org.eclipse.tractusx.productpass.managers.DtrSearchManager; -import org.eclipse.tractusx.productpass.managers.ProcessDataModel; import org.eclipse.tractusx.productpass.managers.ProcessManager; import org.eclipse.tractusx.productpass.models.catenax.BpnDiscovery; import org.eclipse.tractusx.productpass.models.catenax.Dtr; @@ -49,8 +46,8 @@ import org.eclipse.tractusx.productpass.models.edc.AssetSearch; import org.eclipse.tractusx.productpass.models.http.Response; import org.eclipse.tractusx.productpass.models.http.requests.DiscoverySearch; -import org.eclipse.tractusx.productpass.models.http.requests.TokenRequest; import org.eclipse.tractusx.productpass.models.http.requests.Search; +import org.eclipse.tractusx.productpass.models.http.requests.TokenRequest; import org.eclipse.tractusx.productpass.models.manager.History; import org.eclipse.tractusx.productpass.models.manager.Process; import org.eclipse.tractusx.productpass.models.manager.SearchStatus; @@ -60,17 +57,25 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.*; -import utils.*; +import utils.DateTimeUtil; +import utils.HttpUtil; +import utils.JsonUtil; +import utils.LogUtil; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +/** + * This class consists exclusively to define the HTTP methods needed for the Contract negotiation. + **/ @RestController @RequestMapping("/api/contract") @Tag(name = "Contract Controller") @SecurityRequirement(name = "BearerAuthentication") public class ContractController { + + /** ATTRIBUTES **/ private @Autowired HttpServletRequest httpRequest; private @Autowired HttpServletResponse httpResponse; private @Autowired DataTransferService dataService; @@ -86,15 +91,23 @@ public class ContractController { @Autowired DtrSearchManager dtrSearchManager; private @Autowired ProcessConfig processConfig; - @Autowired CatenaXService catenaXService; - @Autowired HttpUtil httpUtil; private @Autowired JsonUtil jsonUtil; - + /** METHODS **/ + + /** + * HTTP POST method to create a new Process. + *

+ * @param searchBody + * the {@code DiscoverySearch} body from the HTTP request with the partInstanceId. + * + * @return this {@code Response} HTTP response with the processId of the new Process created. + * + */ @RequestMapping(value = "/create", method = RequestMethod.POST) @Operation(summary = "Creates a process and checks for the viability of the data retrieval") public Response create(@Valid @RequestBody DiscoverySearch searchBody) { @@ -203,7 +216,15 @@ public Response create(@Valid @RequestBody DiscoverySearch searchBody) { } } - + /** + * HTTP POST method to search the passport of an asset. + *

+ * @param searchBody + * the {@code DiscoverySearch} body from the HTTP request with the partInstanceId, passport version and the processId. + * + * @return this {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/search", method = RequestMethod.POST) @Operation(summary = "Searches for a passport with the following id", responses = { @ApiResponse(description = "Default Response Structure", content = @Content(mediaType = "application/json", @@ -224,7 +245,19 @@ public Response search(@Valid @RequestBody Search searchBody) { return httpUtil.buildResponse(response, httpResponse); } - List versions = passportConfig.getVersions(); + List versions; + boolean isDigitalProductPass; + if (searchBody.getIdShort().equalsIgnoreCase("digitalProductPass")) { + versions = passportConfig.getDigitalProductPass().getVersions(); + searchBody.setSemanticId(passportConfig.getDigitalProductPass().getFullSemanticId(versions.get(0))); + LogUtil.printWarning("SEMANTID ID: " + passportConfig.getDigitalProductPass().getFullSemanticId(versions.get(0))); + isDigitalProductPass = true; + } else { + versions = passportConfig.getBatteryPass().getVersions(); + searchBody.setSemanticId(passportConfig.getBatteryPass().getFullSemanticId(versions.get(0))); + isDigitalProductPass = false; + } + // Initialize variables // Check if version is available if (!versions.contains(searchBody.getVersion())) { @@ -250,6 +283,7 @@ public Response search(@Valid @RequestBody Search searchBody) { return httpUtil.buildResponse(response, httpResponse); } process = processManager.createProcess(processId, httpRequest); + process.setIsDigitalProductPass(isDigitalProductPass); Status status = processManager.getStatus(processId); if (status == null) { response = httpUtil.getBadRequest("The status is not available!"); @@ -322,6 +356,15 @@ public Response search(@Valid @RequestBody Search searchBody) { } } + /** + * HTTP GET method to get the Process status for the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return this {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/status/{processId}", method = RequestMethod.GET) @Operation(summary = "Get status from process") public Response status(@PathVariable String processId) { @@ -349,7 +392,15 @@ public Response status(@PathVariable String processId) { } } - + /** + * HTTP POST method to cancel a Process. + *

+ * @param tokenRequestBody + * the {@code TokenRequest} object with the processId, contractId and the authentication token. + * + * @return this {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/cancel", method = RequestMethod.POST) @Operation(summary = "Cancel the negotiation") public Response cancel(@Valid @RequestBody TokenRequest tokenRequestBody) { @@ -446,6 +497,15 @@ public Response cancel(@Valid @RequestBody TokenRequest tokenRequestBody) { } + /** + * HTTP POST method to sign a Contract retrieved from provider and start the negotiation. + *

+ * @param tokenRequestBody + * the {@code TokenRequest} object with the processId, contractId and the authentication token. + * + * @return this {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/sign", method = RequestMethod.POST) @Operation(summary = "Sign contract retrieved from provider and start negotiation") public Response sign(@Valid @RequestBody TokenRequest tokenRequestBody) { @@ -555,7 +615,15 @@ public Response sign(@Valid @RequestBody TokenRequest tokenRequestBody) { } } - + /** + * HTTP POST method to decline a Passport negotiation. + *

+ * @param tokenRequestBody + * the {@code TokenRequest} object with the processId, contractId and the authentication token. + * + * @return this {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/decline", method = RequestMethod.POST) @Operation(summary = "Decline passport negotiation") public Response decline(@Valid @RequestBody TokenRequest tokenRequestBody) { diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/auth/AuthController.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/auth/AuthController.java index 018cf4b45..2b3a2b50b 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/auth/AuthController.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/auth/AuthController.java @@ -30,26 +30,22 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -import org.eclipse.tractusx.productpass.models.auth.Credential; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.eclipse.tractusx.productpass.models.auth.JwtToken; import org.eclipse.tractusx.productpass.models.auth.UserInfo; import org.eclipse.tractusx.productpass.models.http.Response; -import org.eclipse.tractusx.productpass.models.auth.UserCredential; import org.eclipse.tractusx.productpass.services.AuthenticationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.http.HttpHeaders; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; import utils.HttpUtil; -import utils.JsonUtil; - -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import utils.LogUtil; - -import java.util.HashMap; -import java.util.Set; +/** + * This class consists exclusively to define the HTTP methods for authentication purposes. + **/ @RestController @RequestMapping("/auth") @Tag(name = "Auth Controller") @@ -57,13 +53,11 @@ public class AuthController { // [Logic Methods] ------------- // --------------------------------------------------- + /** ATTRIBUTES **/ @Autowired private Environment env; - @Autowired - HttpUtil httpUtil; - private @Autowired HttpServletRequest httpRequest; private @Autowired HttpServletResponse httpResponse; final static String clientIdPath = "keycloak.resource"; @@ -72,12 +66,22 @@ public class AuthController { // [API Services] ---------------------------------------------------------------- /* */ + + /** METHODS **/ @RequestMapping(method = RequestMethod.GET) @Hidden public Response index() throws Exception{ httpUtil.redirect(httpResponse,"/passport"); return httpUtil.getResponse("Redirect to Login"); } + + /** + * The HTTP GET method to request the logout. + *

+ * + * @return a {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/logout", method = RequestMethod.GET) @Hidden public Response logout() throws Exception{ @@ -87,6 +91,14 @@ public Response logout() throws Exception{ response.message = "Logged out successfully!"; return response; } + + /** + * The HTTP GET method to request the login. + *

+ * + * @return a {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/login", method = RequestMethod.GET) @Hidden public Response login() throws Exception{ @@ -95,6 +107,13 @@ public Response login() throws Exception{ return response; } + /** + * The HTTP GET method to check if the user is authenticated. + *

+ * + * @return a {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/check", method = RequestMethod.GET) @Operation(summary = "Checks the user logged in status", responses = { @ApiResponse(description = "Content of Data Field in Response", responseCode = "200", content = @Content(mediaType = "application/json", @@ -105,7 +124,13 @@ public Response check(){ return httpUtil.getResponse(check ? "User Authenticated":"User not Authenticated", check); } - + /** + * The HTTP GET method to request the authentication token. + *

+ * + * @return a {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/token", method = RequestMethod.GET) @Operation(summary = "Returns access token", responses = { @ApiResponse(description = "Default Response Structure", content = @Content(mediaType = "application/json", @@ -123,6 +148,14 @@ public Response getToken(){ response.data = authService.getToken(); return response; } + + /** + * The HTTP POST method to request the user's information related to the authentication token.. + *

+ * + * @return a {@code Response} HTTP response with the status. + * + */ @RequestMapping(value = "/userInfo", method = RequestMethod.POST) @Operation(security = {@SecurityRequirement(name = "Bearer Authorization")}, summary = "Returns user info related to JWT Token", responses = { diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/error/ErrorResponseController.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/error/ErrorResponseController.java index e77a750cd..bc185dab6 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/error/ErrorResponseController.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/controllers/error/ErrorResponseController.java @@ -24,8 +24,8 @@ package org.eclipse.tractusx.productpass.http.controllers.error; import io.swagger.v3.oas.annotations.Hidden; +import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.apache.juli.logging.Log; import org.eclipse.tractusx.productpass.models.http.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.error.ErrorAttributeOptions; @@ -37,21 +37,36 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.ServletWebRequest; import utils.HttpUtil; -import utils.JsonUtil; import utils.LogUtil; -import jakarta.servlet.http.HttpServletRequest; import java.util.Map; +/** + * This class consists exclusively to define the HTTP methods to handle errors. + **/ @Controller @Hidden // hide this endpoint from api documentation - swagger-ui public class ErrorResponseController implements ErrorController { + /** ATTRIBUTES **/ @Autowired private ErrorAttributes errorAttributes; - @Autowired HttpUtil httpUtil; + + /** METHODS **/ + + /** + * HTTP POST method to get the Digital Twin for the given processId and endpointId in the URL. + *

+ * @param httpRequest + * the HTTP request. + * @param httpResponse + * the HTTP response. + * + * @return this {@code Response} HTTP response with the error message. + * + */ @RequestMapping(value="/error", method = {RequestMethod.GET}) @ResponseBody public Response handleError(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/middleware/BaseInterceptor.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/middleware/BaseInterceptor.java index 1a22cee0c..150b506a3 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/middleware/BaseInterceptor.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/middleware/BaseInterceptor.java @@ -39,6 +39,8 @@ public class BaseInterceptor implements HandlerInterceptor { @Autowired HttpUtil httpUtil; + + @SuppressWarnings("Unused") @Override public boolean preHandle( HttpServletRequest httpRequest, HttpServletResponse httpResponse, Object handler) throws Exception { @@ -48,6 +50,8 @@ public boolean preHandle( } return true; } + + @SuppressWarnings("Unused") @Override public void postHandle( @@ -56,7 +60,7 @@ public void postHandle( //[NOTE]: Post Handle not implemented! } - + @SuppressWarnings("Unused") @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception{ diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/middleware/InterceptorConfig.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/middleware/InterceptorConfig.java index bc0e21be7..29456fd85 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/middleware/InterceptorConfig.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/http/middleware/InterceptorConfig.java @@ -28,11 +28,13 @@ import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +@SuppressWarnings("Unused") @Component public class InterceptorConfig implements WebMvcConfigurer { @Autowired BaseInterceptor baseInterceptor; + @SuppressWarnings("Unused") @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(baseInterceptor); diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/interfaces/ServiceInitializationInterface.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/interfaces/ServiceInitializationInterface.java index 03514590a..647599f6b 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/interfaces/ServiceInitializationInterface.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/interfaces/ServiceInitializationInterface.java @@ -24,10 +24,12 @@ package org.eclipse.tractusx.productpass.interfaces; import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.springframework.core.env.Environment; import java.util.List; +/** + * This interface consists exclusively to define the needed common methods to a Service class. + **/ @org.springframework.stereotype.Service public interface ServiceInitializationInterface { List getEmptyVariables(); // Return the name of the variables that are not initialized diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/listeners/AppListener.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/listeners/AppListener.java index 5cd38fbbd..8d9fabe5d 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/listeners/AppListener.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/listeners/AppListener.java @@ -23,26 +23,14 @@ package org.eclipse.tractusx.productpass.listeners; -import com.fasterxml.jackson.core.type.TypeReference; -import jakarta.servlet.http.HttpServletRequest; -import org.eclipse.tractusx.productpass.Application; -import org.eclipse.tractusx.productpass.exceptions.DataModelException; -import org.eclipse.tractusx.productpass.http.controllers.api.ContractController; -import org.eclipse.tractusx.productpass.config.DiscoveryConfig; import org.eclipse.tractusx.productpass.config.DtrConfig; -import org.eclipse.tractusx.productpass.managers.ProcessDataModel; -import org.eclipse.tractusx.productpass.managers.ProcessManager; import org.eclipse.tractusx.productpass.models.auth.JwtToken; -import org.eclipse.tractusx.productpass.models.catenax.Dtr; +import org.eclipse.tractusx.productpass.models.catenax.Discovery; import org.eclipse.tractusx.productpass.models.edc.Jwt; -import org.eclipse.tractusx.productpass.models.http.requests.Search; import org.eclipse.tractusx.productpass.services.AuthenticationService; +import org.eclipse.tractusx.productpass.services.CatenaXService; import org.eclipse.tractusx.productpass.services.DataTransferService; import org.eclipse.tractusx.productpass.services.VaultService; -import org.eclipse.tractusx.productpass.models.catenax.BpnDiscovery; -import org.eclipse.tractusx.productpass.models.catenax.Discovery; -import org.eclipse.tractusx.productpass.models.catenax.EdcDiscoveryEndpoint; -import org.eclipse.tractusx.productpass.services.CatenaXService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.boot.context.event.ApplicationStartedEvent; @@ -54,39 +42,33 @@ import org.springframework.context.event.EventListener; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; import utils.HttpUtil; -import utils.JsonUtil; import utils.LogUtil; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; +/** + * This class consists exclusively of methods to operate on the Application's Event listeners. + * + *

The methods defined here are the event listeners needed to run the application. + * + */ @Component @Configuration @EnableConfigurationProperties @ConfigurationProperties public class AppListener { - @Autowired - BuildProperties buildProperties; - @Autowired - JsonUtil jsonUtil; + /** ATTRIBUTES **/ @Autowired - DiscoveryConfig discoveryConfig; + BuildProperties buildProperties; @Autowired CatenaXService catenaXService; - @Autowired DtrConfig dtrConfig; @Autowired AuthenticationService authService; @Autowired VaultService vaultService; - @Autowired HttpUtil httpUtil; @Autowired @@ -94,6 +76,7 @@ public class AppListener { @Autowired DataTransferService dataTransferService; + /** METHODS **/ @EventListener(ApplicationStartedEvent.class) public void started() { Boolean preChecks = env.getProperty("configuration.security.check.enabled", Boolean.class, true); @@ -188,4 +171,4 @@ public void onStartUp() { } // Store the process manager in memory - } \ No newline at end of file + } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/DtrSearchManager.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/DtrSearchManager.java index 65da2fa5a..a49b584b9 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/DtrSearchManager.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/DtrSearchManager.java @@ -29,12 +29,13 @@ import org.eclipse.tractusx.productpass.config.DtrConfig; import org.eclipse.tractusx.productpass.exceptions.DataModelException; import org.eclipse.tractusx.productpass.exceptions.ManagerException; -import org.eclipse.tractusx.productpass.models.negotiation.Negotiation; +import org.eclipse.tractusx.productpass.exceptions.ServiceException; import org.eclipse.tractusx.productpass.models.catenax.Dtr; import org.eclipse.tractusx.productpass.models.catenax.EdcDiscoveryEndpoint; import org.eclipse.tractusx.productpass.models.http.responses.IdResponse; import org.eclipse.tractusx.productpass.models.negotiation.Catalog; import org.eclipse.tractusx.productpass.models.negotiation.Dataset; +import org.eclipse.tractusx.productpass.models.negotiation.Negotiation; import org.eclipse.tractusx.productpass.models.negotiation.Offer; import org.eclipse.tractusx.productpass.services.DataTransferService; import org.springframework.beans.factory.annotation.Autowired; @@ -49,12 +50,19 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; +/** + * This class consists exclusively of methods to operate on executing the DTR search. + * + *

The methods defined here are intended to do every needed operations in order to be able to get and save the DTRs. + * + */ @Component public class DtrSearchManager { + + /** ATTRIBUTES **/ private DataTransferService dataTransferService; private FileUtil fileUtil; private JsonUtil jsonUtil; - private ProcessManager processManager; private DtrConfig dtrConfig; private ConcurrentHashMap> dtrDataModel; @@ -63,17 +71,7 @@ public class DtrSearchManager { private final long negotiationTimeoutSeconds; private final String fileName = "dtrDataModel.json"; private String dtrDataModelFilePath; - - public State getState() { - return state; - } - - public void setState(State state) { - this.state = state; - } - private State state; - public enum State { Stopped, Running, @@ -81,6 +79,7 @@ public enum State { Finished } + /** CONSTRUCTOR(S) **/ @Autowired public DtrSearchManager(FileUtil fileUtil, JsonUtil jsonUtil, DataTransferService dataTransferService, DtrConfig dtrConfig, ProcessManager processManager) { this.catalogsCache = new ConcurrentHashMap<>(); @@ -97,6 +96,33 @@ public DtrSearchManager(FileUtil fileUtil, JsonUtil jsonUtil, DataTransferServic } + /** GETTERS AND SETTERS **/ + public State getState() { + return state; + } + public void setState(State state) { + this.state = state; + } + + /** METHODS **/ + + /** + * It's a Thread level method that implements the Runnable interface and starts the process of searching the DTRs with + * the given EDC endpoint for a given processId. + *

+ * @param edcEndpoints + * the {@code List} of EDC endpoints to search. + * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code Runnable} object to be used by a calling thread. + * + * @throws DataModelException + * if unable to get and process the DTRs. + * @throws RuntimeException + * if there's an unexpected thread interruption. + * + */ public Runnable startProcess(List edcEndpoints, String processId) { return new Runnable() { @Override @@ -180,6 +206,13 @@ public void run() { }; } + /** + * Creates the DTR Data Model file where the DTRs are stored. + *

+ * + * @return a {@code String} path to the file created. + * + */ public String createDataModelFile() { Map dataModel = Map.of(); // If path exists try to @@ -199,14 +232,36 @@ public String createDataModelFile() { return jsonUtil.toJsonFile(this.getDataModelPath(), dataModel, true); } + /** + * Gets the path to the DTR Data Model file. + *

+ * + * @return a {@code String} path to the DTR Data Model file. + * + */ public String getDataModelPath() { return Path.of(this.getDataModelDir(), this.fileName).toAbsolutePath().toString(); } + /** + * Gets the path to the DTR Data Model directory. + *

+ * + * @return a {@code String} path to the DTR Data Model directory. + * + */ public String getDataModelDir() { return fileUtil.getTmpDir(); } + /** + * It's a Thread level method that implements the Runnable interface and searches for the Digital Twin Catalog for + * a given URL connection. It doesn't return the Catalogs found, it fills the catalogs cache of this class object. + *

+ * @param connectionUrl + * the {@code String} URL connection of the Digital Twin. + * + */ private Runnable searchDigitalTwinCatalogExecutor(String connectionUrl) { return new Runnable() { @Override @@ -225,6 +280,17 @@ public void run() { }; } + /** + * Adds the found DTR to the DTR Data Model map object at the given BPN number entry. + *

+ * @param bpn + * the {@code String} bpn number. + * @param dtr + * the {@code DTR} object to add. + * + * @return this {@code DtrSearchManager} object. + * + */ public DtrSearchManager addConnectionToBpnEntry(String bpn, Dtr dtr) { if (!(bpn.isEmpty() || bpn.isBlank() || dtr.getEndpoint().isEmpty() || dtr.getEndpoint().isBlank())) { if (this.dtrDataModel.contains(bpn)) { @@ -237,18 +303,13 @@ public DtrSearchManager addConnectionToBpnEntry(String bpn, Dtr dtr) { return this; } - /*public ProcessDtrDataModel addConnectionsToBpnEntry (String bpn, List connectionEdcEndpoints) { - if (!(bpn.isEmpty() || bpn.isBlank()) || checkConnectionEdcEndpoints(connectionEdcEndpoints) ) { - if (this.dtrDataModel.contains(bpn)) { - this.dtrDataModel.get(bpn).addAll(connectionEdcEndpoints); - this.dtrDataModel.get(bpn).stream().distinct().collect(Collectors.toList()); - } else { - this.dtrDataModel.put(bpn, connectionEdcEndpoints); - } - } - return this; - }*/ - + /** + * Loads the thread safe DTR Data Model from the storage file. + *

+ * + * @return the {@code CocurrentHashMap>} object with the DTR Data Model values. + * + */ public ConcurrentHashMap> loadDataModel() { try { String path = this.getDataModelPath(); @@ -261,10 +322,18 @@ public ConcurrentHashMap> loadDataModel() { } } + /** + * Gets the thread safe DTR Data Model cached in this class object. + *

+ * + * @return the {@code CocurrentHashMap>} object with the DTR Data Model values. + * + */ public ConcurrentHashMap> getDtrDataModel() { return dtrDataModel; } + @SuppressWarnings("Unused") private boolean checkConnectionEdcEndpoints(List connectionEdcEndpoints) { AtomicInteger count = new AtomicInteger(0); int connectionsSize = connectionEdcEndpoints.size(); @@ -279,13 +348,32 @@ private boolean checkConnectionEdcEndpoints(List connectionEdcEndpoints) return count.get() == connectionsSize; } + /** + * It's a Thread level method that implements the Runnable interface. It creates the DTR and saves it in the DTR Data Model + * for a given BPN number and an URL connection into a process with the given process id. + *

+ * @param dataset + * the {@code Dataset} data for the contract offer. + * @param bpn + * the {@code String} bpn number. + * @param connectionUrl + * the {@code String} URL connection of the Digital Twin. + * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code Runnable} object to be used by a calling thread. + * + * @throws ManagerException + * if unable to do the contract negotiation for the DTR. + * + */ private Runnable createAndSaveDtr(Dataset dataset, String bpn, String connectionUrl, String processId) { return new Runnable() { @Override public void run() { try { Offer offer = dataTransferService.buildOffer(dataset, 0); - IdResponse negotiationResponse = dataTransferService.doContractNegotiations(offer, bpn, CatenaXUtil.buildDataEndpoint(connectionUrl)); + IdResponse negotiationResponse = dataTransferService.doContractNegotiation(offer, bpn, CatenaXUtil.buildDataEndpoint(connectionUrl)); if (negotiationResponse == null) { return; } @@ -310,6 +398,13 @@ public void run() { } + /** + * Saves the cached DTR Data Model of this class object to the storage file. + *

+ * + * @return true if the cached DTR Data Model was successfully saved, false otherwise. + * + */ public boolean saveDtrDataModel() { if(fileUtil.pathExists(this.dtrDataModelFilePath)) { this.createDataModelFile(); @@ -319,6 +414,13 @@ public boolean saveDtrDataModel() { return filePath != null; } + /** + * Loads the thread safe DTR Data Model from the storage file. + *

+ * + * @return the {@code CocurrentHashMap>} object with the DTR Data Model values. + * + */ private ConcurrentHashMap> loadDtrDataModel() { try { if(fileUtil.pathExists(this.dtrDataModelFilePath)) { diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessDataModel.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessDataModel.java index 03176086d..7ed4ed750 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessDataModel.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessDataModel.java @@ -26,28 +26,72 @@ package org.eclipse.tractusx.productpass.managers; import org.eclipse.tractusx.productpass.exceptions.DataModelException; -import org.eclipse.tractusx.productpass.exceptions.ManagerException; import org.eclipse.tractusx.productpass.models.manager.Process; import org.springframework.stereotype.Component; import utils.DateTimeUtil; -import utils.LogUtil; import utils.ThreadUtil; import java.util.HashMap; import java.util.Map; +/** + * This class consists exclusively of methods to operate on the Process's Data Model. + * + *

The methods defined here are intended to do every needed operations in order to be able to add, start or get a Process, check if + * a specific Process exists or to get and set the Process's state. + * + */ @Component public class ProcessDataModel { + /** ATTRIBUTES **/ public Map dataModel; + /** CONSTRUCTOR(S) **/ public ProcessDataModel() { this.dataModel = new HashMap<>(); } + + /** GETTERS AND SETTERS **/ + @SuppressWarnings("Unused") + public Map getDataModel() { + return dataModel; + } + @SuppressWarnings("Unused") + public void setDataModel(Map dataModel) { + this.dataModel = dataModel; + } + + /** METHODS **/ + + /** + * Adds the given {@code Process} object into the Process Data Model. + *

+ * @param process + * the {@code Process} object to add. + * + * @return this {@code ProcessDataModel} object. + * + */ public ProcessDataModel addProcess(Process process){ this.dataModel.put(process.id, process); return this; } + + /** + * Sets the state of the Process with the given process id with the given state value. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param state + * the {@code String} value of the new process's state (e.g: "FAILED", "NEGOTIATED", "COMPLETED"). + * + * @return this {@code ProcessDataModel} object. + * + * @throws DataModelException + * if the process doesn't exist. + * + */ public ProcessDataModel setState(String processId, String state){ Process process = this.dataModel.getOrDefault(processId, null); if(process == null){ @@ -58,9 +102,35 @@ public ProcessDataModel setState(String processId, String state){ this.dataModel.put(processId, process); return this; } + + /** + * Gets the state of the Process with the given process id. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return this {@code String} state's value. + * + * + */ public String getState(String processId){ return this.dataModel.get(processId).getState(); } + + /** + * Starts the Process with the given process id with the given thread level task. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param processRunnable + * the {@code Runnable} task to start in the process. + * + * @return this {@code ProcessDataModel} object. + * + * @throws DataModelException + * if unable to start the process. + * + */ public ProcessDataModel startProcess(String processId, Runnable processRunnable){ try { Process process = this.dataModel.getOrDefault(processId, null); @@ -77,18 +147,32 @@ public ProcessDataModel startProcess(String processId, Runnable processRunnable) } } + /** + * Gets the Process with the given process id. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return the {@code Process} object found, if exists. + * + * + */ public Process getProcess(String processId){ return this.dataModel.getOrDefault(processId, null); } + /** + * Checks if a Process with the given process id exists in the Process Data Model. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return true if the process exists, false otherwise. + * + * + */ public Boolean processExists(String processId){ return this.dataModel.containsKey(processId); } - public Map getDataModel() { - return dataModel; - } - public void setDataModel(Map dataModel) { - this.dataModel = dataModel; - } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessManager.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessManager.java index 07e3c5e98..7661feddf 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessManager.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessManager.java @@ -28,6 +28,7 @@ import jakarta.servlet.http.HttpServletRequest; import org.eclipse.tractusx.productpass.config.ProcessConfig; import org.eclipse.tractusx.productpass.exceptions.ManagerException; +import org.eclipse.tractusx.productpass.exceptions.ServiceException; import org.eclipse.tractusx.productpass.models.catenax.Dtr; import org.eclipse.tractusx.productpass.models.dtregistry.DigitalTwin; import org.eclipse.tractusx.productpass.models.dtregistry.DigitalTwin3; @@ -40,6 +41,7 @@ import org.eclipse.tractusx.productpass.models.manager.SearchStatus; import org.eclipse.tractusx.productpass.models.manager.Status; import org.eclipse.tractusx.productpass.models.negotiation.*; +import org.eclipse.tractusx.productpass.models.passports.DigitalProductPassport; import org.eclipse.tractusx.productpass.models.passports.Passport; import org.eclipse.tractusx.productpass.models.passports.PassportV3; import org.springframework.beans.factory.annotation.Autowired; @@ -51,12 +53,18 @@ import java.util.List; import java.util.Map; +/** + * This class consists exclusively of methods to operate on managing the Processes. + * + *

The methods defined here are intended to do every needed operations to run the processes. + * + */ @Component public class ProcessManager { + /** ATTRIBUTES **/ private HttpUtil httpUtil; private JsonUtil jsonUtil; - private FileUtil fileUtil; private @Autowired ProcessConfig processConfig; private @Autowired Environment env; @@ -64,13 +72,12 @@ public class ProcessManager { private final String datasetFileName = "dataset"; private final String negotiationFileName = "negotiation"; private final String transferFileName = "transfer"; - private final String processDataModelName = "processDataModel"; - private final String digitalTwinFileName = "digitalTwin"; private final String passportFileName = "passport"; private final String searchFileName = "search"; + /** CONSTRUCTOR(S) **/ @Autowired public ProcessManager(HttpUtil httpUtil, JsonUtil jsonUtil, FileUtil fileUtil, ProcessConfig processConfig) { this.httpUtil = httpUtil; @@ -79,6 +86,19 @@ public ProcessManager(HttpUtil httpUtil, JsonUtil jsonUtil, FileUtil fileUtil, P this.processConfig = processConfig; } + /** METHODS **/ + + /** + * Loads the process data model from the HTTP session, if exists, otherwise creates it. + *

+ * @param httpRequest + * the HTTP request. + * + * @return a {@code ProcessDataModel} object with the loaded data or empty if created. + * + * @throws ManagerException + * if unable to load or create the process data model. + */ public ProcessDataModel loadDataModel(HttpServletRequest httpRequest) { try { ProcessDataModel processDataModel = (ProcessDataModel) httpUtil.getSessionValue(httpRequest, this.processDataModelName); @@ -93,6 +113,18 @@ public ProcessDataModel loadDataModel(HttpServletRequest httpRequest) { } } + /** + * Saves the process data model into a given HTTP session. + *

+ * @param httpRequest + * the HTTP request. + * @param dataModel + * the {@code ProcessDataModel} object to save into the HTTP session. + * + * @throws ManagerException + * if unable to save the process data model. + */ + @SuppressWarnings("Unused") public void saveDataModel(HttpServletRequest httpRequest, ProcessDataModel dataModel) { try { httpUtil.setSessionValue(httpRequest, this.processDataModelName, dataModel); @@ -101,6 +133,19 @@ public void saveDataModel(HttpServletRequest httpRequest, ProcessDataModel dataM } } + /** + * Gets the Process from an HTTP session with a given processId. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code Process} object, if exists. + * + * @throws ManagerException + * if unable to get the process. + */ public Process getProcess(HttpServletRequest httpRequest, String processId) { try { // Getting a process @@ -111,15 +156,49 @@ public Process getProcess(HttpServletRequest httpRequest, String processId) { } } - + /** + * Generates a SHA256 status token for a given contractId and status. + *

+ * @param status + * the {@code Status} object of the process. + * @param contractId + * the {@code String} identification of the contract negotiation. + * + * @return a {@code String} with the generated token. + * + */ public String generateStatusToken(Status status, String contractId) { return CrypUtil.sha256("signToken=[" + status.getCreated() + "|" + status.id + "|" + contractId + "|" + processConfig.getSignToken() + "]"); // Add extra level of security, that just the user that has this token can sign } + /** + * Generates a SHA256 status token for a given contractId and process. + *

+ * @param process + * the {@code Process} object. + * @param contractId + * the {@code String} identification of the contract negotiation. + * + * @return a {@code String} with the generated token. + * + */ public String generateToken(Process process, String contractId) { return CrypUtil.sha256("signToken=[" + process.getCreated() + "|" + process.id + "|" + contractId + "|" + processConfig.getSignToken() + "]"); // Add extra level of security, that just the user that has this token can sign } + /** + * Checks if a Process with the given processId in the given HTTP session exists. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * + * @return true if the process exists, false otherwise. + * + * @throws ManagerException + * if unable to check if the process exists. + */ public Boolean checkProcess(HttpServletRequest httpRequest, String processId) { try { // Getting a process @@ -129,6 +208,18 @@ public Boolean checkProcess(HttpServletRequest httpRequest, String processId) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to check if process exists [" + processId + "]"); } } + + /** + * Checks if a Process with the given processId exists in the storage file. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return true if the process exists, false otherwise. + * + * @throws ManagerException + * if unable to check if the process exists. + */ public Boolean checkProcess(String processId) { try { // Getting a process @@ -139,9 +230,21 @@ public Boolean checkProcess(String processId) { } } - - - + /** + * Starts the contract negotiation process for a given HTTP session with the given processId and the task to run. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * @param contractNegotiation + * the {@code Runnable} task for the contract negotiation. + * + * @return true if the process exists, false otherwise. + * + * @throws ManagerException + * if unable to start the process. + */ public void startNegotiation(HttpServletRequest httpRequest, String processId, Runnable contractNegotiation) { try { // Start the negotiation @@ -152,6 +255,17 @@ public void startNegotiation(HttpServletRequest httpRequest, String processId, R } } + /** + * Sets the given process into the Process Data Model of the given HTTP session. + *

+ * @param httpRequest + * the HTTP request. + * @param process + * the {@code Process} object to set. + * + * @throws ManagerException + * if unable to set the process. + */ public void setProcess(HttpServletRequest httpRequest, Process process) { try { // Setting and updating a process ProcessDataModel dataModel = this.loadDataModel(httpRequest); @@ -161,6 +275,19 @@ public void setProcess(HttpServletRequest httpRequest, Process process) { } } + /** + * Sets the process state of the process with the given processId in the given HTTP session. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * @param processState + * the {@code String} value of the new process's state (e.g: "FAILED", "NEGOTIATED", "COMPLETED"). + * + * @throws ManagerException + * if unable to set the process state. + */ public void setProcessState(HttpServletRequest httpRequest, String processId, String processState) { try { // Setting and updating a process state ProcessDataModel dataModel = (ProcessDataModel) httpUtil.getSessionValue(httpRequest, this.processDataModelName); @@ -169,6 +296,21 @@ public void setProcessState(HttpServletRequest httpRequest, String processId, St throw new ManagerException(this.getClass().getName(), e, "It was not possible to set process state [" + processState + "] for process [" + processId + "]"); } } + + /** + * Gets the process state of the process with the given processId in the given HTTP session. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code String} with the process state value. + * + * @throws ManagerException + * if unable to get the process state. + */ + @SuppressWarnings("Unused") public String getProcessState(HttpServletRequest httpRequest, String processId) { try { // Setting and updating a process state ProcessDataModel dataModel = (ProcessDataModel) httpUtil.getSessionValue(httpRequest, this.processDataModelName); @@ -177,6 +319,18 @@ public String getProcessState(HttpServletRequest httpRequest, String processId) throw new ManagerException(this.getClass().getName(), e, "It was not possible to get process state for process [" + processId + "]"); } } + + /** + * Gets the directory's path of the process with the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param absolute + * a {@code Boolean} value to specify if the path is to be the absolute path. + * + * @return a {@code String} with the directory's path of the process, the path will be the absolute path, if the boolean parameter is true. + * + */ private String getProcessDir(String processId, Boolean absolute) { String dataDir = fileUtil.getDataDir(); if (absolute) { @@ -186,6 +340,17 @@ private String getProcessDir(String processId, Boolean absolute) { } } + /** + * Gets the temporary directory's path of the process with the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param absolute + * a {@code Boolean} value to specify if the path is to be the absolute path. + * + * @return a {@code String} with the directory's path of the process, the path will be the absolute path, if the boolean parameter is true. + * + */ private String getTmpProcessDir(String processId, Boolean absolute) { String tmpDir = fileUtil.getTmpDir(); if (absolute) { @@ -194,10 +359,31 @@ private String getTmpProcessDir(String processId, Boolean absolute) { return Path.of(tmpDir, processConfig.getDir(), processId).toString(); } } + + /** + * Creates a new process in the given HTTP session. + *

+ * @param httpRequest + * the HTTP request. + * + * @return a {@code Process} object representing the created process. + * + */ public Process createProcess(HttpServletRequest httpRequest) { return this.createProcess(httpRequest, ""); } + /** + * Creates a new process in the given HTTP session and set its status in the file system logs. + *

+ * @param httpRequest + * the HTTP request. + * @param connectorAddress + * the {@code String} URL address the of the connector. + * + * @return a {@code Process} object representing the created process. + * + */ public Process createProcess(HttpServletRequest httpRequest, String connectorAddress) { Long createdTime = DateTimeUtil.getTimestamp(); Process process = new Process(CrypUtil.getUUID(), "CREATED", createdTime); @@ -207,6 +393,17 @@ public Process createProcess(HttpServletRequest httpRequest, String connectorAdd return process; } + /** + * Deletes the temporary process directory with the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return true if the temporary directory was successfully deleted, false otherwise. + * + * @throws ManagerException + * if unable to delete the temporary process directory. + */ public Boolean deleteSearchDir(String processId){ try { String path = this.getTmpProcessDir(processId, false); @@ -219,6 +416,20 @@ public Boolean deleteSearchDir(String processId){ throw new ManagerException(this.getClass().getName(), e, "It was not possible to create/update the search in search status file"); } } + + /** + * Sets the process search status with the given processId with the given {@code Search} object data. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param search + * the {@code Search} object to set. + * + * @return the {@code SearchStatus} object updated. + * + * @throws ManagerException + * if unable to set the search data. + */ public SearchStatus setSearch(String processId, Search search) { try { String path = this.getTmpProcessFilePath(processId, this.searchFileName); @@ -234,6 +445,20 @@ public SearchStatus setSearch(String processId, Search search) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to create/update the search in search status file"); } } + + /** + * Updates the process search status with the given processId with the given {@code Dtr} object data. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param dtr + * the {@code DTR} object data of the Digital Twin Registry. + * + * @return the {@code String} file path where data was storage. + * + * @throws ManagerException + * if unable to set the search data. + */ public String addSearchStatusDtr(String processId, Dtr dtr) { try { String path = this.getTmpProcessFilePath(processId, this.searchFileName); @@ -248,6 +473,16 @@ public String addSearchStatusDtr(String processId, Dtr dtr) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to create/update the search status file"); } } + + /** + * Initiates a new empty process and stores it in the temporary directory. + *

+ * + * @return the {@code String} process identification. + * + * @throws ManagerException + * if unable to initiate the process. + */ public String initProcess() { try { String processId = CrypUtil.getUUID(); @@ -260,7 +495,19 @@ public String initProcess() { } } - + /** + * Creates a new Process with the given processId into the given HTTP session. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param httpRequest + * the HTTP request. + * + * @return a {@code Process} object created. + * + * @throws ManagerException + * if unable to create the process. + */ public Process createProcess(String processId, HttpServletRequest httpRequest) { Long createdTime = DateTimeUtil.getTimestamp(); Process process = new Process(processId, "CREATED", createdTime); @@ -269,6 +516,24 @@ public Process createProcess(String processId, HttpServletRequest httpRequest) { this.newStatusFile(process.id,"", createdTime); // Set the status from the process in file system logs. return process; } + + /** + * Creates a new Process with the given processId into the given HTTP session, + * setting the process with the given BPN number. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * @param bpn + * the {@code String} BPN number. + * + * @return a {@code Process} object created. + * + * @throws ManagerException + * if unable to create the process. + */ + @SuppressWarnings("Unused") public Process createProcess(HttpServletRequest httpRequest, String processId, String bpn) { Long createdTime = DateTimeUtil.getTimestamp(); Process process = new Process(processId, "CREATED", createdTime); @@ -279,6 +544,21 @@ public Process createProcess(HttpServletRequest httpRequest, String processId, S return process; } + /** + * Creates a new Status file for the given processId, setting it with the given connector address and timestamp. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param connectorAddress + * the {@code String} URL address the of the connector. + * @param created + * the {@code Long} timestamp of the creation. + * + * @return a {@code String} file path of the created file. + * + * @throws ManagerException + * if unable to create the status file. + */ public String newStatusFile(String processId, String connectorAddress, Long created){ try { String path = this.getProcessFilePath(processId, this.metaFileName); @@ -296,15 +576,50 @@ public String newStatusFile(String processId, String connectorAddress, Long crea throw new ManagerException(this.getClass().getName(), e, "It was not possible to create the status file"); } } + + /** + * Gets the temporary process file path for a given processId and filename. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param filename + * the {@code String} name of the file without the extension (e.g: ".json"). + * + * @return a {@code String} file path of the temporary process file. + * + */ public String getTmpProcessFilePath(String processId, String filename) { String processDir = this.getTmpProcessDir(processId, false); return Path.of(processDir, filename + ".json").toAbsolutePath().toString(); } + + /** + * Gets the process file path for a given processId and filename. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param filename + * the {@code String} name of the file without the extension (e.g: ".json"). + * + * @return a {@code String} file path of the process file. + * + */ public String getProcessFilePath(String processId, String filename) { String processDir = this.getProcessDir(processId, false); return Path.of(processDir, filename + ".json").toAbsolutePath().toString(); } + /** + * Gets the process status of the process with the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code Status} object with the status information. + * + * @throws ManagerException + * if unable to get the status file. + */ public Status getStatus(String processId) { try { String path = this.getProcessFilePath(processId, this.metaFileName); @@ -314,6 +629,19 @@ public Status getStatus(String processId) { } } + /** + * Sets the BPN number of the process with the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param bpn + * the {@code String} BPN number. + * + * @return a {@code String} file path of the process file. + * + * @throws ManagerException + * if unable to get the status file. + */ public String setBpn(String processId, String bpn) { try { String path = this.getProcessFilePath(processId, this.metaFileName); @@ -331,6 +659,21 @@ public String setBpn(String processId, String bpn) { } } + /** + * Sets the history of the process's status containing the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param historyId + * the {@code String} identification of the process's history entry. + * @param history + * the {@code History} object with updated values. + * + * @return a {@code String} file path of the process status file. + * + * @throws ManagerException + * if unable to update the status file. + */ public String setStatus(String processId, String historyId, History history) { try { String path = this.getProcessFilePath(processId, this.metaFileName); @@ -348,6 +691,21 @@ public String setStatus(String processId, String historyId, History history) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to create/update the status file"); } } + + /** + * Sets the process's status containing the given processId with the given status. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param status + * the {@code String} status to update. + * + * @return a {@code String} file path of the process status file. + * + * @throws ManagerException + * if unable to update the status file. + */ + @SuppressWarnings("Unused") public String setStatus(String processId, String status) { try { String path = this.getProcessFilePath(processId, this.metaFileName); @@ -363,7 +721,23 @@ public String setStatus(String processId, String status) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to create/update the status file"); } } - public String setBpnFound(HttpServletRequest httpRequest, String processId, List bpnList) { + + /** + * Sets the process's status containing the given processId with "bpn-found" status, and + * the process state as "CREATED" in the given HTTP session. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code String} file path of the process status file. + * + * @throws ManagerException + * if unable to update the status file. + */ + @SuppressWarnings("Unused") + public String setBpnFound(HttpServletRequest httpRequest, String processId) { this.setProcessState(httpRequest, processId, "CREATED"); @@ -373,6 +747,20 @@ public String setBpnFound(HttpServletRequest httpRequest, String processId, List )); } + /** + * Sets the process's status containing the given processId with "contract-decline" status, and + * the process state as "ABORTED" in the given HTTP session. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code String} file path of the process status file. + * + * @throws ManagerException + * if unable to update the status file. + */ public String setDecline(HttpServletRequest httpRequest, String processId) { this.setProcessState(httpRequest, processId, "ABORTED"); @@ -382,24 +770,58 @@ public String setDecline(HttpServletRequest httpRequest, String processId) { "DECLINED" )); } + + /** + * Cancels the process containing the given processId of the given HTTP session and sets it status as "negotiation-canceled", and + * the process state as "TERMINATED" in the given HTTP session. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code String} file path of the process status file. + * + * @throws ManagerException + * if unable to update the status file. + */ public String cancelProcess(HttpServletRequest httpRequest, String processId) { - try { - Process process = this.getProcess(httpRequest, processId); - Thread thread = process.getThread(); - if (thread == null) { - throw new ManagerException(this.getClass().getName(), "Thread not found!"); - } - this.setProcessState(httpRequest, processId, "TERMINATED"); - thread.interrupt(); // Interrupt thread + try { + Process process = this.getProcess(httpRequest, processId); + Thread thread = process.getThread(); + if (thread == null) { + throw new ManagerException(this.getClass().getName(), "Thread not found!"); + } + this.setProcessState(httpRequest, processId, "TERMINATED"); + thread.interrupt(); // Interrupt thread - return this.setStatus(processId, "negotiation-canceled", new History( - processId, - "CANCELLED" - )); - }catch (Exception e){ - throw new ManagerException(this.getClass().getName(),e, "It was not possible to cancel the negotiation thread for process ["+processId+"]!"); - } + return this.setStatus(processId, "negotiation-canceled", new History( + processId, + "CANCELLED" + )); + } catch (Exception e){ + throw new ManagerException(this.getClass().getName(),e, "It was not possible to cancel the negotiation thread for process ["+processId+"]!"); + } } + + /** + * Sets the history of the process's status containing the given processId with "contract-signed" historyId, the "SIGNED" status + * and with the given contractId. Also updates the process state as "STARTING" in the given HTTP session. + *

+ * @param httpRequest + * the HTTP request. + * @param processId + * the {@code String} id of the application's process. + * @param contractId + * the {@code String} identification of the contract negotiation. + * @param signedAt + * the {@code Long} timestamp when the contract was signed. + * + * @return a {@code String} file path of the process status file. + * + * @throws ManagerException + * if unable to update the status file. + */ public String setSigned(HttpServletRequest httpRequest, String processId, String contractId, Long signedAt) { this.setProcessState(httpRequest, processId, "STARTING"); @@ -411,6 +833,17 @@ public String setSigned(HttpServletRequest httpRequest, String processId, String )); } + /** + * Loads the {@code Dataset} object from the Process with the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code Dataset} object with the loaded data. + * + * @throws ManagerException + * if unable to load the dataset. + */ public Dataset loadDataset(String processId) { try { String path = this.getProcessFilePath(processId, this.datasetFileName); @@ -419,6 +852,18 @@ public Dataset loadDataset(String processId) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to load the dataset for process id [" + processId + "]"); } } + + /** + * Loads the {@code SearchStatus} object from the Process with the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code SearchStatus} object with the status data. + * + * @throws ManagerException + * if unable to load the search status. + */ public SearchStatus getSearchStatus(String processId) { try { String path = this.getTmpProcessFilePath(processId, this.searchFileName); @@ -428,7 +873,17 @@ public SearchStatus getSearchStatus(String processId) { } } - + /** + * Loads the negotiation information from the Process with the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code Map} object with the negotiation data. + * + * @throws ManagerException + * if unable to load the negotiation file. + */ public Map loadNegotiation(String processId) { try { String path = this.getProcessFilePath(processId, this.negotiationFileName); @@ -437,6 +892,18 @@ public Map loadNegotiation(String processId) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to load the negotiation file for process id [" + processId + "]"); } } + + /** + * Loads the transfer data from the Process with the given processId. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code Map} object with the transfer data. + * + * @throws ManagerException + * if unable to load the transfer file. + */ public Map loadTransfer(String processId) { try { String path = this.getProcessFilePath(processId, this.transferFileName); @@ -445,6 +912,31 @@ public Map loadTransfer(String processId) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to load the transfer file for process id [" + processId + "]"); } } + + /** + * Saves the given payload into the Process with the given processId and updates its status history with the + * given information. Setting the started time with the given timestamp by the startedTime parameter. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param payload + * the {@code Object} object representing the payload. + * @param fileName + * the {@code String} name of the file to store the payload. + * @param startedTime + * the {@code Long} timestamp when the process's event started. + * @param assetId + * the {@code String} identification of the asset. + * @param status + * the {@code String} status to update. + * @param eventKey + * the {@code String} name of the event to save (e.g: "negotiation-accepted", "transfer-completed", etc.). + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the payload for the specified event. + */ public String saveProcessPayload(String processId, Object payload, String fileName, Long startedTime, String assetId, String status, String eventKey) { try { Boolean encrypt = env.getProperty("passport.dataTransfer.encrypt", Boolean.class, true); @@ -473,6 +965,28 @@ public String saveProcessPayload(String processId, Object payload, String fileNa } } + /** + * Saves the given payload into the Process with the given processId and updates its status history with the + * given information. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param payload + * the {@code Object} object representing the payload. + * @param fileName + * the {@code String} name of the file to store the payload. + * @param assetId + * the {@code String} identification of the asset. + * @param status + * the {@code String} status to update. + * @param eventKey + * the {@code String} name of the event to save (e.g: "negotiation-accepted", "transfer-completed", etc.). + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the payload for the specified event. + */ public String saveProcessPayload(String processId, Object payload, String fileName, String assetId, String status, String eventKey) { try { return this.saveProcessPayload(processId, payload, fileName, DateTimeUtil.getTimestamp(), assetId, status, eventKey); @@ -480,6 +994,23 @@ public String saveProcessPayload(String processId, Object payload, String fileNa throw new ManagerException(this.getClass().getName(), e, "Failed to save payload!"); } } + + /** + * Saves the given {@code Negotation} object with negotiation data in the Process with the given + * processId and updates its status history. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param negotiation + * the {@code Negotiation} object with the updated data. + * @param dtr + * if true the negotiation is a "digital-twin-registry" type negotiation or "negotiation" type otherwise. + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the negotiation. + */ public String saveNegotiation(String processId, Negotiation negotiation, Boolean dtr) { try { String fileName = !dtr?this.negotiationFileName:"digital-twin-registry/"+this.negotiationFileName; @@ -498,6 +1029,23 @@ public String saveNegotiation(String processId, Negotiation negotiation, Boolean throw new ManagerException(this.getClass().getName(), e, "It was not possible to save the negotiation!"); } } + + /** + * Saves the given {@code Transfer} object with transfer data in the Process with the given + * processId and updates its status history. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param transfer + * the {@code Transfer} object with the updated data. + * @param dtr + * if true the transfer is a "digital-twin-registry" type transfer or "transfer" type otherwise. + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the transfer. + */ public String saveTransfer(String processId, Transfer transfer, Boolean dtr) { try { String fileName = !dtr?this.transferFileName:"digital-twin-registry/"+this.transferFileName; @@ -516,6 +1064,25 @@ public String saveTransfer(String processId, Transfer transfer, Boolean dtr) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to save the transfer!"); } } + + /** + * Saves the given {@code NegotiationRequest} object with negotiation request data and the negotiation response in the Process with the given + * processId and updates its status history. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param negotiationRequest + * the {@code NegotiationRequest} object with the updated data. + * @param negotiationResponse + * the {@code NegotiationResponse} object with the negotiation's response data. + * @param dtr + * if true the negotiation is a "digital-twin-registry" type negotiation or "negotiation" type otherwise. + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the negotiation request. + */ public String saveNegotiationRequest(String processId, NegotiationRequest negotiationRequest, IdResponse negotiationResponse, Boolean dtr) { try { return this.saveProcessPayload( @@ -530,6 +1097,24 @@ public String saveNegotiationRequest(String processId, NegotiationRequest negoti } } + /** + * Saves the given {@code TransferRequest} object with transfer request data and the transfer response in the Process with the given + * processId and updates its status history. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param transferRequest + * the {@code TransferRequest} object with the updated data. + * @param transferResponse + * the {@code TransferResponse} object with the transfer's response data. + * @param dtr + * if true the transfer is a "digital-twin-registry" type transfer or "transfer" type otherwise. + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the transfer request. + */ public String saveTransferRequest(String processId, TransferRequest transferRequest, IdResponse transferResponse, Boolean dtr) { try { return this.saveProcessPayload( @@ -544,6 +1129,19 @@ public String saveTransferRequest(String processId, TransferRequest transferRequ } } + /** + * Saves the given {@code Endpoint} URL endpoint in the Process containing the given processId and updates its status. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param endpoint + * the {@code String} endpoint URL of the target passport. + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the endpoint. + */ public String setEndpoint(String processId, String endpoint){ try { String path = this.getProcessFilePath(processId, this.metaFileName); @@ -560,6 +1158,16 @@ public String setEndpoint(String processId, String endpoint){ throw new ManagerException(this.getClass().getName(), e, "It was not possible to create/update the status file"); } } + + /** + * Extracts the contractId from the given {@code DataPlaneEndpoint} object. + *

+ * @param endpointData + * the {@code DataPlaneEndpoint} object with data plane endpoint data. + * + * @return a {@code String} identification of the contract. + * + */ public String getContractId(DataPlaneEndpoint endpointData){ if(!endpointData.offerIdExists()) { @@ -569,6 +1177,18 @@ public String getContractId(DataPlaneEndpoint endpointData){ return endpointData.getOfferId(); } + + /** + * Loads the transferred passport of the Process with the given processId after the negotiations being succeeded. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code PassportV3} object with the loaded passport data. + * + * @throws ManagerException + * if unable to load the passport. + */ public PassportV3 loadPassport(String processId){ try { String path = this.getProcessFilePath(processId, this.passportFileName); @@ -611,6 +1231,77 @@ public PassportV3 loadPassport(String processId){ throw new ManagerException(this.getClass().getName(), e, "It was not possible to load the passport!"); } } + + /** + * Loads the transferred digital product passport of the Process with the given processId after the negotiations being succeeded. + *

+ * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code DigitalProductPassport} object with the loaded passport data. + * + * @throws ManagerException + * if unable to load the digital product passport. + */ + public DigitalProductPassport loadDigitalProductPassport(String processId){ + try { + String path = this.getProcessFilePath(processId, this.passportFileName); + History history = new History( + processId, + "RETRIEVED" + ); + if(!fileUtil.pathExists(path)){ + throw new ManagerException(this.getClass().getName(), "Digital Product Passport file ["+path+"] not found!"); + } + DigitalProductPassport passport = null; + Boolean encrypt = env.getProperty("passport.dataTransfer.encrypt", Boolean.class, true); + if(encrypt){ + Status status = this.getStatus(processId); + History negotiationHistory = status.getHistory("negotiation-accepted"); + String decryptedPassportJson = CrypUtil.decryptAes(fileUtil.readFile(path), this.generateStatusToken(status, negotiationHistory.getId())); + // Delete passport file + + passport = (DigitalProductPassport) jsonUtil.loadJson(decryptedPassportJson, DigitalProductPassport.class); + }else{ + passport = (DigitalProductPassport) jsonUtil.fromJsonFileToObject(path, DigitalProductPassport.class); + } + + if(passport == null){ + throw new ManagerException(this.getClass().getName(), "Failed to load the passport"); + } + Boolean deleteResponse = fileUtil.deleteFile(path); + + if(deleteResponse==null){ + LogUtil.printStatus("[PROCESS " + processId +"] Digital Product file not found, failed to delete!"); + } else if (deleteResponse) { + LogUtil.printStatus("[PROCESS " + processId +"] Digital Product file deleted successfully!"); + } else{ + LogUtil.printStatus("[PROCESS " + processId +"] Failed to delete digital product passport file!"); + } + + this.setStatus(processId,"passport-retrieved", history); + return passport; + } catch (Exception e) { + throw new ManagerException(this.getClass().getName(), e, "It was not possible to load the digital product passport!"); + } + } + + /** + * Saves the given Passport in the Process with the given processId encrypted with a token generated by + * data extracted from the {@code DataPlaneEndpoint} object. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param endpointData + * the {@code DataPlaneEndpoint} object with data plane endpoint data. + * @param passport + * the {@code Passport} object with the passport data to update. + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the passport. + */ public String savePassport(String processId, DataPlaneEndpoint endpointData, Passport passport) { try { // Retrieve the configuration @@ -623,7 +1314,7 @@ public String savePassport(String processId, DataPlaneEndpoint endpointData, Pas // Get token content or the contractID from properties String contractId = this.getContractId(endpointData); if(contractId == null){ - throw new ManagerException(this.getClass().getName(), "The Contract Id is null! It was not possible to save the passport!"); + throw new ManagerException(this.getClass().getName(), "The Contract Id is null! It was not possible to save the digital product passport!"); } passportContent = CrypUtil.encryptAes(jsonUtil.toJson(passport, prettyPrint), this.generateStatusToken(status, contractId)); // Encrypt the data with the token } @@ -636,10 +1327,25 @@ public String savePassport(String processId, DataPlaneEndpoint endpointData, Pas "RECEIVED", "passport-received"); } catch (Exception e) { - throw new ManagerException(this.getClass().getName(), e, "It was not possible to save the passport!"); + throw new ManagerException(this.getClass().getName(), e, "It was not possible to save the digital product passport!"); } } + /** + * Saves the given {@code DigitalTwin} object in the Process with the given processId with the given timestamp. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param digitalTwin + * the {@code DigitalTwin} object to save. + * @param startedTime + * the {@code Long} timestamp when the process's event started. + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the {@code DigitalTwin}. + */ public String saveDigitalTwin(String processId, DigitalTwin digitalTwin, Long startedTime) { try { return this.saveProcessPayload( @@ -655,6 +1361,21 @@ public String saveDigitalTwin(String processId, DigitalTwin digitalTwin, Long st } } + /** + * Saves the given {@code DigitalTwin3} object in the Process with the given processId with the given timestamp. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param digitalTwin + * the {@code DigitalTwin3} object to save. + * @param startedTime + * the {@code Long} timestamp when the process's event started. + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the {@code DigitalTwin3}. + */ public String saveDigitalTwin3(String processId, DigitalTwin3 digitalTwin, Long startedTime) { try { return this.saveProcessPayload( @@ -670,8 +1391,23 @@ public String saveDigitalTwin3(String processId, DigitalTwin3 digitalTwin, Long } } - - + /** + * Saves the given {@code Dataset} object in the Process with the given processId with the given timestamp. + *

+ * @param processId + * the {@code String} id of the application's process. + * @param dataset + * the {@code Dataset} object to save. + * @param startedTime + * the {@code Long} timestamp when the process's event started. + * @param dtr + * if true the file name is a "digital-twin-registry" type or "dataset" type otherwise. + * + * @return a {@code String} file path of the file where data was stored. + * + * @throws ManagerException + * if unable to save the data set. + */ public String saveDataset(String processId, Dataset dataset, Long startedTime, Boolean dtr) { try { return this.saveProcessPayload( @@ -687,4 +1423,4 @@ public String saveDataset(String processId, Dataset dataset, Long startedTime, B } } -} \ No newline at end of file +} diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/Credential.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/Credential.java index 0fed3bafe..c8ae5105d 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/Credential.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/Credential.java @@ -30,16 +30,15 @@ import jakarta.servlet.http.HttpServletRequest; +@SuppressWarnings("Unused") @Component public class Credential { @Autowired HttpUtil httpUtil; - private String session_code; private String execution; private String client_id; - private String client_secret; private String tab_id; private UserCredential userCredential; diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/JwtToken.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/JwtToken.java index ecc7009ea..83a52db8e 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/JwtToken.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/JwtToken.java @@ -26,33 +26,33 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This class consists exclusively to define attributes and methods related to the JSON Web Token (JWT) token used + * for authentication in the Application. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class JwtToken { + /** ATTRIBUTES **/ @JsonProperty("access_token") String accessToken; - @JsonProperty("refresh_token") String refreshToken; @JsonProperty("expires_in") Integer expiresIn; - @JsonProperty("refresh_expires_in") Integer refreshExpiresIn; - @JsonProperty("token_type") String tokenType; - @JsonProperty("id_token") String idToken; - @JsonProperty("not-before-policy") String notBeforePolicy; - @JsonProperty("scope") String scope; - + /** CONSTRUCTOR(S) **/ public JwtToken(){ } @@ -61,66 +61,67 @@ public JwtToken(String accessToken, String refreshToken) { this.refreshToken = refreshToken; } + /** GETTERS AND SETTERS **/ public String getAccessToken() { return accessToken; } - + @SuppressWarnings("Unused") public void setAccessToken(String accessToken) { this.accessToken = accessToken; } - + @SuppressWarnings("Unused") public String getRefreshToken() { return refreshToken; } - + @SuppressWarnings("Unused") public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } - + @SuppressWarnings("Unused") public Integer getExpiresIn() { return expiresIn; } - + @SuppressWarnings("Unused") public void setExpiresIn(Integer expiresIn) { this.expiresIn = expiresIn; } - + @SuppressWarnings("Unused") public Integer getRefreshExpiresIn() { return refreshExpiresIn; } - + @SuppressWarnings("Unused") public void setRefreshExpiresIn(Integer refreshExpiresIn) { this.refreshExpiresIn = refreshExpiresIn; } - + @SuppressWarnings("Unused") public String getTokenType() { return tokenType; } - + @SuppressWarnings("Unused") public void setTokenType(String tokenType) { this.tokenType = tokenType; } - + @SuppressWarnings("Unused") public String getIdToken() { return idToken; } - + @SuppressWarnings("Unused") public void setIdToken(String idToken) { this.idToken = idToken; } - + @SuppressWarnings("Unused") public String getNotBeforePolicy() { return notBeforePolicy; } - + @SuppressWarnings("Unused") public void setNotBeforePolicy(String notBeforePolicy) { this.notBeforePolicy = notBeforePolicy; } - + @SuppressWarnings("Unused") public String getScope() { return scope; } - + @SuppressWarnings("Unused") public void setScope(String scope) { this.scope = scope; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserCredential.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserCredential.java index 22bf21d46..0eb7ebbf5 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserCredential.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserCredential.java @@ -23,14 +23,19 @@ package org.eclipse.tractusx.productpass.models.auth; +/** + * This class consists exclusively to define attributes and methods related to the JSON Web Token (JWT) token used + * for authentication in the Application. + **/ public class UserCredential { + /** ATTRIBUTES **/ private String username; private String password; private String credentialId; - private JwtToken jwt = null; + /** CONSTRUCTOR(S) **/ public UserCredential(){ } @@ -39,57 +44,62 @@ public UserCredential(String username, String password, String credentialId) { this.password = password; this.credentialId = credentialId; } - + @SuppressWarnings("Unused") public UserCredential(String username, String password, String credentialId, JwtToken jwt) { this.username = username; this.password = password; this.credentialId = credentialId; this.jwt = jwt; } - + @SuppressWarnings("Unused") public UserCredential(JwtToken jwt){ this.jwt = jwt; } + /** GETTERS AND SETTERS **/ public JwtToken getJwt() { return jwt; } - public void setJwt(JwtToken jwt) { this.jwt = jwt; } + @SuppressWarnings("Unused") public void setJwtToken(String accessToken, String refreshToken){ this.jwt = new JwtToken(accessToken, refreshToken); } - public void cleanJwtToken(){ - this.jwt = new JwtToken(); - } - public void deleteJwt(){ - this.jwt = null; - } - + @SuppressWarnings("Unused") public String getUsername() { return username; } - + @SuppressWarnings("Unused") public void setUsername(String username) { this.username = username; } - + @SuppressWarnings("Unused") public String getPassword() { return password; } - + @SuppressWarnings("Unused") public void setPassword(String password) { this.password = password; } - + @SuppressWarnings("Unused") public String getCredentialId() { return credentialId; } - + @SuppressWarnings("Unused") public void setCredentialId(String credentialId) { this.credentialId = credentialId; } + /** METHODS **/ + @SuppressWarnings("Unused") + public void cleanJwtToken(){ + this.jwt = new JwtToken(); + } + @SuppressWarnings("Unused") + public void deleteJwt(){ + this.jwt = null; + } + } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserInfo.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserInfo.java index 688d93edd..7879c6d8a 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserInfo.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserInfo.java @@ -25,8 +25,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This class consists exclusively to define attributes and methods related to the needed User's information. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class UserInfo { + + /** ATTRIBUTES **/ @JsonProperty("sub") String sub; @JsonProperty("email_verified") @@ -37,15 +43,15 @@ public class UserInfo { String preferred_username; @JsonProperty("locale") String locale; - @JsonProperty("given_name") String given_name; - @JsonProperty("family_name") String family_name; @JsonProperty("email") String email; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public UserInfo(String sub, String email_verified, String name, String preferred_username, String locale, String given_name, String family_name, String email) { this.sub = sub; this.email_verified = email_verified; @@ -56,70 +62,70 @@ public UserInfo(String sub, String email_verified, String name, String preferred this.family_name = family_name; this.email = email; } - + @SuppressWarnings("Unused") public UserInfo() { } + /** GETTERS AND SETTERS **/ + @SuppressWarnings("Unused") public String getSub() { return sub; } - + @SuppressWarnings("Unused") public void setSub(String sub) { this.sub = sub; } - + @SuppressWarnings("Unused") public String getEmail_verified() { return email_verified; } - + @SuppressWarnings("Unused") public void setEmail_verified(String email_verified) { this.email_verified = email_verified; } - public String getName() { return name; } - public void setName(String name) { this.name = name; } - + @SuppressWarnings("Unused") public String getPreferred_username() { return preferred_username; } - + @SuppressWarnings("Unused") public void setPreferred_username(String preferred_username) { this.preferred_username = preferred_username; } - + @SuppressWarnings("Unused") public String getLocale() { return locale; } - + @SuppressWarnings("Unused") public void setLocale(String locale) { this.locale = locale; } - + @SuppressWarnings("Unused") public String getGiven_name() { return given_name; } - + @SuppressWarnings("Unused") public void setGiven_name(String given_name) { this.given_name = given_name; } - + @SuppressWarnings("Unused") public String getFamily_name() { return family_name; } - + @SuppressWarnings("Unused") public void setFamily_name(String family_name) { this.family_name = family_name; } - + @SuppressWarnings("Unused") public String getEmail() { return email; } - + @SuppressWarnings("Unused") public void setEmail(String email) { this.email = email; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/BpnDiscovery.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/BpnDiscovery.java index 780466535..5fdd59213 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/BpnDiscovery.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/BpnDiscovery.java @@ -31,34 +31,49 @@ import java.util.List; import java.util.stream.Collectors; +/** + * This class consists exclusively to define attributes and methods related to discovering the BPN numbers. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class BpnDiscovery { + + /** ATTRIBUTES **/ @JsonProperty("bpns") List bpns; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public BpnDiscovery(List bpns) { this.bpns = bpns; } - + @SuppressWarnings("Unused") public BpnDiscovery() { } + /** GETTERS AND SETTERS **/ + @SuppressWarnings("Unused") public List getBpns() { return bpns; } + @SuppressWarnings("Unused") + public void setBpns(List bpns) { + this.bpns = bpns; + } + /** METHODS **/ public List getBpnNumbers(){ return bpns.stream().map( BpnEndpoint::getValue ).collect(Collectors.toList()); } - - public void setBpns(List bpns) { - this.bpns = bpns; - } - + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes and methods related to BPN endpoints. + **/ public static class BpnEndpoint { + + /** ATTRIBUTES **/ @JsonProperty("type") String type; @JsonProperty("key") @@ -68,44 +83,42 @@ public static class BpnEndpoint { @JsonProperty("resourceId") String resourceId; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public BpnEndpoint(String type, String key, String value, String resourceId) { this.type = type; this.key = key; this.value = value; this.resourceId = resourceId; } - + @SuppressWarnings("Unused") public BpnEndpoint() { } + /** GETTERS AND SETTERS **/ public String getType() { return type; } - public void setType(String type) { this.type = type; } - public String getKey() { return key; } - public void setKey(String key) { this.key = key; } - public String getValue() { return value; } - public void setValue(String value) { this.value = value; } - + @SuppressWarnings("Unused") public String getResourceId() { return resourceId; } - + @SuppressWarnings("Unused") public void setResourceId(String resourceId) { this.resourceId = resourceId; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/Discovery.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/Discovery.java index d7173bb2f..0f9150dae 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/Discovery.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/Discovery.java @@ -30,43 +30,51 @@ import java.util.List; +/** + * This class consists exclusively to define attributes and methods related to discovering the needed Endpoints. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Discovery { + /** ATTRIBUTES **/ @JsonProperty("endpoints") List endpoints; + /** CONSTRUCTOR(S) **/ public Discovery() { } - public Discovery(List endpoints) { this.endpoints = endpoints; } + /** GETTERS AND SETTERS **/ public List getEndpoints() { return endpoints; } - public void setEndpoints(List endpoints) { this.endpoints = endpoints; } - public static class Endpoint{ + /** INNER CLASSES **/ + + /** + * This class consists exclusively to define attributes and methods related to the Endpoints information. + **/ + public static class Endpoint { + + /** ATTRIBUTES **/ @JsonProperty("type") String type; - @JsonProperty("description") String description; - @JsonProperty("endpointAddress") String endpointAddress; - @JsonProperty("documentation") String documentation; - @JsonProperty("resourceId") String resourceId; + /** CONSTRUCTOR(S) **/ public Endpoint(String type, String description, String endpointAddress, String documentation, String resourceId) { this.type = type; this.description = description; @@ -74,46 +82,42 @@ public Endpoint(String type, String description, String endpointAddress, String this.documentation = documentation; this.resourceId = resourceId; } - public Endpoint() { } + /** GETTERS AND SETTERS **/ public String getType() { return type; } - public void setType(String type) { this.type = type; } - public String getDescription() { return description; } - public void setDescription(String description) { this.description = description; } - public String getEndpointAddress() { return endpointAddress; } - + @SuppressWarnings("Unused") public void setEndpointAddress(String endpointAddress) { this.endpointAddress = endpointAddress; } - + @SuppressWarnings("Unused") public String getDocumentation() { return documentation; } - + @SuppressWarnings("Unused") public void setDocumentation(String documentation) { this.documentation = documentation; } - + @SuppressWarnings("Unused") public String getResourceId() { return resourceId; } - + @SuppressWarnings("Unused") public void setResourceId(String resourceId) { this.resourceId = resourceId; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/Dtr.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/Dtr.java index 2531c6bc6..e24a865bb 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/Dtr.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/Dtr.java @@ -30,57 +30,42 @@ import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; + +/** + * This class consists exclusively to define attributes and methods related to the Digital Twin Registry (DTR). + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Dtr { + + /** ATTRIBUTES **/ @JsonProperty("contractId") private String contractId; @JsonProperty("endpoint") private String endpoint; @JsonProperty("assetId") private String assetId; - @JsonProperty("bpn") private String bpn; + /** CONSTRUCTOR(S) **/ public Dtr(String contractId, String endpoint, String assetId, String bpn) { this.contractId = contractId; this.endpoint = endpoint; this.assetId = assetId; this.bpn = bpn; } - public Dtr() { } + /** GETTERS AND SETTERS **/ public String getContractId() { return contractId; } - - public void setContractId(String contractId) { - this.contractId = contractId; - } - - public String getEndpoint() { - return endpoint; - } - - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } - - public String getAssetId() { - return assetId; - } - - public void setAssetId(String assetId) { - this.assetId = assetId; - } - - public String getBpn() { - return bpn; - } - - public void setBpn(String bpn) { - this.bpn = bpn; - } + public void setContractId(String contractId) { this.contractId = contractId; } + public String getEndpoint() { return endpoint; } + public void setEndpoint(String endpoint) { this.endpoint = endpoint; } + public String getAssetId() { return assetId; } + public void setAssetId(String assetId) { this.assetId = assetId; } + public String getBpn() { return bpn; } + public void setBpn(String bpn) { this.bpn = bpn; } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/EdcDiscoveryEndpoint.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/EdcDiscoveryEndpoint.java index 3e8cfc3f8..07c4d0ef4 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/EdcDiscoveryEndpoint.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/EdcDiscoveryEndpoint.java @@ -30,33 +30,36 @@ import java.util.List; +/** + * This class consists exclusively to define attributes and methods related to discovering the EDC endpoints for each BPN number. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class EdcDiscoveryEndpoint { + + /** ATTRIBUTES **/ @JsonProperty("bpn") String bpn; @JsonProperty("connectorEndpoint") List connectorEndpoint; + /** CONSTRUCTOR(S) **/ public EdcDiscoveryEndpoint(String bpn, List connectorEndpoint) { this.bpn = bpn; this.connectorEndpoint = connectorEndpoint; } - public EdcDiscoveryEndpoint() { } + /** GETTERS AND SETTERS **/ public String getBpn() { return bpn; } - public void setBpn(String bpn) { this.bpn = bpn; } - public List getConnectorEndpoint() { return connectorEndpoint; } - public void setConnectorEndpoint(List connectorEndpoint) { this.connectorEndpoint = connectorEndpoint; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/DigitalTwin.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/DigitalTwin.java index d7413a033..2752193c7 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/DigitalTwin.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/DigitalTwin.java @@ -29,8 +29,13 @@ import java.util.ArrayList; +/** + * This class consists exclusively to define attributes related to the designed model of the Digital Twin's first version. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class DigitalTwin { + + /** ATTRIBUTES **/ @JsonProperty("description") ArrayList description; @JsonProperty("globalAssetId") @@ -41,13 +46,14 @@ public class DigitalTwin { String identification; @JsonProperty("specificAssetIds") ArrayList specificAssetIds; - @JsonProperty("submodelDescriptors") ArrayList submodelDescriptors; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public DigitalTwin() { } - + @SuppressWarnings("Unused") public DigitalTwin(ArrayList description, JsonNode globalAssetId, String idShort, String identification, ArrayList specificAssetIds, ArrayList submodelDescriptors) { this.description = description; this.globalAssetId = globalAssetId; @@ -57,51 +63,46 @@ public DigitalTwin(ArrayList description, JsonNode globalAssetId, Stri this.submodelDescriptors = submodelDescriptors; } - + /** GETTERS AND SETTERS **/ public ArrayList getDescription() { return description; } - public void setDescription(ArrayList description) { this.description = description; } - + @SuppressWarnings("Unused") public JsonNode getGlobalAssetId() { return globalAssetId; } - + @SuppressWarnings("Unused") public void setGlobalAssetId(JsonNode globalAssetId) { this.globalAssetId = globalAssetId; } - public String getIdShort() { return idShort; } - public void setIdShort(String idShort) { this.idShort = idShort; } - public String getIdentification() { return identification; } - + @SuppressWarnings("Unused") public void setIdentification(String identification) { this.identification = identification; } - + @SuppressWarnings("Unused") public ArrayList getSpecificAssetIds() { return specificAssetIds; } - + @SuppressWarnings("Unused") public void setSpecificAssetIds(ArrayList specificAssetIds) { this.specificAssetIds = specificAssetIds; } - public ArrayList getSubmodelDescriptors() { return submodelDescriptors; } - + @SuppressWarnings("Unused") public void setSubmodelDescriptors(ArrayList submodelDescriptors) { this.submodelDescriptors = submodelDescriptors; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/DigitalTwin3.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/DigitalTwin3.java index dd2348e16..576ca2b79 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/DigitalTwin3.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/DigitalTwin3.java @@ -30,36 +30,38 @@ import java.util.ArrayList; +/** + * This class consists exclusively to define attributes related to the designed model of the Digital Twin's improved version. + **/ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class DigitalTwin3 { + + /** ATTRIBUTES **/ @JsonProperty("description") ArrayList description; @JsonProperty("idShort") String idShort; - @JsonProperty("assetKind") String assetKind; - @JsonProperty("assetType") String assetType; - @JsonProperty("globalAssetId") String globalAssetId; @JsonProperty("displayName") Object displayName; - @JsonProperty("id") String identification; @JsonProperty("specificAssetIds") ArrayList specificAssetIds; - @JsonProperty("submodelDescriptors") ArrayList submodelDescriptors; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public DigitalTwin3() { } - + @SuppressWarnings("Unused") public DigitalTwin3(ArrayList description, String idShort, String identification, ArrayList specificAssetIds, ArrayList submodelDescriptors) { this.description = description; this.idShort = idShort; @@ -67,7 +69,7 @@ public DigitalTwin3(ArrayList description, String idShort, String iden this.specificAssetIds = specificAssetIds; this.submodelDescriptors = submodelDescriptors; } - + @SuppressWarnings("Unused") public DigitalTwin3(ArrayList description, String idShort, Object displayName, String identification, ArrayList specificAssetIds, ArrayList submodelDescriptors) { this.description = description; this.idShort = idShort; @@ -76,7 +78,7 @@ public DigitalTwin3(ArrayList description, String idShort, Object disp this.specificAssetIds = specificAssetIds; this.submodelDescriptors = submodelDescriptors; } - + @SuppressWarnings("Unused") public DigitalTwin3(ArrayList description, String idShort, String globalAssetId, Object displayName, String identification, ArrayList specificAssetIds, ArrayList submodelDescriptors) { this.description = description; this.idShort = idShort; @@ -86,7 +88,7 @@ public DigitalTwin3(ArrayList description, String idShort, String glob this.specificAssetIds = specificAssetIds; this.submodelDescriptors = submodelDescriptors; } - + @SuppressWarnings("Unused") public DigitalTwin3(ArrayList description, String idShort, String assetKind, String assetType, String globalAssetId, Object displayName, String identification, ArrayList specificAssetIds, ArrayList submodelDescriptors) { this.description = description; this.idShort = idShort; @@ -99,75 +101,70 @@ public DigitalTwin3(ArrayList description, String idShort, String asse this.submodelDescriptors = submodelDescriptors; } - + /** GETTERS AND SETTERS **/ public ArrayList getDescription() { return description; } - public void setDescription(ArrayList description) { this.description = description; } - public String getIdShort() { return idShort; } - public void setIdShort(String idShort) { this.idShort = idShort; } - public String getIdentification() { return identification; } - + @SuppressWarnings("Unused") public void setIdentification(String identification) { this.identification = identification; } - + @SuppressWarnings("Unused") public ArrayList getSpecificAssetIds() { return specificAssetIds; } - + @SuppressWarnings("Unused") public void setSpecificAssetIds(ArrayList specificAssetIds) { this.specificAssetIds = specificAssetIds; } - public ArrayList getSubmodelDescriptors() { return submodelDescriptors; } - + @SuppressWarnings("Unused") public void setSubmodelDescriptors(ArrayList submodelDescriptors) { this.submodelDescriptors = submodelDescriptors; } - + @SuppressWarnings("Unused") public Object getDisplayName() { return displayName; } - + @SuppressWarnings("Unused") public void setDisplayName(Object displayName) { this.displayName = displayName; } - + @SuppressWarnings("Unused") public String getGlobalAssetId() { return globalAssetId; } - + @SuppressWarnings("Unused") public void setGlobalAssetId(String globalAssetId) { this.globalAssetId = globalAssetId; } - + @SuppressWarnings("Unused") public String getAssetKind() { return assetKind; } - + @SuppressWarnings("Unused") public void setAssetKind(String assetKind) { this.assetKind = assetKind; } - + @SuppressWarnings("Unused") public String getAssetType() { return assetType; } - + @SuppressWarnings("Unused") public void setAssetType(String assetType) { this.assetType = assetType; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/EndPoint.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/EndPoint.java index ae2a7d3bc..3391000de 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/EndPoint.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/EndPoint.java @@ -26,68 +26,77 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +/** + * This class consists exclusively to define attributes related to the designed model of the Endpoint's first version. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class EndPoint { + + /** ATTRIBUTES **/ @JsonProperty("interface") String interfaceName; - ProtocolInformation protocolInformation = new ProtocolInformation(); + /** GETTERS AND SETTERS **/ public String getInterfaceName() { return interfaceName; } - + @SuppressWarnings("Unused") public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } - public ProtocolInformation getProtocolInformation() { return protocolInformation; } - + @SuppressWarnings("Unused") public void setProtocolInformation(String endpointAddress, String endpointProtocol, String endpointProtocolVersion) { this.protocolInformation = new ProtocolInformation(endpointAddress, endpointProtocol, endpointProtocolVersion); } - public static class ProtocolInformation{ + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes related to the needed protocol information for the first version. + **/ + public static class ProtocolInformation { + + /** ATTRIBUTES **/ @JsonProperty("endpointAddress") String endpointAddress; - @JsonProperty("endpointProtocol") String endpointProtocol; - @JsonProperty("endpointProtocolVersion") String endpointProtocolVersion; + /** CONSTRUCTOR(S) **/ public ProtocolInformation(String endpointAddress, String endpointProtocol, String endpointProtocolVersion) { this.endpointAddress = endpointAddress; this.endpointProtocol = endpointProtocol; this.endpointProtocolVersion = endpointProtocolVersion; } - public ProtocolInformation() { } + /** GETTERS AND SETTERS **/ public String getEndpointAddress() { return endpointAddress; } - + @SuppressWarnings("Unused") public void setEndpointAddress(String endpointAddress) { this.endpointAddress = endpointAddress; } - + @SuppressWarnings("Unused") public String getEndpointProtocol() { return endpointProtocol; } - + @SuppressWarnings("Unused") public void setEndpointProtocol(String endpointProtocol) { this.endpointProtocol = endpointProtocol; } - + @SuppressWarnings("Unused") public String getEndpointProtocolVersion() { return endpointProtocolVersion; } - + @SuppressWarnings("Unused") public void setEndpointProtocolVersion(String endpointProtocolVersion) { this.endpointProtocolVersion = endpointProtocolVersion; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/EndPoint3.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/EndPoint3.java index 3d6c8056c..139736579 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/EndPoint3.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/EndPoint3.java @@ -32,60 +32,66 @@ import java.util.List; import java.util.Map; +/** + * This class consists exclusively to define attributes related to the designed model of the Endpoint's improved version. + **/ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class EndPoint3 { + + /** ATTRIBUTES **/ @JsonProperty("interface") String interfaceName; - @JsonProperty("protocolInformation") ProtocolInformation3 protocolInformation = new ProtocolInformation3(); + /** GETTERS AND SETTERS **/ public String getInterfaceName() { return interfaceName; } - + @SuppressWarnings("Unused") public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } - public ProtocolInformation3 getProtocolInformation() { return protocolInformation; } - + @SuppressWarnings("Unused") public void setProtocolInformation(String endpointAddress, String endpointProtocol, List endpointProtocolVersion) { this.protocolInformation = new ProtocolInformation3(endpointAddress, endpointProtocol, endpointProtocolVersion); } - public static class ProtocolInformation3{ + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes related to the needed protocol information for the improved version. + **/ + public static class ProtocolInformation3 { + + /** ATTRIBUTES **/ @JsonProperty("href") String endpointAddress; - @JsonProperty("endpointProtocol") String endpointProtocol; @JsonProperty("subprotocol") String subprotocol; @JsonProperty("subprotocolBody") String subprotocolBody; - @JsonProperty("subprotocolBodyEncoding") String subprotocolBodyEncoding; - @JsonProperty("securityAttributes") Object securityAttributes; - @JsonProperty("endpointProtocolVersion") List endpointProtocolVersion; + /** CONSTRUCTOR(S) **/ public ProtocolInformation3(String endpointAddress, String endpointProtocol, List endpointProtocolVersion) { this.endpointAddress = endpointAddress; this.endpointProtocol = endpointProtocol; this.endpointProtocolVersion = endpointProtocolVersion; } - public ProtocolInformation3() { } - + @SuppressWarnings("Unused") public ProtocolInformation3(String endpointAddress, String endpointProtocol, String subprotocol, String subprotocolBody, List endpointProtocolVersion) { this.endpointAddress = endpointAddress; this.endpointProtocol = endpointProtocol; @@ -93,7 +99,7 @@ public ProtocolInformation3(String endpointAddress, String endpointProtocol, Str this.subprotocolBody = subprotocolBody; this.endpointProtocolVersion = endpointProtocolVersion; } - + @SuppressWarnings("Unused") public ProtocolInformation3(String endpointAddress, String endpointProtocol, String subprotocol, String subprotocolBody, String subprotocolBodyEncoding, List endpointProtocolVersion) { this.endpointAddress = endpointAddress; this.endpointProtocol = endpointProtocol; @@ -102,7 +108,7 @@ public ProtocolInformation3(String endpointAddress, String endpointProtocol, Str this.subprotocolBodyEncoding = subprotocolBodyEncoding; this.endpointProtocolVersion = endpointProtocolVersion; } - + @SuppressWarnings("Unused") public ProtocolInformation3(String endpointAddress, String endpointProtocol, String subprotocol, String subprotocolBody, String subprotocolBodyEncoding, Object securityAttributes, List endpointProtocolVersion) { this.endpointAddress = endpointAddress; this.endpointProtocol = endpointProtocol; @@ -113,42 +119,43 @@ public ProtocolInformation3(String endpointAddress, String endpointProtocol, Str this.endpointProtocolVersion = endpointProtocolVersion; } + /** GETTERS AND SETTERS **/ + @SuppressWarnings("Unused") public String getEndpointAddress() { return endpointAddress; } - + @SuppressWarnings("Unused") public void setEndpointAddress(String endpointAddress) { this.endpointAddress = endpointAddress; } - + @SuppressWarnings("Unused") public String getEndpointProtocol() { return endpointProtocol; } - + @SuppressWarnings("Unused") public void setEndpointProtocol(String endpointProtocol) { this.endpointProtocol = endpointProtocol; } - + @SuppressWarnings("Unused") public List getEndpointProtocolVersion() { return endpointProtocolVersion; } - + @SuppressWarnings("Unused") public void setEndpointProtocolVersion(List endpointProtocolVersion) { this.endpointProtocolVersion = endpointProtocolVersion; } - + @SuppressWarnings("Unused") public String getSubprotocol() { return subprotocol; } - + @SuppressWarnings("Unused") public void setSubprotocol(String subprotocol) { this.subprotocol = subprotocol; } - + @SuppressWarnings("Unused") public String getSubprotocolBody() { return subprotocolBody; } - public Map getParsedSubprotocolBody() { try { return Splitter.on(';').withKeyValueSeparator('=').split(this.subprotocolBody); @@ -157,23 +164,23 @@ public Map getParsedSubprotocolBody() { return null; } } - + @SuppressWarnings("Unused") public void setSubprotocolBody(String subprotocolBody) { this.subprotocolBody = subprotocolBody; } - + @SuppressWarnings("Unused") public String getSubprotocolBodyEncoding() { return subprotocolBodyEncoding; } - + @SuppressWarnings("Unused") public void setSubprotocolBodyEncoding(String subprotocolBodyEncoding) { this.subprotocolBodyEncoding = subprotocolBodyEncoding; } - + @SuppressWarnings("Unused") public Object getSecurityAttributes() { return securityAttributes; } - + @SuppressWarnings("Unused") public void setSecurityAttributes(Object securityAttributes) { this.securityAttributes = securityAttributes; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/SubModel.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/SubModel.java index 2fdaed74c..682af7f79 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/SubModel.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/SubModel.java @@ -28,7 +28,12 @@ import java.util.ArrayList; +/** + * This class consists exclusively to define attributes related to the designed model of the Submodel's first version. + **/ public class SubModel { + + /** ATTRIBUTES **/ @JsonProperty("description") ArrayList description; @JsonProperty("idShort") @@ -37,10 +42,11 @@ public class SubModel { String identification; @JsonProperty("semanticId") JsonNode semanticId; - @JsonProperty("endpoints") ArrayList endpoints; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public SubModel(ArrayList description, String idShort, String identification, JsonNode semanticId, ArrayList endpoints) { this.description = description; this.idShort = idShort; @@ -48,46 +54,39 @@ public SubModel(ArrayList description, String idShort, String identifi this.semanticId = semanticId; this.endpoints = endpoints; } - + @SuppressWarnings("Unused") public SubModel() { } + /** GETTERS AND SETTERS **/ public ArrayList getDescription() { return description; } - public void setDescription(ArrayList description) { this.description = description; } - public String getIdShort() { return idShort; } - public void setIdShort(String idShort) { this.idShort = idShort; } - public String getIdentification() { return identification; } - + @SuppressWarnings("Unused") public void setIdentification(String identification) { this.identification = identification; } - public JsonNode getSemanticId() { return semanticId; } - public void setSemanticId(JsonNode semanticId) { this.semanticId = semanticId; } - public ArrayList getEndpoints() { return endpoints; } - public void setEndpoints(ArrayList endpoints) { this.endpoints = endpoints; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/SubModel3.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/SubModel3.java index 1264cf45f..7eb919a20 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/SubModel3.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/dtregistry/SubModel3.java @@ -29,38 +29,43 @@ import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; +import java.util.Map; +/** + * This class consists exclusively to define attributes related to the designed model of the Submodel's improved version. + **/ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class SubModel3 { + + /** ATTRIBUTES **/ @JsonProperty("description") ArrayList description; @JsonProperty("idShort") String idShort; - @JsonProperty("supplementalSemanticId") Object supplementalSemanticId; - @JsonProperty("id") String identification; @JsonProperty("semanticId") - JsonNode semanticId; - + SemanticId semanticId; @JsonProperty("endpoints") ArrayList endpoints; - public SubModel3(ArrayList description, String idShort, String identification, JsonNode semanticId, ArrayList endpoints) { + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") + public SubModel3(ArrayList description, String idShort, String identification, SemanticId semanticId, ArrayList endpoints) { this.description = description; this.idShort = idShort; this.identification = identification; this.semanticId = semanticId; this.endpoints = endpoints; } - + @SuppressWarnings("Unused") public SubModel3() { } - - public SubModel3(ArrayList description, String idShort, Object supplementalSemanticId, String identification, JsonNode semanticId, ArrayList endpoints) { + @SuppressWarnings("Unused") + public SubModel3(ArrayList description, String idShort, Object supplementalSemanticId, String identification, SemanticId semanticId, ArrayList endpoints) { this.description = description; this.idShort = idShort; this.supplementalSemanticId = supplementalSemanticId; @@ -69,51 +74,82 @@ public SubModel3(ArrayList description, String idShort, Object supplem this.endpoints = endpoints; } + /** GETTERS AND SETTERS **/ public ArrayList getDescription() { return description; } - public void setDescription(ArrayList description) { this.description = description; } - public String getIdShort() { return idShort; } - public void setIdShort(String idShort) { this.idShort = idShort; } - public String getIdentification() { return identification; } - + @SuppressWarnings("Unused") public void setIdentification(String identification) { this.identification = identification; } - - public JsonNode getSemanticId() { + public SemanticId getSemanticId() { return semanticId; } - - public void setSemanticId(JsonNode semanticId) { + public void setSemanticId(SemanticId semanticId) { this.semanticId = semanticId; } - public ArrayList getEndpoints() { return endpoints; } - public void setEndpoints(ArrayList endpoints) { this.endpoints = endpoints; } - + @SuppressWarnings("Unused") public Object getSupplementalSemanticId() { return supplementalSemanticId; } - + @SuppressWarnings("Unused") public void setSupplementalSemanticId(Object supplementalSemanticId) { this.supplementalSemanticId = supplementalSemanticId; } + + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes related to the Submodel's SemanticId. + **/ + public static class SemanticId { + + /** ATTRIBUTES **/ + @JsonProperty("type") + String type; + @JsonProperty("keys") + Map keys; + + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") + public SemanticId(String type, Map keys) { + this.type = type; + this.keys = keys; + } + @SuppressWarnings("Unused") + public SemanticId() { + } + + /** GETTERS AND SETTERS **/ + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public Map getKeys() { + return keys; + } + @SuppressWarnings("Unused") + public void setKeys(Map keys) { + this.keys = keys; + } + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/AssetSearch.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/AssetSearch.java index 457ea2f37..2f60f7558 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/AssetSearch.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/AssetSearch.java @@ -27,36 +27,38 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This class consists exclusively to define attributes related to the Asset search. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class AssetSearch { + /** ATTRIBUTES **/ @JsonProperty("assetId") String assetId; - @JsonProperty("connectorAddress") String connectorAddress; + /** CONSTRUCTOR(S) **/ public AssetSearch(String assetId, String connectorAddress) { this.assetId = assetId; this.connectorAddress = connectorAddress; } - + @SuppressWarnings("Unused") public AssetSearch() { } - + /** GETTERS AND SETTERS **/ public String getAssetId() { return assetId; } - public void setAssetId(String assetId) { this.assetId = assetId; } - public String getConnectorAddress() { return connectorAddress; } - public void setConnectorAddress(String connectorAddress) { this.connectorAddress = connectorAddress; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/DataPlaneEndpoint.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/DataPlaneEndpoint.java index 234c99bec..efcb6c7c0 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/DataPlaneEndpoint.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/DataPlaneEndpoint.java @@ -27,24 +27,28 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import org.eclipse.tractusx.productpass.exceptions.ServiceException; +/** + * This class consists exclusively to define attributes related to the Asset search. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class DataPlaneEndpoint { + + /** ATTRIBUTES **/ @JsonProperty("id") String id; - @JsonProperty("endpoint") String endpoint; - @JsonProperty("authKey") String authKey; - @JsonProperty("authCode") String authCode; - @JsonProperty("properties") Properties properties; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public DataPlaneEndpoint(String id, String endpoint, String authKey, String authCode, Properties properties) { this.id = id; this.endpoint = endpoint; @@ -52,58 +56,59 @@ public DataPlaneEndpoint(String id, String endpoint, String authKey, String auth this.authCode = authCode; this.properties = properties; } - + @SuppressWarnings("Unused") public DataPlaneEndpoint() { } + /** GETTERS AND SETTERS **/ public String getId() { return id; } - public void setId(String id) { this.id = id; } - public String getEndpoint() { return endpoint; } - public void setEndpoint(String endpoint) { this.endpoint = endpoint; } - public String getAuthKey() { return authKey; } - + @SuppressWarnings("Unused") public void setAuthKey(String authKey) { this.authKey = authKey; } - public String getAuthCode() { return authCode; } - + @SuppressWarnings("Unused") public void setAuthCode(String authCode) { this.authCode = authCode; } - public Properties getProperties() { return properties; } - public void setProperties(Properties properties) { this.properties = properties; } - + @SuppressWarnings("Unused") public void setOfferId(String offerId) { this.properties.offerId = offerId; } - public String getOfferId() { return this.properties.offerId; } + /** METHODS **/ + /** + * Checks if offerId exists in the properties attribute. + *

+ * + * @return true if the offerId exists, false otherwise. + * + */ public Boolean offerIdExists(){ try { return this.properties != null && this.properties.offerId != null; @@ -113,12 +118,13 @@ public Boolean offerIdExists(){ return false; } + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes related to the Asset search's properties. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) static class Properties { @JsonProperty("https://w3id.org/edc/v0.0.1/ns/cid") String offerId; - } - - } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/Jwt.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/Jwt.java index 8dbfa132d..500274666 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/Jwt.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/edc/Jwt.java @@ -30,24 +30,27 @@ import java.util.Map; +/** + * This class consists exclusively to define attributes related to the JSON Web Token (JWT) for authentication purposes. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Jwt { + + /** ATTRIBUTES **/ @JsonProperty("header") Map header; @JsonProperty("payload") Map payload; + /** GETTERS AND SETTERS **/ public Map getHeader() { return header; } - public void setHeader(Map header) { this.header = header; } - public Map getPayload() { return payload; } - public void setPayload(Map payload) { this.payload = payload; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/Response.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/Response.java index 3a5016f5a..9c3221b43 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/Response.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/Response.java @@ -27,19 +27,24 @@ import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; + +/** + * This class consists exclusively to define attributes related to any kind of HTTP response of the HTTP requests made by the Application. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Response { + /** ATTRIBUTES **/ @JsonProperty("message") public String message = null; @JsonProperty("status") public Integer status = 200; @JsonProperty("statusText") public String statusText = null; - @JsonProperty("data") public Object data = null; + /** CONSTRUCTOR(S) **/ public Response(String message, Integer status, String statusText) { this.message = message; this.status = status; @@ -62,7 +67,6 @@ public Response(String message, Integer status) { } public Response() { } - public Response mapError(Map errorAttributes) { this.message = errorAttributes.getOrDefault("message", "An error occurred in the server").toString(); this.status = (Integer) errorAttributes.getOrDefault("status", 500); @@ -70,38 +74,33 @@ public Response mapError(Map errorAttributes) { return this; } + /** GETTERS AND SETTERS **/ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } - public Integer getStatus() { return status; } - public void setStatus(Integer status) { this.status = status; } - + @SuppressWarnings("Unused") public String getStatusText() { return statusText; } - + @SuppressWarnings("Unused") public void setStatusText(String statusText) { this.statusText = statusText; } - public String errorString(){ return "["+this.statusText+"]: "+this.message; } - public Object getData() { return data; } - public void setData(Object data) { this.data = data; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/DiscoverySearch.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/DiscoverySearch.java index 99a4cb90c..587abe378 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/DiscoverySearch.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/DiscoverySearch.java @@ -28,38 +28,44 @@ import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.NotNull; +/** + * This class consists exclusively to define attributes related to the "/create" endpoint request and therefor to the Discovery search request. + * It's the mandatory body parameter for the HTTP request. + * + **/ public class DiscoverySearch { + + /** ATTRIBUTES **/ @NotNull(message = "Id needs to be defined!") @JsonProperty("id") String id; - @JsonProperty("type") String type; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public DiscoverySearch(String id, String type) { this.id = id; this.type = type; } - + @SuppressWarnings("Unused") public DiscoverySearch(String id) { this.id = id; } - + @SuppressWarnings("Unused") public DiscoverySearch() { } + /** GETTERS AND SETTERS **/ public String getId() { return id; } - public void setId(String id) { this.id = id; } - public String getType() { return type; } - public void setType(String type) { this.type = type; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/Search.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/Search.java index 63213e199..477963e63 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/Search.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/Search.java @@ -25,88 +25,89 @@ package org.eclipse.tractusx.productpass.models.http.requests; -import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.NotNull; +/** + * This class consists exclusively to define attributes related to the "/search" endpoint request. + * It's the mandatory body parameter for the HTTP request. + **/ public class Search { - + /** ATTRIBUTES **/ @NotNull(message = "Process Id") @JsonProperty("processId") String processId; - @NotNull(message = "Id needs to be defined!") @JsonProperty("id") String id; - @NotNull(message = "Passport Version needs to be defined!") @JsonProperty("version") String version; - @JsonProperty(value = "idType", defaultValue = "partInstanceId") String idType = "partInstanceId"; @JsonProperty(value = "dtIndex", defaultValue = "0") Integer dtIndex = 0; - @JsonProperty(value = "idShort", defaultValue = "batteryPass") - String idShort = "batteryPass"; - + @JsonProperty(value = "idShort", defaultValue = "digitalProductPass") + String idShort = "digitalProductPass"; + @JsonProperty(value = "semanticId") + String semanticId; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public Search() { } - - public Search(String processId, String id, String version, String idType, Integer dtIndex, String idShort) { + @SuppressWarnings("Unused") + public Search(String processId, String id, String version, String idType, Integer dtIndex, String idShort, String semanticId) { this.processId = processId; this.id = id; this.version = version; this.idType = idType; this.dtIndex = dtIndex; this.idShort = idShort; + this.semanticId = semanticId; } + /** GETTERS AND SETTERS **/ + public String getSemanticId() { + return semanticId; + } + public void setSemanticId(String semanticId) { + this.semanticId = semanticId; + } public String getProcessId() { return processId; } - public void setProcessId(String processId) { this.processId = processId; } public String getId() { return id; } - public void setId(String id) { this.id = id; } - public String getIdType() { return idType; } - public void setIdType(String idType) { this.idType = idType; } - public Integer getDtIndex() { return dtIndex; } - public void setDtIndex(Integer dtIndex) { this.dtIndex = dtIndex; } - public String getIdShort() { return idShort; } - public void setIdShort(String idShort) { this.idShort = idShort; } - public String getVersion() { return version; } - public void setVersion(String version) { this.version = version; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/TokenRequest.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/TokenRequest.java index 4a73b514c..acb79b222 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/TokenRequest.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/requests/TokenRequest.java @@ -28,11 +28,17 @@ import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.NotNull; + +/** + * This class consists exclusively to define attributes related to the many endpoint request like "/sign", "/passport", etc. + * It's the mandatory body parameter for the HTTP requests. + **/ public class TokenRequest { + + /** ATTRIBUTES **/ @NotNull(message = "Process id needs to be defined!") @JsonProperty("processId") String processId; - @NotNull(message = "ContractId needs to be defined!") @JsonProperty("contractId") String contractId; @@ -40,36 +46,34 @@ public class TokenRequest { @JsonProperty("token") String token; - + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public TokenRequest(String processId, String contractId, String token) { this.processId = processId; this.contractId = contractId; this.token = token; } + + /** GETTERS AND SETTERS **/ public String getToken() { return token; } - public void setToken(String token) { this.token = token; } - + @SuppressWarnings("Unused") public TokenRequest() { } - public String getProcessId() { return processId; } - public void setProcessId(String processId) { this.processId = processId; } - public String getContractId() { return contractId; } - public void setContractId(String contractId) { this.contractId = contractId; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/responses/IdResponse.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/responses/IdResponse.java index a81ffacbb..d96a60932 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/responses/IdResponse.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/http/responses/IdResponse.java @@ -30,45 +30,47 @@ import com.fasterxml.jackson.databind.JsonNode; import org.eclipse.tractusx.productpass.models.negotiation.DidDocument; +/** + * This class consists exclusively to define attributes related to the response of the requests made by the Application. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class IdResponse extends DidDocument { + /** ATTRIBUTES **/ @JsonProperty("edc:createdAt") public Long createdAt; @JsonProperty("@context") JsonNode context; - + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public IdResponse(String id, String type, Long createdAt, JsonNode context) { super(id, type); this.createdAt = createdAt; this.context = context; } - + @SuppressWarnings("Unused") public IdResponse(Long createdAt, JsonNode context) { this.createdAt = createdAt; this.context = context; } - + @SuppressWarnings("Unused") public IdResponse() { } + /** GETTERS AND SETTERS **/ public IdResponse(String id, String type) { super(id, type); } - public Long getCreatedAt() { return createdAt; } - public void setCreatedAt(Long createdAt) { this.createdAt = createdAt; } - public JsonNode getContext() { return context; } - public void setContext(JsonNode context) { this.context = context; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/History.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/History.java index b2a581236..93bfadc3b 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/History.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/History.java @@ -29,23 +29,27 @@ import com.fasterxml.jackson.annotation.JsonProperty; import utils.DateTimeUtil; +/** + * This class consists exclusively to define attributes related to the historization of the processes' status. + * To keep track of each process status history. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class History { + /** ATTRIBUTES **/ @JsonProperty("id") public String id; - @JsonProperty("status") public String status; - @JsonProperty("started") public Long started; - @JsonProperty("updated") public Long updated; @JsonProperty("attempts") public Integer attempts; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public History(String id, String status, Integer attempts) { this.id = id; this.status = status; @@ -53,14 +57,13 @@ public History(String id, String status, Integer attempts) { this.updated = DateTimeUtil.getTimestamp(); this.attempts = attempts; } - public History(String id, String status, Long started) { this.id = id; this.status = status; this.started = started; this.updated = DateTimeUtil.getTimestamp(); } - + @SuppressWarnings("Unused") public History(String id, String status, Long started, Integer attempts) { this.id = id; this.status = status; @@ -68,24 +71,23 @@ public History(String id, String status, Long started, Integer attempts) { this.updated = DateTimeUtil.getTimestamp(); this.attempts = attempts; } - public History(String id, String status) { this.id = id; this.status = status; this.started = DateTimeUtil.getTimestamp(); this.updated = DateTimeUtil.getTimestamp(); } - + @SuppressWarnings("Unused") public History() { } - + @SuppressWarnings("Unused") public History(String id,String status, Long started, Long updated) { this.id = id; this.status = status; this.started = started; this.updated = updated; } - + @SuppressWarnings("Unused") public History(String id,String status, Long started, Long updated, Integer attempts) { this.id = id; this.status = status; @@ -94,27 +96,24 @@ public History(String id,String status, Long started, Long updated, Integer atte this.attempts = attempts; } - + /** GETTERS AND SETTERS **/ public Long getStarted() { return started; } - public void setStarted(Long started) { this.started = started; } - public Long getUpdated() { return updated; } - public void setUpdated(Long updated) { this.updated = updated; } - + @SuppressWarnings("Unused") public Integer getAttempts() { return attempts; } - + @SuppressWarnings("Unused") public void addAttempt(){ this.updated = DateTimeUtil.getTimestamp(); if(this.attempts==null){ @@ -122,25 +121,21 @@ public void addAttempt(){ } this.attempts++; } - + @SuppressWarnings("Unused") public void setAttempts(Integer attempts) { this.updated = DateTimeUtil.getTimestamp(); this.attempts = attempts; } - public String getStatus() { return status; } - public void setStatus(String status) { this.status = status; this.updated = DateTimeUtil.getTimestamp(); } - public String getId() { return id; } - public void setId(String id) { this.id = id; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/Process.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/Process.java index c7242b461..a32158401 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/Process.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/Process.java @@ -29,24 +29,28 @@ import com.fasterxml.jackson.annotation.JsonProperty; import utils.DateTimeUtil; + +/** + * This class consists exclusively to define attributes related to the Processes. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Process { + /** ATTRIBUTES **/ @JsonProperty("id") public String id; - @JsonProperty("state") public String state; - @JsonProperty("created") public Long created; - @JsonProperty("updated") public Long updated; - @JsonProperty("thread") public Thread thread; + @JsonProperty("isDigitalProductPass") + private boolean isDigitalProductPass; + /** CONSTRUCTOR(S) **/ public Process(String id, String state, Thread thread) { this.id = id; this.state = state; @@ -54,7 +58,6 @@ public Process(String id, String state, Thread thread) { this.updated = DateTimeUtil.getTimestamp(); this.thread = thread; } - public Process() { } public Process(String id, String state, Long created, Long updated) { @@ -69,14 +72,12 @@ public Process(String id, String state, Long created) { this.created = created; this.updated = DateTimeUtil.getTimestamp(); } - public Process(String id, String state) { this.id = id; this.state = state; this.created = DateTimeUtil.getTimestamp(); this.updated = DateTimeUtil.getTimestamp(); } - public Process(String id, String state, Long created, Long updated, Thread thread) { this.id = id; this.state = state; @@ -85,47 +86,42 @@ public Process(String id, String state, Long created, Long updated, Thread threa this.thread = thread; } - + /** GETTERS AND SETTERS **/ public String getId() { return id; } - public void setId(String id) { this.id = id; } - public String getState() { return state; } - public void setState(String state) { this.state = state; this.updated = DateTimeUtil.getTimestamp(); } - public Thread getThread() { return thread; } - public void setThread(Thread thread) { this.thread = thread; } - - - public Long getUpdated() { return updated; } - public void setUpdated(Long updated) { this.updated = updated; } - public Long getCreated() { return created; } - public void setCreated(Long created) { this.created = created; } + public boolean getIsDigitalProductPass() { + return isDigitalProductPass; + } + public void setIsDigitalProductPass(boolean isDigitalProductPass) { + this.isDigitalProductPass = isDigitalProductPass; + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/SearchStatus.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/SearchStatus.java index a6f939e70..4fb4bb09e 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/SearchStatus.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/SearchStatus.java @@ -27,6 +27,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import org.eclipse.tractusx.productpass.exceptions.ServiceException; import org.eclipse.tractusx.productpass.models.catenax.Dtr; import org.eclipse.tractusx.productpass.models.http.requests.Search; import utils.CrypUtil; @@ -34,81 +35,91 @@ import java.util.Map; +/** + * This class consists exclusively to define attributes and methods related to the DTR's search status. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class SearchStatus { + @JsonProperty("search") public Search search; - @JsonProperty("dtrs") public Map dtrs; - @JsonProperty("created") public Long created; - @JsonProperty("updated") public Long updated; + /** CONSTRUCTOR(S) **/ public SearchStatus(Search search, Map dtrs, Long created, Long updated) { this.search = search; this.dtrs = dtrs; this.created = created; this.updated = updated; } - public SearchStatus(Search search, Map dtrs){ this.search = search; this.dtrs = dtrs; Long timestamp = DateTimeUtil.getTimestamp(); this.updated = this.created = timestamp; } - - - public void addDtr(Dtr dtr) { - this.updated = DateTimeUtil.getTimestamp(); - this.dtrs.put( - CrypUtil.md5(dtr.getEndpoint()), // Use MD5 to identify the endpoint - dtr - ); - } - - public Dtr getDtr(String id) { - return this.dtrs.get(id); - } public SearchStatus() { this.dtrs = Map.of(); Long timestamp = DateTimeUtil.getTimestamp(); this.updated = this.created = timestamp; } + /** GETTERS AND SETTERS **/ public Search getSearch() { return search; } - public void setSearch(Search search) { this.search = search; } - public Map getDtrs() { return dtrs; } - public void setDtrs(Map dtrs) { this.dtrs = dtrs; } - public Long getCreated() { return created; } - public void setCreated(Long created) { this.created = created; } - public Long getUpdated() { return updated; } - public void setUpdated(Long updated) { this.updated = updated; } + + /** METHODS **/ + /** + * Gets the DTR with the given id from the DTR map object. + *

+ * @param id + * the {@code String} identification of the DTR. + * + * @return a {@code Dtr} object with the given id, if exists. + * + */ + public Dtr getDtr(String id) { + return this.dtrs.get(id); + } + /** + * Gets a new DTR into the DTR map object. + *

+ * @param dtr + * the {@code Dtr} object to add. + * + */ + public void addDtr(Dtr dtr) { + this.updated = DateTimeUtil.getTimestamp(); + this.dtrs.put( + CrypUtil.md5(dtr.getEndpoint()), // Use MD5 to identify the endpoint + dtr + ); + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/Status.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/Status.java index 95f8a9138..459ed8763 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/Status.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/Status.java @@ -33,30 +33,30 @@ import java.util.List; import java.util.Map; +/** + * This class consists exclusively to define attributes and methods related to the Process' status. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Status { + + /** ATTRIBUTES **/ @JsonProperty("id") public String id; - @JsonProperty("status") public String status; - @JsonProperty("created") public Long created; - @JsonProperty("modified") public Long modified; - - @JsonProperty("endpoint") public String endpoint; - @JsonProperty("bpn") public String bpn; - @JsonProperty("history") public Map history; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public Status(String id, String status, Long created, Long modified, String endpoint, Map history) { this.id = id; this.status = status; @@ -65,7 +65,7 @@ public Status(String id, String status, Long created, Long modified, String endp this.endpoint = endpoint; this.history = history; } - + @SuppressWarnings("Unused") public Status(String id, String status, Long modified, String endpoint, Map history) { this.id = id; this.status = status; @@ -74,7 +74,7 @@ public Status(String id, String status, Long modified, String endpoint, Map(); } - public Status(String id, String status, String endpoint, Long created, Long modified) { this.id = id; this.status = status; @@ -109,9 +109,10 @@ public Status(String id, String status, String endpoint, Long created, Long modi this.endpoint = endpoint; this.history = new HashMap(); } + @SuppressWarnings("Unused") public Status() { } - + @SuppressWarnings("Unused") public Status(String id, String status, Long created, Long modified) { this.id = id; this.status = status; @@ -119,6 +120,7 @@ public Status(String id, String status, Long created, Long modified) { this.modified = modified; this.history = new HashMap(); } + @SuppressWarnings("Unused") public Status(String id, String status, Long created, Long modified, String historyId, History history) { this.id = id; this.status = status; @@ -126,7 +128,7 @@ public Status(String id, String status, Long created, Long modified, String hist this.modified = modified; this.history = Map.of(historyId, history); } - + @SuppressWarnings("Unused") public Status(String id, String status, Long created, Long modified, String endpoint, String bpn, Map history) { this.id = id; this.status = status; @@ -136,7 +138,7 @@ public Status(String id, String status, Long created, Long modified, String endp this.bpn = bpn; this.history = history; } - + @SuppressWarnings("Unused") public Status(String id, String status, Long created, Long modified, String endpoint, String bpn) { this.id = id; this.status = status; @@ -146,6 +148,7 @@ public Status(String id, String status, Long created, Long modified, String endp this.bpn = bpn; this.history = new HashMap(); } + @SuppressWarnings("Unused") public Status(String id, String status, Long created, Long modified, String endpoint, String bpn, String historyId, History history) { this.id = id; this.status = status; @@ -155,55 +158,49 @@ public Status(String id, String status, Long created, Long modified, String endp this.bpn = bpn; this.history = Map.of(historyId, history); } + + /** GETTERS AND SETTERS **/ public String getId() { return id; } - public void setId(String id) { this.id = id; } - public String getStatus() { return status; } - public void setStatus(String status) { this.status = status; } - public Long getCreated() { return created; } - public void setCreated(Long created) { this.created = created; } - public Long getModified() { return modified; } - public void setModified(Long modified) { this.modified = modified; } - public Map getHistory() { return history; } public Boolean historyExists(String name) { return this.history.containsKey(name); } - public void setHistory(Map history) { this.history = history; } - public void setHistory(String name, History history) { this.history.put(name, history); } + @SuppressWarnings("Unused") public void deleteHistory() { this.history = new HashMap<>(); } + @SuppressWarnings("Unused") public Boolean removeHistory(String name) { if(!this.history.containsKey(name)){ return false; @@ -214,19 +211,15 @@ public Boolean removeHistory(String name) { public History getHistory(String name) { return this.history.getOrDefault(name, null); } - public String getEndpoint() { return endpoint; } - public void setEndpoint(String endpoint) { this.endpoint = endpoint; } - public String getBpn() { return this.bpn; } - public void setBpn(String bpn) { this.bpn = bpn; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Catalog.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Catalog.java index bceda66f7..db3393523 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Catalog.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Catalog.java @@ -33,24 +33,25 @@ import java.util.List; import java.util.Map; +/** + * This class consists exclusively to define attributes related to the Catalog's data. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Catalog extends DidDocument { + /** ATTRIBUTES **/ @JsonProperty("dcat:dataset") Object contractOffers; - @JsonProperty("dcat:service") DataService service; - @JsonProperty("edc:participantId") String participantId; - @JsonProperty("@context") JsonNode context; - @JsonIgnore protected Map contractOffersMap = new HashMap<>(); + /** CONSTRUCTOR(S) **/ public Catalog(String id, String type, Object contractOffers, DataService service, String participantId, JsonNode context) { super(id, type); this.contractOffers = contractOffers; @@ -58,52 +59,43 @@ public Catalog(String id, String type, Object contractOffers, DataService servic this.participantId = participantId; this.context = context; } - public Catalog(String id, String type) { super(id, type); } - public Catalog() { } - + /** GETTERS AND SETTERS **/ public Object getContractOffers() { return contractOffers; } - + @SuppressWarnings("Unused") public void setContractOffer(Object contractOffers) { this.contractOffers = contractOffers; } - + @SuppressWarnings("Unused") public Map getContractOffersMap() { return contractOffersMap; } - + @SuppressWarnings("Unused") public void setContractOffersMap(Map contractOffersMap) { this.contractOffersMap = contractOffersMap; } - - public DataService getService() { return service; } - public void setService(DataService service) { this.service = service; } - public String getParticipantId() { return participantId; } - public void setParticipantId(String participantId) { this.participantId = participantId; } - public JsonNode getContext() { return context; } - public void setContext(JsonNode context) { this.context = context; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/CatalogRequest.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/CatalogRequest.java index be1f539a5..c8dcd3f3c 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/CatalogRequest.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/CatalogRequest.java @@ -31,24 +31,30 @@ import java.util.List; +/** + * This class consists exclusively to define attributes related to the Catalog requests. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class CatalogRequest { + + /** ATTRIBUTES **/ @JsonProperty("@context") JsonNode context; @JsonProperty("protocol") String protocol; @JsonProperty("providerUrl") String providerUrl; - @JsonProperty("querySpec") QuerySpec querySpec; + /** CONSTRUCTOR(S) **/ public CatalogRequest(JsonNode context, String providerUrl, QuerySpec querySpec) { this.context = context; this.protocol = "dataspace-protocol-http"; this.providerUrl = providerUrl; this.querySpec = querySpec; } + public CatalogRequest(JsonNode context, String protocol, String providerUrl, QuerySpec querySpec) { this.context = context; this.protocol = protocol; @@ -59,18 +65,16 @@ public CatalogRequest(JsonNode context, String protocol, String providerUrl, Que public CatalogRequest() { } + /** GETTERS AND SETTERS **/ public JsonNode getContext() { return context; } - public void setContext(JsonNode context) { this.context = context; } - public String getProtocol() { return protocol; } - public void setProtocol(String protocol) { this.protocol = protocol; } @@ -91,26 +95,31 @@ public void setQuerySpec(QuerySpec querySpec) { this.querySpec = querySpec; } - + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes related to the Query specification of the Catalog request. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public static class QuerySpec { + /** ATTRIBUTES **/ @JsonProperty("filterExpression") List filterExpression; - - @JsonProperty("offset") Integer offset; - @JsonProperty("limit") Integer limit; - @JsonProperty("filter") String filter; - @JsonProperty("range") Range range; + @JsonProperty("sortField") + String sortField; + @JsonProperty("criterion") + String criterion; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public QuerySpec(Integer offset, Integer limit, String filter, Range range, String sortField, String criterion) { this.offset = offset; this.limit = limit; @@ -119,146 +128,151 @@ public QuerySpec(Integer offset, Integer limit, String filter, Range range, Stri this.sortField = sortField; this.criterion = criterion; } - public QuerySpec() { } - public List getFilterExpression() { - return filterExpression; - } - + /** GETTERS AND SETTERS **/ + @SuppressWarnings("Unused") + public List getFilterExpression() { return filterExpression; } public void setFilterExpression(List filterExpression) { this.filterExpression = filterExpression; } + @SuppressWarnings("Unused") + public Integer getOffset() { + return offset; + } + @SuppressWarnings("Unused") + public void setOffset(Integer offset) { + this.offset = offset; + } + @SuppressWarnings("Unused") + public Integer getLimit() { + return limit; + } + @SuppressWarnings("Unused") + public void setLimit(Integer limit) { + this.limit = limit; + } + @SuppressWarnings("Unused") + public String getFilter() { + return filter; + } + @SuppressWarnings("Unused") + public void setFilter(String filter) { + this.filter = filter; + } + @SuppressWarnings("Unused") + public Range getRange() { + return range; + } + @SuppressWarnings("Unused") + public void setRange(Range range) { + this.range = range; + } + @SuppressWarnings("Unused") + public String getSortField() { + return sortField; + } + @SuppressWarnings("Unused") + public void setSortField(String sortField) { + this.sortField = sortField; + } + @SuppressWarnings("Unused") + public String getCriterion() { + return criterion; + } + @SuppressWarnings("Unused") + public void setCriterion(String criterion) { + this.criterion = criterion; + } + + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes related to the filter expression property of the Query specification. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) - public static class FilterExpression{ + public static class FilterExpression { + + /** ATTRIBUTES **/ @JsonProperty("operandLeft") String operandLeft; - @JsonProperty("operator") String operator; - @JsonProperty("operandRight") String operandRight; + /** CONSTRUCTOR(S) **/ public FilterExpression(String operandLeft, String operator, String operandRight) { this.operandLeft = operandLeft; this.operator = operator; this.operandRight = operandRight; } - + @SuppressWarnings("Unused") public FilterExpression() { } + /** GETTERS AND SETTERS **/ + @SuppressWarnings("Unused") public String getOperandLeft() { return operandLeft; } - + @SuppressWarnings("Unused") public void setOperandLeft(String operandLeft) { this.operandLeft = operandLeft; } - + @SuppressWarnings("Unused") public String getOperator() { return operator; } - + @SuppressWarnings("Unused") public void setOperator(String operator) { this.operator = operator; } - + @SuppressWarnings("Unused") public String getOperandRight() { return operandRight; } - + @SuppressWarnings("Unused") public void setOperandRight(String operandRight) { this.operandRight = operandRight; } } + + /** + * This class consists exclusively to define attributes to specify the range property of the Query specification. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public static class Range { + + /** ATTRIBUTES **/ @JsonProperty("from") Integer from; - @JsonProperty("to") Integer to; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public Range(Integer from, Integer to) { this.from = from; this.to = to; } - + @SuppressWarnings("Unused") public Range() { } + /** GETTERS AND SETTERS **/ public Integer getFrom() { return from; } - public void setFrom(Integer from) { this.from = from; } - public Integer getTo() { return to; } - public void setTo(Integer to) { this.to = to; } } - - @JsonProperty("sortField") - String sortField; - - @JsonProperty("criterion") - String criterion; - public Integer getOffset() { - return offset; - } - - public void setOffset(Integer offset) { - this.offset = offset; - } - - public Integer getLimit() { - return limit; - } - - public void setLimit(Integer limit) { - this.limit = limit; - } - - public String getFilter() { - return filter; - } - - public void setFilter(String filter) { - this.filter = filter; - } - - public Range getRange() { - return range; - } - - public void setRange(Range range) { - this.range = range; - } - - public String getSortField() { - return sortField; - } - - public void setSortField(String sortField) { - this.sortField = sortField; - } - - public String getCriterion() { - return criterion; - } - - public void setCriterion(String criterion) { - this.criterion = criterion; - } - } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Constraint.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Constraint.java index df002a1b3..3524c0594 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Constraint.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Constraint.java @@ -30,11 +30,12 @@ import java.util.List; +@SuppressWarnings("Unused") @JsonInclude(JsonInclude.Include.NON_NULL) public class Constraint { + @JsonProperty("odrl:target") String target; - @JsonProperty("odrl:action") Action action; diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DataDestination.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DataDestination.java new file mode 100644 index 000000000..f46beaf7c --- /dev/null +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DataDestination.java @@ -0,0 +1,23 @@ +package org.eclipse.tractusx.productpass.models.negotiation; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This class consists exclusively to define attributes related to the Transfer's and Transfer request's data destination property. + **/ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DataDestination { + + /** ATTRIBUTES **/ + @JsonProperty("edc:type") + String type; + + /** GETTERS AND SETTERS **/ + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } +} diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DataService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DataService.java index 55794203f..f3fd16605 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DataService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DataService.java @@ -28,34 +28,37 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +/** + * This class consists exclusively to define attributes related to the Catalog's Data service property. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class DataService extends DidDocument { + + /** ATTRIBUTES **/ @JsonProperty("dct:terms") String terms; @JsonProperty("dct:endpointUrl") String endpoint; + /** CONSTRUCTOR(S) **/ public DataService(String id, String type, String terms, String endpoint) { super(id, type); this.terms = terms; this.endpoint = endpoint; } - public DataService() { } + /** GETTERS AND SETTERS **/ public String getTerms() { return terms; } - public void setTerms(String terms) { this.terms = terms; } - public String getEndpoint() { return endpoint; } - public void setEndpoint(String endpoint) { this.endpoint = endpoint; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Dataset.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Dataset.java index aae9d8041..7cc58c6a0 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Dataset.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Dataset.java @@ -29,25 +29,20 @@ import java.util.List; +/** + * This class consists exclusively to define attributes related to the Contract Offer's information data set. + **/ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) -public class Dataset extends DidDocument{ +public class Dataset extends DidDocument { + + /** ATTRIBUTES **/ @JsonProperty("odrl:hasPolicy") Object policy; @JsonProperty("dcat:distribution") List distributions; - @JsonProperty("edc:description") String assetDescription; - - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - @JsonProperty("edc:contenttype") String contentType; @JsonProperty("edc:id") @@ -57,6 +52,7 @@ public void setContentType(String contentType) { @JsonProperty("edc:type") String assetType; + /** CONSTRUCTOR(S) **/ public Dataset(String id, String type, Object policy, List distributions, String assetDescription, String contentType, String assetId) { super(id, type); this.policy = policy; @@ -74,7 +70,6 @@ public Dataset(String id, String type, Object policy, List distrib this.assetId = assetId; this.assetName = assetName; } - public Dataset(String id, String type, Object policy, List distributions, String assetDescription, String contentType, String assetId, String assetName, String assetType) { super(id, type); this.policy = policy; @@ -85,59 +80,60 @@ public Dataset(String id, String type, Object policy, List distrib this.assetName = assetName; this.assetType = assetType; } - public Dataset(String id, String type) { super(id, type); } - public Dataset() { } - + /** GETTERS AND SETTERS **/ + public String getContentType() { + return contentType; + } + public void setContentType(String contentType) { + this.contentType = contentType; + } public Object getPolicy() { return policy; } - public void setPolicy(Object policy) { this.policy = policy; } - + @SuppressWarnings("Unused") public List getDistributions() { return distributions; } - + @SuppressWarnings("Unused") public void setDistributions(List distributions) { this.distributions = distributions; } - + @SuppressWarnings("Unused") public String getAssetDescription() { return assetDescription; } - + @SuppressWarnings("Unused") public void setAssetDescription(String assetDescription) { this.assetDescription = assetDescription; } - public String getAssetId() { return assetId; } - public void setAssetId(String assetId) { this.assetId = assetId; } - + @SuppressWarnings("Unused") public String getAssetType() { return assetType; } - + @SuppressWarnings("Unused") public void setAssetType(String assetType) { this.assetType = assetType; } - + @SuppressWarnings("Unused") public String getAssetName() { return assetName; } - + @SuppressWarnings("Unused") public void setAssetName(String assetName) { this.assetName = assetName; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DidDocument.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DidDocument.java index df79e09bf..4bccc5a0d 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DidDocument.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/DidDocument.java @@ -28,33 +28,37 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +/** + * This class consists exclusively to define attributes that are common between the needed data objects for the Application. + * For example for Catalog, Dataset, Negotiation, etc. that extends this class. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class DidDocument { + + /** ATTRIBUTES **/ @JsonProperty("@id") String id; @JsonProperty("@type") String type; + /** CONSTRUCTOR(S) **/ public DidDocument(String id, String type) { this.id = id; this.type = type; } - public DidDocument() { } + /** GETTERS AND SETTERS **/ public String getId() { return id; } - public void setId(String id) { this.id = id; } - public String getType() { return type; } - public void setType(String type) { this.type = type; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Distribution.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Distribution.java index 6d626ebd5..77b2a0ec5 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Distribution.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Distribution.java @@ -28,65 +28,73 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +/** + * This class consists exclusively to define attributes related to the Dataset's distributions property. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Distribution { + + /** ATTRIBUTES **/ @JsonProperty("@type") String type; - @JsonProperty("dct:format") Format format; - @JsonProperty("dcat:accessService") String accessService; + /** CONSTRUCTOR(S) **/ public Distribution(String type, Format format, String accessService) { this.type = type; this.format = format; this.accessService = accessService; } - public Distribution() { } + /** GETTERS AND SETTERS **/ public String getType() { return type; } - public void setType(String type) { this.type = type; } - public Format getFormat() { return format; } - public void setFormat(Format format) { this.format = format; } - + @SuppressWarnings("Unused") public String getAccessService() { return accessService; } - + @SuppressWarnings("Unused") public void setAccessService(String accessService) { this.accessService = accessService; } - static class Format{ + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes related to the Distribution's format property. + **/ + static class Format { + /** ATTRIBUTES **/ @JsonProperty("@id") String id; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public Format(String id) { this.id = id; } - + @SuppressWarnings("Unused") public Format() { } + /** GETTERS AND SETTERS **/ public String getId() { return id; } - public void setId(String id) { this.id = id; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/EdcResponse.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/EdcResponse.java index 741d15f88..7871d03c5 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/EdcResponse.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/EdcResponse.java @@ -29,11 +29,11 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; +@SuppressWarnings("Unused") @JsonInclude(JsonInclude.Include.NON_NULL) public class EdcResponse extends DidDocument{ @JsonProperty("edc:createdAt") Integer createdAt; - @JsonProperty("@context") JsonNode context; diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Negotiation.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Negotiation.java index 740f5cb2c..5ad193c8a 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Negotiation.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Negotiation.java @@ -29,31 +29,32 @@ import java.util.List; +/** + * This class consists exclusively to define attributes related to the Negotiation's data. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Negotiation extends DidDocument { + + /** ATTRIBUTES **/ @JsonProperty("edc:type") String edcType; - @JsonProperty("edc:protocol") String protocol; - @JsonProperty("edc:state") String state; @JsonProperty("edc:errorDetail") String errorDetail; - @JsonProperty("edc:counterPartyAddress") String counterPartyAddress; - @JsonProperty("edc:callbackAddresses") List callbackAddresses; - @JsonProperty("edc:contractAgreementId") String contractAgreementId; - @JsonProperty("@context") JsonNode context; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public Negotiation(String id, String type, String edcType, String protocol, String state, String counterPartyAddress, List callbackAddresses, String contractAgreementId, JsonNode context) { super(id, type); this.edcType = edcType; @@ -64,7 +65,7 @@ public Negotiation(String id, String type, String edcType, String protocol, Stri this.contractAgreementId = contractAgreementId; this.context = context; } - + @SuppressWarnings("Unused") public Negotiation(String edcType, String protocol, String state, String counterPartyAddress, List callbackAddresses, String contractAgreementId, JsonNode context) { this.edcType = edcType; this.protocol = protocol; @@ -74,16 +75,14 @@ public Negotiation(String edcType, String protocol, String state, String counter this.contractAgreementId = contractAgreementId; this.context = context; } - - - + @SuppressWarnings("Unused") public Negotiation() { } - + @SuppressWarnings("Unused") public Negotiation(String id, String type) { super(id, type); } - + @SuppressWarnings("Unused") public Negotiation(String id, String type, String edcType, String protocol, String state, String errorDetail, String counterPartyAddress, List callbackAddresses, String contractAgreementId, JsonNode context) { super(id, type); this.edcType = edcType; @@ -96,66 +95,55 @@ public Negotiation(String id, String type, String edcType, String protocol, Stri this.context = context; } + + /** GETTERS AND SETTERS **/ + @SuppressWarnings("Unused") public String getEdcType() { return edcType; } - + @SuppressWarnings("Unused") public void setEdcType(String edcType) { this.edcType = edcType; } - public String getProtocol() { return protocol; } - public void setProtocol(String protocol) { this.protocol = protocol; } - public String getState() { return state; } - public void setState(String state) { this.state = state; } - public String getCounterPartyAddress() { return counterPartyAddress; } - public void setCounterPartyAddress(String counterPartyAddress) { this.counterPartyAddress = counterPartyAddress; } - public List getCallbackAddresses() { return callbackAddresses; } - public void setCallbackAddresses(List callbackAddresses) { this.callbackAddresses = callbackAddresses; } - public String getContractAgreementId() { return contractAgreementId; } - public void setContractAgreementId(String contractAgreementId) { this.contractAgreementId = contractAgreementId; } - public JsonNode getContext() { return context; } - public void setContext(JsonNode context) { this.context = context; } - public String getErrorDetail() { return errorDetail; } - public void setErrorDetail(String errorDetail) { this.errorDetail = errorDetail; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/NegotiationRequest.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/NegotiationRequest.java index 097f460d1..0b3a32de4 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/NegotiationRequest.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/NegotiationRequest.java @@ -27,28 +27,30 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; +/** + * This class consists exclusively to define attributes related to the Negotiation requests. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class NegotiationRequest { + /** ATTRIBUTES **/ @JsonProperty("@context") JsonNode context; - @JsonProperty("@type") String type; @JsonProperty("connectorAddress") String connectorAddress; @JsonProperty("protocol") String protocol; - @JsonProperty("connectorId") String connectorId; - @JsonProperty("providerId") String providerId; - @JsonProperty("offer") Offer offer; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public NegotiationRequest(JsonNode context, String connectorAddress, String protocol, String connectorId, String providerId, Offer offer) { this.context = context; this.type = "NegotiationInitiateRequestDto"; @@ -58,6 +60,7 @@ public NegotiationRequest(JsonNode context, String connectorAddress, String prot this.providerId = providerId; this.offer = offer; } + @SuppressWarnings("Unused") public NegotiationRequest(JsonNode context, String connectorAddress, String connectorId, String providerId, Offer offer) { this.context = context; this.type = "NegotiationInitiateRequestDto"; @@ -75,6 +78,7 @@ public NegotiationRequest(JsonNode context, String connectorAddress, String conn this.connectorId = connectorId; this.offer = offer; } + @SuppressWarnings("Unused") public NegotiationRequest(JsonNode context, String type, String connectorAddress, String protocol, String connectorId, String providerId, Offer offer) { this.context = context; this.type = type; @@ -84,63 +88,53 @@ public NegotiationRequest(JsonNode context, String type, String connectorAddress this.providerId = providerId; this.offer = offer; } - - + @SuppressWarnings("Unused") public NegotiationRequest() { } + /** GETTERS AND SETTERS **/ public String getConnectorId() { return connectorId; } - public void setConnectorId(String connectorId) { this.connectorId = connectorId; } - public String getConnectorAddress() { return connectorAddress; } - public void setConnectorAddress(String connectorAddress) { this.connectorAddress = connectorAddress; } - public Offer getOffer() { return offer; } - + @SuppressWarnings("Unused") public void setOffer(Offer offer) { this.offer = offer; } - public JsonNode getContext() { return context; } - public void setContext(JsonNode context) { this.context = context; } - public String getProtocol() { return protocol; } - public void setProtocol(String protocol) { this.protocol = protocol; } - + @SuppressWarnings("Unused") public String getProviderId() { return providerId; } - + @SuppressWarnings("Unused") public void setProviderId(String providerId) { this.providerId = providerId; } - public String getType() { return type; } - public void setType(String type) { this.type = type; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Offer.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Offer.java index 3969fe419..bd7d5fc16 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Offer.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Offer.java @@ -28,48 +28,46 @@ import java.util.List; +/** + * This class consists exclusively to define attributes related to the Offer's data. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Offer { + /** ATTRIBUTES **/ @JsonProperty("offerId") String offerId; - @JsonProperty("assetId") String assetId; - @JsonProperty("policy") Set policy; - + /** CONSTRUCTOR(S) **/ public Offer(String offerId, String assetId, Set policy) { this.offerId = offerId; this.assetId = assetId; this.policy = policy; } - public Offer() { } + /** GETTERS AND SETTERS **/ public String getOfferId() { return offerId; } - + @SuppressWarnings("Unused") public void setOfferId(String offerId) { this.offerId = offerId; } - public String getAssetId() { return assetId; } - public void setAssetId(String assetId) { this.assetId = assetId; } - public Set getPolicy() { return policy; } - public void setPolicy(Set policy) { this.policy = policy; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Properties.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Properties.java index d9c43d3bc..cd3b5db0d 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Properties.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Properties.java @@ -26,6 +26,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +@SuppressWarnings("Unused") @JsonInclude(JsonInclude.Include.NON_NULL) public class Properties { @JsonProperty("type") diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Set.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Set.java index cf002adf8..39431e422 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Set.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Set.java @@ -29,8 +29,13 @@ import java.util.List; +/** + * This class consists exclusively to define attributes related to the Policy's data. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) -public class Set extends DidDocument{ +public class Set extends DidDocument { + + /** ATTRIBUTES **/ @JsonProperty("odrl:permission") Object permissions; @JsonProperty("odrl:prohibition") @@ -40,6 +45,7 @@ public class Set extends DidDocument{ @JsonProperty("odrl:target") String target; + /** CONSTRUCTOR(S) **/ public Set(String id, String type, Object permissions, Object prohibitions, Object obligations, String target) { super(id, type); this.permissions = permissions; @@ -47,50 +53,44 @@ public Set(String id, String type, Object permissions, Object prohibitions, Obje this.obligations = obligations; this.target = target; } - public Set(Object permissions, Object prohibitions, Object obligations, String target) { this.permissions = permissions; this.prohibitions = prohibitions; this.obligations = obligations; this.target = target; } - public Set(String id, String type) { super(id, type); } - public Set() { } - + /** GETTERS AND SETTERS **/ public String getTarget() { return target; } - public void setTarget(String target) { this.target = target; } - public Object getPermissions() { return permissions; } - public void setPermissions(Object permissions) { this.permissions = permissions; } - + @SuppressWarnings("Unused") public Object getProhibitions() { return prohibitions; } - + @SuppressWarnings("Unused") public void setProhibitions(Object prohibitions) { this.prohibitions = prohibitions; } - + @SuppressWarnings("Unused") public Object getObligations() { return obligations; } - + @SuppressWarnings("Unused") public void setObligations(Object obligations) { this.obligations = obligations; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Transfer.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Transfer.java index e80c8210e..fa5491284 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Transfer.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/Transfer.java @@ -29,8 +29,13 @@ import java.util.List; +/** + * This class consists exclusively to define attributes related to the Transfer's data. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) -public class Transfer extends DidDocument{ +public class Transfer extends DidDocument { + + /** ATTRIBUTES **/ @JsonProperty("edc:state") String state; @JsonProperty("edc:stateTimestamp") @@ -39,22 +44,18 @@ public class Transfer extends DidDocument{ String errorDetail; @JsonProperty("edc:type") String edcType; - @JsonProperty("edc:callbackAddresses") List callbackAddresses; - @JsonProperty("edc:dataDestination") DataDestination dataDestination; - @JsonProperty("edc:dataRequest") DataRequest dataRequest; - @JsonProperty("edc:receiverHttpEndpoint") String receiverHttpEndpoint; - @JsonProperty("@context") JsonNode context; + /** CONSTRUCTOR(S) **/ public Transfer(String id, String type, String state, Long stateTimestamp, String edcType, List callbackAddresses, DataDestination dataDestination, DataRequest dataRequest, String receiverHttpEndpoint, JsonNode context) { super(id, type); this.state = state; @@ -66,7 +67,6 @@ public Transfer(String id, String type, String state, Long stateTimestamp, Strin this.receiverHttpEndpoint = receiverHttpEndpoint; this.context = context; } - public Transfer(String state, Long stateTimestamp, String edcType, List callbackAddresses, DataDestination dataDestination, DataRequest dataRequest, String receiverHttpEndpoint, JsonNode context) { this.state = state; this.stateTimestamp = stateTimestamp; @@ -77,14 +77,11 @@ public Transfer(String state, Long stateTimestamp, String edcType, List callbackAddresses, DataDestination dataDestination, DataRequest dataRequest, String receiverHttpEndpoint, JsonNode context) { super(id, type); this.state = state; @@ -98,124 +95,99 @@ public Transfer(String id, String type, String state, Long stateTimestamp, Strin this.context = context; } + /** GETTERS AND SETTERS **/ public String getState() { return state; } - public void setState(String state) { this.state = state; } - public Long getStateTimestamp() { return stateTimestamp; } - public void setStateTimestamp(Long stateTimestamp) { this.stateTimestamp = stateTimestamp; } - + @SuppressWarnings("Unused") public String getEdcType() { return edcType; } - + @SuppressWarnings("Unused") public void setEdcType(String edcType) { this.edcType = edcType; } - public List getCallbackAddresses() { return callbackAddresses; } - public void setCallbackAddresses(List callbackAddresses) { this.callbackAddresses = callbackAddresses; } - public DataDestination getDataDestination() { return dataDestination; } - public void setDataDestination(DataDestination dataDestination) { this.dataDestination = dataDestination; } - public DataRequest getDataRequest() { return dataRequest; } - public void setDataRequest(DataRequest dataRequest) { this.dataRequest = dataRequest; } - public String getReceiverHttpEndpoint() { return receiverHttpEndpoint; } - public void setReceiverHttpEndpoint(String receiverHttpEndpoint) { this.receiverHttpEndpoint = receiverHttpEndpoint; } - public JsonNode getContext() { return context; } - public void setContext(JsonNode context) { this.context = context; } - public String getErrorDetail() { return errorDetail; } - public void setErrorDetail(String errorDetail) { this.errorDetail = errorDetail; } + + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes related to the Transfer's data request property. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) - static class DataRequest extends DidDocument{ + static class DataRequest extends DidDocument { + + /** ATTRIBUTES **/ @JsonProperty("edc:assetId") String assetId; - @JsonProperty("edc:connectorId") String connectorId; - @JsonProperty("edc:contractId") String contractId; + /** GETTERS AND SETTERS **/ public String getAssetId() { return assetId; } - public void setAssetId(String assetId) { this.assetId = assetId; } - public String getContractId() { return contractId; } - public void setContractId(String contractId) { this.contractId = contractId; } - public String getConnectorId() { return connectorId; } - public void setConnectorId(String connectorId) { this.connectorId = connectorId; } } - @JsonInclude(JsonInclude.Include.NON_NULL) - static class DataDestination { - @JsonProperty("edc:type") - String type; - - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/TransferRequest.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/TransferRequest.java index 44f85b57b..5eec26999 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/TransferRequest.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/negotiation/TransferRequest.java @@ -26,19 +26,20 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; -import org.springframework.cglib.core.Block; - +/** + * This class consists exclusively to define attributes related to the Transfer requests. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class TransferRequest { + /** ATTRIBUTES **/ @JsonProperty("@context") JsonNode context; @JsonProperty("assetId") String assetId; @JsonProperty("connectorAddress") String connectorAddress; - @JsonProperty("connectorId") String connectorId; @JsonProperty("contractId") @@ -54,10 +55,10 @@ public class TransferRequest { @JsonProperty("transferType") TransferType transferType; + /** CONSTRUCTOR(S) **/ public TransferRequest() { } - public TransferRequest(JsonNode context, String assetId, String connectorAddress, String connectorId, String contractId, DataDestination dataDestination, Boolean managedResources, PrivateProperties privateProperties, String protocol, TransferType transferType) { this.context = context; this.assetId = assetId; @@ -71,133 +72,82 @@ public TransferRequest(JsonNode context, String assetId, String connectorAddress this.transferType = transferType; } + /** GETTERS AND SETTERS **/ public JsonNode getContext() { return context; } - public void setContext(JsonNode context) { this.context = context; } - public String getAssetId() { return assetId; } - public void setAssetId(String assetId) { this.assetId = assetId; } - public String getConnectorAddress() { return connectorAddress; } - public void setConnectorAddress(String connectorAddress) { this.connectorAddress = connectorAddress; } - - - public String getContractId() { - return contractId; - } - - public void setContractId(String contractId) { - this.contractId = contractId; - } - - public DataDestination getDataDestination() { - return dataDestination; - } - - public void setDataDestination(DataDestination dataDestination) { - this.dataDestination = dataDestination; - } - - public Boolean getManagedResources() { - return managedResources; - } - - public void setManagedResources(Boolean managedResources) { - this.managedResources = managedResources; - } - - public PrivateProperties getPrivateProperties() { - return privateProperties; - } - - public void setPrivateProperties(PrivateProperties privateProperties) { - this.privateProperties = privateProperties; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public TransferType getTransferType() { - return transferType; - } - - public void setTransferType(TransferType transferType) { - this.transferType = transferType; - } - - public String getConnectorId() { - return connectorId; - } - - public void setConnectorId(String connectorId) { - this.connectorId = connectorId; - } - + public String getContractId() { return contractId; } + public void setContractId(String contractId) { this.contractId = contractId; } + public DataDestination getDataDestination() { return dataDestination; } + public void setDataDestination(DataDestination dataDestination) { this.dataDestination = dataDestination; } + public Boolean getManagedResources() { return managedResources; } + public void setManagedResources(Boolean managedResources) { this.managedResources = managedResources; } + public PrivateProperties getPrivateProperties() { return privateProperties; } + public void setPrivateProperties(PrivateProperties privateProperties) { this.privateProperties = privateProperties; } + public String getProtocol() { return protocol; } + public void setProtocol(String protocol) { this.protocol = protocol; } + public TransferType getTransferType() { return transferType; } + public void setTransferType(TransferType transferType) { this.transferType = transferType; } + public String getConnectorId() { return connectorId; } + public void setConnectorId(String connectorId) { this.connectorId = connectorId; } + + /** INNER CLASSES **/ + /** + * This class consists exclusively to define attributes related to the Transfer request's transfer type property. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) - public static class TransferType{ + public static class TransferType { + + /** ATTRIBUTES **/ @JsonProperty("contentType") String contentType; @JsonProperty("isFinite") Boolean isFinite; + /** GETTERS AND SETTERS **/ public String getContentType() { return contentType; } - public void setContentType(String contentType) { this.contentType = contentType; } - public Boolean getIsFinite() { return isFinite; } - public void setIsFinite(Boolean isFinite) { this.isFinite = isFinite; } } - @JsonInclude(JsonInclude.Include.NON_NULL) - public static class DataDestination { - @JsonProperty("type") - String type; - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - } + /** + * This class consists exclusively to define attributes related to the Transfer request's private properties' attribute. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) - public static class PrivateProperties{ + public static class PrivateProperties { + + /** ATTRIBUTES **/ @JsonProperty("receiverHttpEndpoint") String receiverHttpEndpoint; + /** GETTERS AND SETTERS **/ public String getReceiverHttpEndpoint() { return receiverHttpEndpoint; } - public void setReceiverHttpEndpoint(String receiverHttpEndpoint) { this.receiverHttpEndpoint = receiverHttpEndpoint; } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/DigitalProductPassport.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/DigitalProductPassport.java new file mode 100644 index 000000000..297704ec8 --- /dev/null +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/DigitalProductPassport.java @@ -0,0 +1,34 @@ +package org.eclipse.tractusx.productpass.models.passports; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.JsonNode; + +/** + * This class consists exclusively to define attributes related to the designed model of the Digital Product Passport. + **/ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DigitalProductPassport extends Passport { + @JsonProperty("serialization") + JsonNode serialization; + @JsonProperty("typology") + JsonNode typology; + @JsonProperty("metadata") + String metadata; + @JsonProperty("characteristics") + JsonNode characteristics; + @JsonProperty("commercial") + JsonNode commercial; + @JsonProperty("identification") + JsonNode identification; + @JsonProperty("sources") + JsonNode sources; + @JsonProperty("handling") + JsonNode handling; + @JsonProperty("additionalData") + String additionalData; + @JsonProperty("sustainability") + JsonNode sustainability; + @JsonProperty("operation") + JsonNode operation; +} diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/Passport.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/Passport.java index f1f318d9b..778396700 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/Passport.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/Passport.java @@ -25,6 +25,10 @@ import com.fasterxml.jackson.annotation.JsonInclude; +/** + * This class consists exclusively to define attributes and methods that are common to the passports used in the Application. + * Also used to perform polymorphism in the Application with all the passports that extends it. + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class Passport { // Here will be included then next release Generic Passport Structure diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/PassportResponse.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/PassportResponse.java index ead99bce4..84d5e15e9 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/PassportResponse.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/PassportResponse.java @@ -28,22 +28,22 @@ import java.util.Map; - -/* - * Passport Response given to the consumer with data from the transaction - * and the passport - */ +/** + * This class consists exclusively to define attributes and methods needed for the Passport response given to the consumer + * with metadata from the transaction and the passport. + **/ public class PassportResponse { @JsonProperty("metadata") Map metadata; @JsonProperty("passport") Passport passport; + @SuppressWarnings("Unused") public PassportResponse(Map metadata, Passport passport) { this.metadata = metadata; this.passport = passport; } - + @SuppressWarnings("Unused") public PassportResponse() { } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/PassportV3.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/PassportV3.java index 76475470f..0af8ea6e7 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/PassportV3.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/passports/PassportV3.java @@ -27,16 +27,16 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; - -/* - * =======[DESCRIPTION]========================================================= - * Passport Semantic BAMM Version @v3.0.1 - * Aspect model URN: urn:bamm:io.catenax.battery.battery_pass:3.0.1#BatteryPass - * https://portal.int.demo.catena-x.net/semantichub/urn%3Abamm%3Aio.catenax.battery.battery_pass%3A3.0.1%23BatteryPass - * Flexible Structure (Abstraction from main attributes using JsonNodes) - * ============================================================================= - */ - +/** + * This class consists exclusively to define attributes related to the designed model of the Passport v3.0.1. + * + * * =======[DESCRIPTION]========================================================= + * * Passport Semantic BAMM Version @v3.0.1 + * * Aspect model URN: urn:bamm:io.catenax.battery.battery_pass:3.0.1#BatteryPass + * * https://portal.int.demo.catena-x.net/semantichub/urn%3Abamm%3Aio.catenax.battery.battery_pass%3A3.0.1%23BatteryPass + * * Flexible Structure (Abstraction from main attributes using JsonNodes) + * * ============================================================================= + **/ @JsonInclude(JsonInclude.Include.NON_NULL) public class PassportV3 extends Passport{ @@ -44,37 +44,28 @@ public class PassportV3 extends Passport{ JsonNode electrochemicalProperties; @JsonProperty("document") JsonNode document; - @JsonProperty("datePlacedOnMarket") String datePlacedOnMarket; - @JsonProperty("cellChemistry") JsonNode cellChemistry; @JsonProperty("physicalDimensions") JsonNode physicalDimensions; - @JsonProperty("temperatureRangeIdleState") JsonNode temperatureRangeIdleState; @JsonProperty("batteryCycleLife") JsonNode batteryCycleLife; @JsonProperty("manufacturer") JsonNode manufacturer; - @JsonProperty("warrantyPeriod") String warrantyPeriod; - @JsonProperty("composition") JsonNode composition; - @JsonProperty("manufacturing") JsonNode manufacturing; - @JsonProperty("batteryIdentification") JsonNode batteryIdentification; - @JsonProperty("stateOfBattery") JsonNode stateOfBattery; - @JsonProperty("cO2FootprintTotal") JsonNode cO2FootprintTotal; diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/service/BaseService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/service/BaseService.java index 547d0e822..6be8ec3f2 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/service/BaseService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/service/BaseService.java @@ -30,6 +30,10 @@ import java.util.List; +/** + * This abstract class consists exclusively to define methods that are common to a Service class in the Application. + * Implements the ServiceInitializationInterface and all Service classes extends this class. + **/ public abstract class BaseService implements ServiceInitializationInterface { public void checkEmptyVariables() throws ServiceInitializationException { diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AasService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AasService.java index 07506c674..26a557412 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AasService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AasService.java @@ -23,17 +23,13 @@ package org.eclipse.tractusx.productpass.services; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import jakarta.servlet.http.HttpServletRequest; -import org.apache.juli.logging.Log; import org.eclipse.tractusx.productpass.config.DtrConfig; import org.eclipse.tractusx.productpass.exceptions.ControllerException; import org.eclipse.tractusx.productpass.exceptions.ServiceException; import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; import org.eclipse.tractusx.productpass.managers.DtrSearchManager; -import org.eclipse.tractusx.productpass.managers.ProcessDataModel; import org.eclipse.tractusx.productpass.managers.ProcessManager; +import org.eclipse.tractusx.productpass.models.auth.JwtToken; import org.eclipse.tractusx.productpass.models.catenax.Dtr; import org.eclipse.tractusx.productpass.models.dtregistry.*; import org.eclipse.tractusx.productpass.models.edc.AssetSearch; @@ -41,46 +37,42 @@ import org.eclipse.tractusx.productpass.models.http.requests.Search; import org.eclipse.tractusx.productpass.models.manager.SearchStatus; import org.eclipse.tractusx.productpass.models.manager.Status; -import org.eclipse.tractusx.productpass.models.manager.Process; -import org.eclipse.tractusx.productpass.models.negotiation.Transfer; -import org.eclipse.tractusx.productpass.models.negotiation.TransferRequest; import org.eclipse.tractusx.productpass.models.service.BaseService; -import org.eclipse.tractusx.productpass.models.auth.JwtToken; -import org.sonarsource.scanner.api.internal.shaded.minimaljson.Json; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import utils.*; -import javax.xml.crypto.Data; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +/** + * This class consists exclusively of methods to operate on getting Digital Twins and Submodels. + * + *

The methods defined here are intended to do every needed operations to be able to get Digital Twins and the Submodels. + * + */ @Service public class AasService extends BaseService { + /** ATTRIBUTES **/ public String registryUrl; - public Boolean central; + public Boolean central; private final HttpUtil httpUtil; - private final JsonUtil jsonUtil; - private final DtrConfig dtrConfig; private final AuthenticationService authService; - Map apis; private DtrSearchManager dtrSearchManager; private ProcessManager processManager; - private DataTransferService dataService; + /** CONSTRUCTOR(S) **/ @Autowired public AasService(Environment env, HttpUtil httpUtil, JsonUtil jsonUtil, AuthenticationService authService, DtrConfig dtrConfig, DtrSearchManager dtrSearchManager, ProcessManager processManager, DataTransferService dataService) throws ServiceInitializationException { this.httpUtil = httpUtil; @@ -94,6 +86,11 @@ public AasService(Environment env, HttpUtil httpUtil, JsonUtil jsonUtil, Authent this.checkEmptyVariables(); } + /** METHODS **/ + + /** + * Initiates the main needed variables for the AasService by loading from the application's configuration file. + **/ public void init(Environment env) { this.registryUrl = dtrConfig.getCentralUrl(); this.central = dtrConfig.getCentral(); @@ -115,6 +112,13 @@ public void init(Environment env) { ); } + /** + * Creates a List of missing variables needed to this service. + *

+ * + * @return an {@code Arraylist} with the environment variables missing in the service's configuration. + * + */ @Override public List getEmptyVariables() { List missingVariables = new ArrayList<>(); @@ -131,6 +135,20 @@ public List getEmptyVariables() { return missingVariables; } + /** + * Searches a {@code Submodel} from a Digital Twin by a given position index. + *

+ * @param digitalTwin + * the {@code DigitalTwin} object with its submodels. + * @param position + * the {@code Integer} position index of the intended submodel. + * + * @return a {@code Submodel} object from the position index, if exists. + * + * @throws ServiceException + * if unable to find a submodel for the specified position index. + */ + @SuppressWarnings("Unused") public SubModel searchSubModelInDigitalTwinByIndex(DigitalTwin digitalTwin, Integer position) { try { SubModel subModel = this.getSubModelFromDigitalTwin(digitalTwin, position); @@ -145,6 +163,26 @@ public SubModel searchSubModelInDigitalTwinByIndex(DigitalTwin digitalTwin, Inte "It was not possible to get subModel!"); } } + + /** + * Searches a {@code DigitalTwin3} from a given position index containing the specified parameters. + *

+ * @param assetType + * the {@code String} type of the asset. + * @param assetId + * the {@code String} identification of the asset. + * @param position + * the {@code Integer} position index of the intended digital twin. + * @param registryUrl + * the {@code String} registry URL of the Digital Twin. + * @param edr + * the {@code DataPlaneEndpoint} object with the data plane needed parameters. + * + * @return a {@code DigitalTwin3} object from the position index, if exists. + * + * @throws ServiceException + * if unable to find a {@code DigitalTwin3} for the specified position index. + */ public DigitalTwin3 searchDigitalTwin3(String assetType, String assetId, Integer position, String registryUrl, DataPlaneEndpoint edr) { try { ArrayList digitalTwinIds = this.queryDigitalTwin(assetType, assetId, registryUrl, edr); @@ -172,6 +210,25 @@ public DigitalTwin3 searchDigitalTwin3(String assetType, String assetId, Integer } } + /** + * Searches a {@code DigitalTwin} from a given position index containing the specified parameters. + *

+ * @param assetType + * the {@code String} type of the asset. + * @param assetId + * the {@code String} identification of the asset. + * @param position + * the {@code Integer} position index of the intended digital twin. + * @param registryUrl + * the {@code String} registry URL of the Digital Twin. + * @param edr + * the {@code DataPlaneEndpoint} object with the data plane needed parameters. + * + * @return a {@code DigitalTwin} object from the position index, if exists. + * + * @throws ServiceException + * if unable to find a {@code DigitalTwin} for the specified position index. + */ public DigitalTwin searchDigitalTwin(String assetType, String assetId, Integer position, String registryUrl, DataPlaneEndpoint edr) { try { ArrayList digitalTwinIds = this.queryDigitalTwin(assetType, assetId, registryUrl, edr); @@ -199,7 +256,17 @@ public DigitalTwin searchDigitalTwin(String assetType, String assetId, Integer p } } - + /** + * Builds the endpoint for a given registry URL and context key. + *

+ * @param registryUrl + * the {@code String} registry URL of the intended endpoint. + * @param key + * the {@code String} key with the intended URLs context (e.g: "digitaltwin", "search", "submodel", etc). + * + * @return a {@code String} object with the built endpoint. + * + */ public String getPathEndpoint(String registryUrl, String key) { if (this.central || registryUrl == null || registryUrl.isEmpty()) { return (String) jsonUtil.getValue(this.apis, "central." + key, ".", null); @@ -207,6 +274,20 @@ public String getPathEndpoint(String registryUrl, String key) { String path = (String) jsonUtil.getValue(this.apis, "decentral." + key, ".", null); return path; } + + /** + * Searches a {@code Submodel3} from a Digital Twin by a given short identification. + *

+ * @param digitalTwin + * the {@code DigitalTwin3} object with its submodels. + * @param idShort + * the {@code String} short id of the intended submodel. + * + * @return a {@code Submodel3} object with the submodel found, if exists. + * + * @throws ServiceException + * if unable to find a the {@code Submodel3} for the given id. + */ public SubModel3 searchSubModel3ById(DigitalTwin3 digitalTwin, String idShort) { try { SubModel3 subModel = this.getSubModel3ById(digitalTwin, idShort); @@ -221,6 +302,49 @@ public SubModel3 searchSubModel3ById(DigitalTwin3 digitalTwin, String idShort) { "It was not possible to search submodel!"); } } + + /** + * Searches a {@code Submodel3} from a Digital Twin by a given semantic identification. + *

+ * @param digitalTwin + * the {@code DigitalTwin3} object with its submodels. + * @param semanticId + * the {@code String} semantic id of the intended submodel. + * + * @return a {@code Submodel3} object with the submodel found, if exists. + * + * @throws ServiceException + * if unable to find a the {@code Submodel3} for the given semantic id. + */ + public SubModel3 searchSubModel3BySemanticId(DigitalTwin3 digitalTwin, String semanticId) { + try { + SubModel3 subModel = this.getSubModel3BySemanticId(digitalTwin, semanticId); + LogUtil.printWarning("SUBMODEL3:\n" + jsonUtil.toJson(subModel, true)); + if (subModel == null) { + throw new ServiceException(this.getClass().getName() + "." + "searchSubModel3BySemanticId", + "It was not possible to get submodel in the selected position for the selected asset type and the the selected assetId"); + } + return subModel; + } catch (Exception e) { + throw new ServiceException(this.getClass().getName() + "." + "searchSubModel3ById", + e, + "It was not possible to search submodel!"); + } + } + + /** + * Searches a {@code Submodel} from a Digital Twin by a given short identification. + *

+ * @param digitalTwin + * the {@code DigitalTwin} object with its submodels. + * @param idShort + * the {@code String} short id of the intended submodel. + * + * @return a {@code Submodel} object with the submodel found, if exists. + * + * @throws ServiceException + * if unable to find a the {@code Submodel} for the given id. + */ public SubModel searchSubModelById(DigitalTwin digitalTwin, String idShort) { try { SubModel subModel = this.getSubModelById(digitalTwin, idShort); @@ -236,6 +360,23 @@ public SubModel searchSubModelById(DigitalTwin digitalTwin, String idShort) { } } + /** + * Searches a {@code Submodel} from a Digital Twin from a given position index containing the specified parameters. + *

+ * @param digitalTwin + * the {@code DigitalTwin} object with its submodels. + * @param position + * the {@code Integer} position index of the intended submodel. + * @param registryUrl + * the {@code String} registry URL of the Digital Twin. + * @param edr + * the {@code DataPlaneEndpoint} object with the data plane needed parameters. + * + * @return a {@code Submodel} object from the position index, if exists. + * + * @throws ServiceException + * if unable to find a {@code Submodel} for the specified position index. + */ public SubModel searchSubModel(DigitalTwin digitalTwin, Integer position, String registryUrl, DataPlaneEndpoint edr) { try { SubModel subModel = this.getSubModel(digitalTwin, position, registryUrl, edr); @@ -251,6 +392,21 @@ public SubModel searchSubModel(DigitalTwin digitalTwin, Integer position, String } } + /** + * Gets the {@code DigitalTwin3} of a given id. + *

+ * @param digitalTwinId + * the {@code String} identification of the digital twin. + * @param registryUrl + * the {@code String} registry URL of the Digital Twin. + * @param edr + * the {@code DataPlaneEndpoint} object with the data plane needed parameters. + * + * @return a {@code DigitalTwin3} object with the given id, if exists. + * + * @throws ServiceException + * if unable to find a {@code DigitalTwin3} for the specified id. + */ public DigitalTwin3 getDigitalTwin3(String digitalTwinId, String registryUrl, DataPlaneEndpoint edr) { try { String path = this.getPathEndpoint(registryUrl, "digitalTwin"); @@ -267,6 +423,22 @@ public DigitalTwin3 getDigitalTwin3(String digitalTwinId, String registryUrl, Da } } + + /** + * Gets the {@code DigitalTwin} of a given id. + *

+ * @param digitalTwinId + * the {@code String} identification of the digital twin. + * @param registryUrl + * the {@code String} registry URL of the Digital Twin. + * @param edr + * the {@code DataPlaneEndpoint} object with the data plane needed parameters. + * + * @return a {@code DigitalTwin} object with the given id, if exists. + * + * @throws ServiceException + * if unable to find a {@code DigitalTwin} for the specified id. + */ public DigitalTwin getDigitalTwin(String digitalTwinId, String registryUrl, DataPlaneEndpoint edr) { try { String path = this.getPathEndpoint(registryUrl, "digitalTwin"); @@ -284,6 +456,20 @@ public DigitalTwin getDigitalTwin(String digitalTwinId, String registryUrl, Data } + + /** + * Gets the {@code Submodel} from a Digital Twin from a given position index. + *

+ * @param digitalTwin + * the {@code DigitalTwin} object with its submodels. + * @param position + * the {@code Integer} position index of the intended submodel. + * + * @return a {@code Submodel} object from the position index, if exists. + * + * @throws ServiceException + * if unable to find a {@code Submodel} for the specified position index. + */ public SubModel getSubModelFromDigitalTwin(DigitalTwin digitalTwin, Integer position) { try { ArrayList subModels = digitalTwin.getSubmodelDescriptors(); @@ -299,6 +485,23 @@ public SubModel getSubModelFromDigitalTwin(DigitalTwin digitalTwin, Integer posi } } + /** + * Gets the {@code Submodel} from a Digital Twin from a given position index containing the specified parameters. + *

+ * @param digitalTwin + * the {@code DigitalTwin} object with its submodels. + * @param position + * the {@code Integer} position index of the intended submodel. + * @param registryUrl + * the {@code String} registry URL of the Digital Twin. + * @param edr + * the {@code DataPlaneEndpoint} object with the data plane needed parameters. + * + * @return a {@code Submodel} object from the position index, if exists. + * + * @throws ServiceException + * if unable to find a {@code Submodel} for the specified position index. + */ public SubModel getSubModel(DigitalTwin digitalTwin, Integer position, String registryUrl, DataPlaneEndpoint edr) { try { String path = this.getPathEndpoint(registryUrl, "digitalTwin"); @@ -317,6 +520,19 @@ public SubModel getSubModel(DigitalTwin digitalTwin, Integer position, String re } } + /** + * Gets the {@code Submodel3} from a Digital Twin by a given short identification. + *

+ * @param digitalTwin + * the {@code DigitalTwin3} object with its submodels. + * @param idShort + * the {@code String} short id of the intended submodel. + * + * @return a {@code Submodel3} object with the submodel found, if exists. + * + * @throws ServiceException + * if unable to find a the {@code Submodel3} for the given id. + */ public SubModel3 getSubModel3ById(DigitalTwin3 digitalTwin, String idShort) { try { ArrayList subModels = digitalTwin.getSubmodelDescriptors(); @@ -341,6 +557,56 @@ public SubModel3 getSubModel3ById(DigitalTwin3 digitalTwin, String idShort) { } } + /** + * Gets the {@code Submodel3} from a Digital Twin by a given semantic identification. + *

+ * @param digitalTwin + * the {@code DigitalTwin3} object with its submodels. + * @param semanticId + * the {@code String} semantic id of the intended submodel. + * + * @return a {@code Submodel3} object with the submodel found, if exists. + * + * @throws ServiceException + * if unable to find a the {@code Submodel3} for the given semantic id. + */ + public SubModel3 getSubModel3BySemanticId(DigitalTwin3 digitalTwin, String semanticId) { + try { + ArrayList subModels = digitalTwin.getSubmodelDescriptors(); + if (subModels.size() < 1) { + throw new ServiceException(this.getClass().getName() + "." + "getSubModel3ById", + "No subModel found in digitalTwin!"); + } + // Search for first subModel with matching idShort, if it fails gives null + SubModel3 subModel = subModels.stream().filter(s -> s.getSemanticId().getKeys().get("Submodel").equalsIgnoreCase(semanticId)).findFirst().orElse(null); + + if (subModel == null) { + // If the subModel idShort does not exist + throw new ServiceException(this.getClass().getName() + "." + "getSubModel3ById", + "SubModel for SemanticId not found!"); + } + // Return subModel if found + return subModel; + } catch (Exception e) { + throw new ServiceException(this.getClass().getName() + "." + "getSubModel3ById", + e, + "It was not possible to get subModel!"); + } + } + + /** + * Gets the {@code Submodel} from a Digital Twin by a given short identification. + *

+ * @param digitalTwin + * the {@code DigitalTwin} object with its submodels. + * @param idShort + * the {@code String} short id of the intended submodel. + * + * @return a {@code Submodel} object with the submodel found, if exists. + * + * @throws ServiceException + * if unable to find a the {@code Submodel} for the given id. + */ public SubModel getSubModelById(DigitalTwin digitalTwin, String idShort) { try { ArrayList subModels = digitalTwin.getSubmodelDescriptors(); @@ -365,6 +631,17 @@ public SubModel getSubModelById(DigitalTwin digitalTwin, String idShort) { } } + /** + * Builds an HTTP header with the authentication key and code from the EDR's token. + *

+ * @param edr + * the {@code DataPlaneEndpoint} object with the data plane information. + * + * @return an {@code HTTPHeaders} object set with authentication key and code. + * + * @throws ServiceException + * if unable to retrieve the token headers. + */ public HttpHeaders getTokenHeader(DataPlaneEndpoint edr) { try { // If the dtr is central we just need the token @@ -384,16 +661,32 @@ public HttpHeaders getTokenHeader(DataPlaneEndpoint edr) { } } + /** + * Gets the registry URL. + *

+ * @param url + * the {@code String} URL for the registry. + * + * @return a {@code String} object with the registry URL. + * + */ public String getRegistryUrl(String url) { - try { return (url == null || this.central || url.isEmpty()) ? this.registryUrl : url; - } catch (Exception e) { - // Do nothing - } - return this.registryUrl; } - + /** + * Searches for centralized Digital Twin Registries. + *

+ * @param processId + * the {@code String} identification of the process. + * @param searchBody + * the {@code Search} object with the Request Body of the HTTP request. + * + * @return an {@code AssetSearch} object with the connector address and the asset id of the DTR. + * + * @throws ServiceException + * if unable to search and/or find the DTR. + */ public AssetSearch centralDtrSearch(String processId, Search searchBody){ try { // Start Digital Twin Query @@ -442,12 +735,29 @@ public AssetSearch centralDtrSearch(String processId, Search searchBody){ "It was not possible to search and find digital twin"); } } + + /** + * Searches for decentralized Digital Twin Registries. + *

+ * @param processId + * the {@code String} identification of the process. + * @param searchBody + * the {@code Search} object with the Request Body of the HTTP request. + * + * @return an {@code AssetSearch} object with the connector address and the asset id of the DTR. + * + * @throws ServiceException + * if unable to search and/or find the DTR. + */ public AssetSearch decentralDtrSearch(String processId, Search searchBody){ try { Status status = this.processManager.getStatus(processId); SearchStatus searchStatus = this.processManager.setSearch(processId, searchBody); + LogUtil.printWarning("Decentral SearchStatus:\n" + jsonUtil.toJson(searchStatus, true)); for (String endpointId : searchStatus.getDtrs().keySet()) { Dtr dtr = searchStatus.getDtr(endpointId); + LogUtil.printWarning("EndpointId: " + endpointId); + LogUtil.printWarning("Decentral DTR:\n" + jsonUtil.toJson(dtr, true)); DataTransferService.DigitalTwinRegistryTransfer dtrTransfer = dataService.new DigitalTwinRegistryTransfer( processId, endpointId, @@ -455,6 +765,7 @@ public AssetSearch decentralDtrSearch(String processId, Search searchBody){ searchBody, dtr ); + LogUtil.printWarning("Decentral DTRTransfer:\n" + jsonUtil.toJson(dtrTransfer, true)); Thread thread = ThreadUtil.runThread(dtrTransfer, dtr.getEndpoint()); thread.join(Duration.ofSeconds(this.dtrConfig.getTimeouts().getTransfer())); } @@ -469,6 +780,7 @@ public AssetSearch decentralDtrSearch(String processId, Search searchBody){ return null; } status = this.processManager.getStatus(processId); + LogUtil.printWarning("STATUS:\n" + jsonUtil.toJson(status, true)); if(status.historyExists("digital-twin-found")){ return new AssetSearch(status.getHistory("digital-twin-found").getId(), status.getEndpoint()); }; @@ -480,37 +792,23 @@ public AssetSearch decentralDtrSearch(String processId, Search searchBody){ } } - public class DigitalTwinTimeout implements Runnable { - private ProcessManager processManager; - - private String processId; - - public DigitalTwinTimeout(ProcessManager processManager, String processId) { - this.processManager = processManager; - this.processId = processId; - } - - - @Override - public void run() { - this.waitForDigitalTwin(); - } - public void waitForDigitalTwin(){ - Status status = this.getStatus(); - while(!status.historyExists("digital-twin-found")){ - status = this.getStatus(); - if(status.getStatus().equals("FAILED")){ - break; - } - } - } - public Status getStatus(){ - return this.processManager.getStatus(this.processId); - } - } - - - + /** + * Gets the Digital Twin's ids list for a given asset type and id. + *

+ * @param assetType + * the {@code String} type of the asset. + * @param assetId + * the {@code String} identification of the asset. + * @param registryUrl + * the {@code String} registry URL of the Digital Twin. + * @param edr + * the {@code DataPlaneEndpoint} object with the data plane needed parameters. + * + * @return a {@code ArrayList} object list with the digital twin ids found. + * + * @throws ServiceException + * if unable to find any digital twin. + */ public ArrayList queryDigitalTwin(String assetType, String assetId, String registryUrl, DataPlaneEndpoint edr) { try { String path = this.getPathEndpoint(registryUrl, "search"); @@ -560,90 +858,140 @@ public ArrayList queryDigitalTwin(String assetType, String assetId, Stri } } + /** INNER CLASSES **/ + + public class DigitalTwinTimeout implements Runnable { + + /** ATTRIBUTES **/ + private ProcessManager processManager; + private String processId; + + /** CONSTRUCTOR(S) **/ + public DigitalTwinTimeout(ProcessManager processManager, String processId) { + this.processManager = processManager; + this.processId = processId; + } + + /** METHODS **/ + + /** + * This method is exclusively for the waiting for the response of a Digital Twin request. + * + *

It's a Thread level method from Runnable interface used to wait for the response of a Digital Twin request by the timeout period defined + * in the calling thread join method. This timeout is configured on the application's configuration variables. + * + */ + @Override + public void run() { + this.waitForDigitalTwin(); + } + + /** + * Method used to wait for the digital twin for a timeout period defined in a thread join. + **/ + public void waitForDigitalTwin(){ + Status status = this.getStatus(); + while(!status.historyExists("digital-twin-found")){ + status = this.getStatus(); + if(status.getStatus().equals("FAILED")){ + break; + } + } + } + + public Status getStatus(){ + return this.processManager.getStatus(this.processId); + } + } + public class DecentralDigitalTwinRegistryQueryById implements Runnable { + /** ATTRIBUTES **/ private DataPlaneEndpoint edr; private SubModel3 subModel; private DigitalTwin3 digitalTwin; - private final String assetId; private final String idType; - private final Integer dtIndex; - - private final String idShort; + private final String semanticId; + + /** CONSTRUCTOR(S) **/ public DecentralDigitalTwinRegistryQueryById(Search search, DataPlaneEndpoint edr) { this.assetId = search.getId(); this.idType = search.getIdType(); this.dtIndex = search.getDtIndex(); this.idShort = search.getIdShort(); this.edr = edr; + this.semanticId = search.getSemanticId(); } - @Override - public void run() { - this.setDigitalTwin(searchDigitalTwin3(this.getIdType(), this.getAssetId(), this.getDtIndex(), this.getEdr().getEndpoint(), this.getEdr())); - this.setSubModel(searchSubModel3ById(this.getDigitalTwin(), this.getIdShort())); - } - + /** GETTERS AND SETTERS **/ public DataPlaneEndpoint getEdr() { return edr; } - public void setEdr(DataPlaneEndpoint edr) { this.edr = edr; } - public SubModel3 getSubModel() { return subModel; } - public void setSubModel(SubModel3 subModel) { this.subModel = subModel; } - public DigitalTwin3 getDigitalTwin() { return digitalTwin; } - public void setDigitalTwin(DigitalTwin3 digitalTwin) { this.digitalTwin = digitalTwin; } - public String getAssetId() { return assetId; } - public String getIdType() { return idType; } - public Integer getDtIndex() { return dtIndex; } - public String getIdShort() { return idShort; } - } - - - + public String getSemanticId() { return semanticId; } + + /** METHODS **/ + + /** + * This method is exclusively to search for a digital twin and the submodel. + * + *

It's a Thread level method from Runnable interface and does the {@code DigitalTwin3} and {@code Submodel3} search, setting the results + * to this class object. + *

The submodel search it's done by the idShort or semanticId parameters depending on if it's a BatteryPass or DigitalProductPass search, respectively. + * + */ + @Override + public void run() { + this.setDigitalTwin(searchDigitalTwin3(this.getIdType(), this.getAssetId(), this.getDtIndex(), this.getEdr().getEndpoint(), this.getEdr())); + if (this.getIdShort().equalsIgnoreCase("digitalProductPass")) { + this.setSubModel(searchSubModel3BySemanticId(this.getDigitalTwin(), this.getSemanticId())); + } else { + this.setSubModel(searchSubModel3ById(this.getDigitalTwin(), this.getIdShort())); + } + } + } public class DigitalTwinRegistryQueryById implements Runnable { + + /** ATTRIBUTES **/ private SubModel subModel; private DigitalTwin digitalTwin; - private final String assetId; private final String idType; - private final Integer dtIndex; - - private final String idShort; + /** CONSTRUCTOR(S) **/ public DigitalTwinRegistryQueryById(Search search) { this.assetId = search.getId(); this.idType = search.getIdType(); @@ -651,74 +999,94 @@ public DigitalTwinRegistryQueryById(Search search) { this.idShort = search.getIdShort(); } - @Override - public void run() { - this.digitalTwin = searchDigitalTwin(this.idType, this.assetId, this.dtIndex, null, null); - this.subModel = searchSubModelById(this.digitalTwin, this.idShort); - } - + /** GETTERS AND SETTERS **/ public SubModel getSubModel() { return this.subModel; } - public DigitalTwin getDigitalTwin() { return this.digitalTwin; } - public void setSubModel(SubModel subModel) { this.subModel = subModel; } - public void setDigitalTwin(DigitalTwin digitalTwin) { this.digitalTwin = digitalTwin; } - public String getAssetId() { return assetId; } - public String getIdType() { return idType; } - public Integer getDtIndex() { return dtIndex; } - public String getIdShort() { return idShort; } + + /** METHODS **/ + + /** + * This method is exclusively to search for a digital twin and the submodel. + * + *

It's a Thread level method from Runnable interface and does the {@code DigitalTwin} and {@code Submodel} search, setting the results + * to this class object. + *

The submodel search it's done by the idShort. + * + */ + @Override + public void run() { + this.digitalTwin = searchDigitalTwin(this.idType, this.assetId, this.dtIndex, null, null); + this.subModel = searchSubModelById(this.digitalTwin, this.idShort); + } + } + @SuppressWarnings("Unused") public class DigitalTwinRegistryQuery implements Runnable { + + /** ATTRIBUTES **/ private SubModel subModel; private DigitalTwin digitalTwin; private final String assetId; private final String idType; - private final Integer dtIndex; + /** CONSTRUCTOR(S) **/ + @SuppressWarnings("Unused") public DigitalTwinRegistryQuery(String assetId, String idType, Integer dtIndex) { this.assetId = assetId; this.idType = idType; this.dtIndex = dtIndex; - - } - - @Override - public void run() { - this.digitalTwin = searchDigitalTwin(this.idType, this.assetId, this.dtIndex, null, null); - this.subModel = searchSubModel(this.digitalTwin, this.dtIndex, null, null); } + /** GETTERS AND SETTERS **/ + @SuppressWarnings("Unused") public SubModel getSubModel() { return this.subModel; } - + @SuppressWarnings("Unused") public DigitalTwin getDigitalTwin() { return this.digitalTwin; } + /** METHODS **/ + + /** + * This method is exclusively to search for a digital twin and the submodel. + * + *

It's a Thread level method from Runnable interface and does the {@code DigitalTwin} and {@code Submodel} search, setting the results + * to this class object. + *

The submodel search it's done by index position. + * + */ + @Override + public void run() { + this.digitalTwin = searchDigitalTwin(this.idType, this.assetId, this.dtIndex, null, null); + this.subModel = searchSubModel(this.digitalTwin, this.dtIndex, null, null); + } + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AuthenticationService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AuthenticationService.java index 8eb79bc59..a603cc08f 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AuthenticationService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AuthenticationService.java @@ -29,7 +29,6 @@ import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; import org.eclipse.tractusx.productpass.models.auth.JwtToken; import org.eclipse.tractusx.productpass.models.auth.UserInfo; -import org.eclipse.tractusx.productpass.models.edc.Jwt; import org.eclipse.tractusx.productpass.models.service.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; @@ -38,7 +37,6 @@ import org.springframework.stereotype.Service; import utils.HttpUtil; import utils.JsonUtil; -import utils.LogUtil; import java.util.ArrayList; import java.util.List; @@ -46,17 +44,17 @@ @Service public class AuthenticationService extends BaseService { + + /** ATTRIBUTES **/ private final VaultService vaultService; private final Environment env; - private final HttpUtil httpUtil; - private final JsonUtil jsonUtil; - public String tokenUri; public String clientId; public String clientSecret; + /** CONSTRUCTOR(S) **/ @Autowired public AuthenticationService(VaultService vaultService, Environment env, HttpUtil httpUtil, JsonUtil jsonUtil) throws ServiceInitializationException { this.vaultService = vaultService; @@ -66,25 +64,25 @@ public AuthenticationService(VaultService vaultService, Environment env, HttpUti this.init(env); this.checkEmptyVariables(List.of("clientId", "clientSecret")); } + + /** METHODS **/ + + /** + * Initiates the main needed variables for Authetication Service by loading from the environment variables. + **/ public void init(Environment env) { this.tokenUri = env.getProperty("configuration.keycloak.tokenUri", String.class, ""); } - @Override - public List getEmptyVariables() { - List missingVariables = new ArrayList<>(); - if (this.tokenUri.isEmpty()) { - missingVariables.add("tokenUri"); - } - if (clientId == null || clientId.isEmpty()) { - missingVariables.add("clientId"); - } - if (clientSecret == null || clientSecret.isEmpty()) { - missingVariables.add("clientSecret"); - } - return missingVariables; - } - + /** + * Gets the authentication token for the technical user. + *

+ * + * @return a {@code JwtToken} object with all token's authentication parameters. + * + * @throws ServiceException + * if unable to retrieve the token. + */ public JwtToken getToken(){ try{ this.clientId = (String) vaultService.getLocalSecret("client.id"); @@ -113,6 +111,16 @@ public JwtToken getToken(){ } } + /** + * Checks if the user is authenticated. + *

+ * @param jwtToken + * the {@code JwtToken} object regarding the authentication token. + * + * @return true if the user is authenticated, false otherwise. + * + */ + @SuppressWarnings("Unused") public Boolean isAuthenticated(String jwtToken){ UserInfo userInfo = null; try { @@ -122,6 +130,16 @@ public Boolean isAuthenticated(String jwtToken){ } return userInfo != null; } + + /** + * Checks if the user is authenticated. + *

+ * @param httpRequest + * the {@code HttpServletRequest} object representing the HTTP request. + * + * @return true if the user is authenticated, false otherwise. + * + */ public Boolean isAuthenticated(HttpServletRequest httpRequest){ String token = httpUtil.getAuthorizationToken(httpRequest); if(token == null){ @@ -148,6 +166,17 @@ public Boolean isAuthenticated(HttpServletRequest httpRequest){ return userInfo != null; } + /** + * Gets the user's information from the given token. + *

+ * @param jwtToken + * the {@code String} authentication token. + * + * @return a {@code UserInfo} object with the user's information. + * + * @throws ServiceException + * if unable to retrieve the user's information. + */ public UserInfo getUserInfo(String jwtToken){ try{ HttpHeaders headers = httpUtil.getHeadersWithToken(jwtToken); @@ -164,6 +193,25 @@ public UserInfo getUserInfo(String jwtToken){ } } - - + /** + * Creates a List of missing variables needed to proceed with the authentication. + *

+ * + * @return an {@code Arraylist} with the environment variables missing in the configuration for the authentication. + * + */ + @Override + public List getEmptyVariables() { + List missingVariables = new ArrayList<>(); + if (this.tokenUri.isEmpty()) { + missingVariables.add("tokenUri"); + } + if (clientId == null || clientId.isEmpty()) { + missingVariables.add("clientId"); + } + if (clientSecret == null || clientSecret.isEmpty()) { + missingVariables.add("clientSecret"); + } + return missingVariables; + } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/CatenaXService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/CatenaXService.java index 8a1a6f597..64649aeb3 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/CatenaXService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/CatenaXService.java @@ -34,7 +34,6 @@ import org.eclipse.tractusx.productpass.managers.DtrSearchManager; import org.eclipse.tractusx.productpass.models.catenax.BpnDiscovery; import org.eclipse.tractusx.productpass.models.catenax.Discovery; -import org.eclipse.tractusx.productpass.models.catenax.Dtr; import org.eclipse.tractusx.productpass.models.catenax.EdcDiscoveryEndpoint; import org.eclipse.tractusx.productpass.models.service.BaseService; import org.springframework.beans.factory.annotation.Autowired; @@ -47,37 +46,91 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +/** + * This class consists exclusively of methods to operate on executing Catena-X related operations. + * + *

The methods defined here are intended to do every needed operations related to Catena-X service in order to run the application. + * Like BPN and EDC discovery operations. + * + */ @Service public class CatenaXService extends BaseService { + /** ATTRIBUTES **/ private final HttpUtil httpUtil; - private final JsonUtil jsonUtil; private final FileUtil fileUtil; private final VaultService vaultService; private final DtrSearchManager dtrSearchManager; private final DataTransferService dataTransferService; - private final AuthenticationService authService; - private final DiscoveryConfig discoveryConfig; - private DtrConfig dtrConfig; private String discoveryEndpoint; - private List defaultDiscoveryKeys; + + /** CONSTRUCTOR(S) **/ + @Autowired + public CatenaXService(Environment env, FileUtil fileUtil, HttpUtil httpUtil, JsonUtil jsonUtil, VaultService vaultService, DtrSearchManager dtrSearchManager, AuthenticationService authService, DiscoveryConfig discoveryConfig, DataTransferService dataTransferService, DtrConfig dtrConfig) throws ServiceInitializationException { + this.httpUtil = httpUtil; + this.fileUtil = fileUtil; + this.jsonUtil = jsonUtil; + this.dtrConfig = dtrConfig; + this.vaultService = vaultService; + this.dtrSearchManager = dtrSearchManager; + this.authService = authService; + this.discoveryConfig = discoveryConfig; + this.dataTransferService = dataTransferService; + this.init(env); + this.checkEmptyVariables(); + } + + /** METHODS **/ + + /** + * Initiates the main needed variables for Catena-X Service by loading from the application's configuration file. + **/ + public void init(Environment env){ + this.discoveryEndpoint = this.discoveryConfig.getEndpoint(); + this.defaultDiscoveryKeys = List.of( + this.discoveryConfig.getBpn().getKey(), this.discoveryConfig.getEdc().getKey() + ); + } + + /** + * Checks if the empty variables are well configured. + *

+ * + * @throws ServiceInitializationException + * if unable to check initialize the service. + */ @Override public void checkEmptyVariables() throws ServiceInitializationException { super.checkEmptyVariables(); } + /** + * Checks if the empty variables are well configured. + *

+ * @param initializationOptionalVariables + * the {@code List} list of the initialization optional variables. + * + * @throws ServiceInitializationException + * if unable to check initialize the service. + */ @Override public void checkEmptyVariables(List initializationOptionalVariables) throws ServiceInitializationException { super.checkEmptyVariables(initializationOptionalVariables); } + /** + * Creates a List of missing variables needed to proceed with the authentication. + *

+ * + * @return an {@code Arraylist} with the environment variables missing in the configuration for the Catena-x service. + * + */ @Override public List getEmptyVariables() { List missingVariables = new ArrayList<>(); @@ -93,30 +146,24 @@ public List getEmptyVariables() { return missingVariables; } - public void init(Environment env){ - this.discoveryEndpoint = this.discoveryConfig.getEndpoint(); - this.defaultDiscoveryKeys = List.of( - this.discoveryConfig.getBpn().getKey(), this.discoveryConfig.getEdc().getKey() - ); - } - @Autowired - public CatenaXService(Environment env, FileUtil fileUtil, HttpUtil httpUtil, JsonUtil jsonUtil, VaultService vaultService, DtrSearchManager dtrSearchManager, AuthenticationService authService, DiscoveryConfig discoveryConfig, DataTransferService dataTransferService, DtrConfig dtrConfig) throws ServiceInitializationException { - this.httpUtil = httpUtil; - this.fileUtil = fileUtil; - this.jsonUtil = jsonUtil; - this.dtrConfig = dtrConfig; - this.vaultService = vaultService; - this.dtrSearchManager = dtrSearchManager; - this.authService = authService; - this.discoveryConfig = discoveryConfig; - this.dataTransferService = dataTransferService; - this.init(env); - this.checkEmptyVariables(); - } + /** + * Gets the default discovery endpoints. + *

+ * + * @return a {@code Discovery} object with discovery endpoints list. + * + */ public Discovery getDiscoveryEndpoints() { return this.getDiscoveryEndpoints(this.defaultDiscoveryKeys); // Get default discovery endpoints } + /** + * Initiates the default endpoints discovery. + *

+ * + * @return a {@code Discovery} object with discovery endpoints list, if exists. + * + */ public Discovery start(){ try { Discovery discovery = this.getDiscoveryEndpoints(); @@ -131,6 +178,18 @@ public Discovery start(){ } return null; } + + /** + * Adds a new entry to the discovery endpoints list for a given key. + *

+ * @param key + * the {@code String} key parameter to search the discovery endpoint. + * + * @return a {@code Discovery} object with discovery endpoints list updated. + * + * @throws ServiceException + * if unable to get the discovery endpoint for the given key. + */ public Discovery addEndpoint(String key){ try { Discovery discovery = this.getDiscoveryEndpoint(key); @@ -147,8 +206,19 @@ public Discovery addEndpoint(String key){ } } - - + /** + * Gets the discovery endpoint from the {@code Discovery} object for a given key. + *

+ * @param discovery + * the {@code Discovery} object containing the list of discovery endpoints. + * @param key + * the {@code String} key parameter to search the discovery endpoint. + * + * @return a {@code Discovery.Endpoint} object with the endpoint data found. + * + * @throws ServiceException + * if unable to get the endpoint for the given key. + */ public Discovery.Endpoint getDiscoveryEndpoint(Discovery discovery, String key) { List endpoints = discovery.getEndpoints(); Discovery.Endpoint responseEndpoint = endpoints.stream().filter(endpoint -> endpoint.getType().equals(key)).findAny().orElse(null); @@ -159,6 +229,20 @@ public Discovery.Endpoint getDiscoveryEndpoint(Discovery discovery, String key) return responseEndpoint; } + /** + * Updates the discovery endpoint from the {@code Discovery} object with a given key. + *

+ * @param discovery + * the {@code Discovery} object containing the list of discovery endpoints. + * @param key + * the {@code String} key parameter to update in the discovery endpoint. + * + * @return a {@code Discovery.Endpoint} object with the endpoint data found. + * + * @throws ServiceException + * if unable to get the endpoint for the given key. + */ + @SuppressWarnings("Unused") public Boolean updateDiscovery(Discovery discovery, String key){ try{ if(discovery.getEndpoints().isEmpty()){ @@ -174,6 +258,17 @@ public Boolean updateDiscovery(Discovery discovery, String key){ } } + /** + * Updates the given {@code Discovery} object with default discovery endpoints. + *

+ * @param discovery + * the {@code Discovery} object containing the list of discovery endpoints. + * + * @return true if the discovery was updated, false otherwise. + * + * @throws ServiceException + * if unable to update the discovery endpoints. + */ public Boolean updateDefaultDiscovery(Discovery discovery){ try{ if(discovery.getEndpoints().isEmpty()){ @@ -190,6 +285,19 @@ public Boolean updateDefaultDiscovery(Discovery discovery){ } } + /** + * Creates or Updates the endpoint with the given key in the vault, if exists. + *

+ * @param endpoint + * the {@code Discovery.Endpoint} object to update. + * @param key + * the {@code String} key parameter to update. + * + * @return true if the endpoint is successfully created/update, false otherwise. + * + * @throws ServiceException + * if unable to update the discovery endpoint. + */ public Boolean updateEndpointFile(Discovery.Endpoint endpoint, String key){ try { String address = endpoint.getEndpointAddress(); @@ -208,6 +316,19 @@ public Boolean updateEndpointFile(Discovery.Endpoint endpoint, String key){ } } + /** + * Creates or Updates BPN and EDC endpoints in the Vault. + *

+ * @param bpnEndpoint + * the {@code Discovery.Endpoint} object related to BPN. + * @param edcEndpoint + * the {@code Discovery.Endpoint} object related to EDC. + * + * @return true if both endpoints are successfully created/update, false otherwise. + * + * @throws ServiceException + * if unable to create/update the BPN and EDC endpoints. + */ public Boolean updateDefaultDiscoveryFile(Discovery.Endpoint bpnEndpoint, Discovery.Endpoint edcEndpoint){ try { Boolean bpnResponse = this.updateEndpointFile(bpnEndpoint, this.discoveryConfig.getBpn().getKey()); @@ -226,6 +347,17 @@ public Boolean updateDefaultDiscoveryFile(Discovery.Endpoint bpnEndpoint, Discov } } + /** + * Gets the Discovery endpoint for the given key, if exists. + *

+ * @param key + * the {@code String} key parameter to search. + * + * @return a {@code Discovery} object found. + * + * @throws ServiceException + * if unable to find the discovery endpoint. + */ public Discovery getDiscoveryEndpoint(String key) { try { return this.getDiscoveryEndpoints(List.of(key)); @@ -236,6 +368,17 @@ public Discovery getDiscoveryEndpoint(String key) { } } + /** + * Gets the Discovery endpoint for a given endpoints list. + *

+ * @param endpoints + * the {@code List} of endpoints to search. + * + * @return a {@code Discovery} object found containing the given endpoints. + * + * @throws ServiceException + * if unable to find the discovery endpoint. + */ public Discovery getDiscoveryEndpoints(List endpoints) { try { this.checkEmptyVariables(); @@ -257,6 +400,17 @@ public Discovery getDiscoveryEndpoints(List endpoints) { } } + /** + * Gets the EDC Discovery endpoints for a given BPNs list. + *

+ * @param bpns + * the {@code List} of BPNs list to search. + * + * @return a {@code List} object with the EDC discovery endpoints found. + * + * @throws ServiceException + * if unable to get the EDC discovery endpoints. + */ public List getEdcDiscovery(List bpns) { try { this.checkEmptyVariables(); @@ -285,6 +439,19 @@ public List getEdcDiscovery(List bpns) { } } + /** + * Gets the BPN discovery endpoint for a given id and id's type. + *

+ * @param id + * the {@code String} id to look up for the BPN. + * @param type + * the {@code String} type of the id. + * + * @return a {@code BpnDiscovery} object found with the BPN discovery endpoint data. + * + * @throws ServiceException + * if unable to get the BPN discovery endpoint. + */ public BpnDiscovery getBpnDiscovery(String id, String type){ try { this.checkEmptyVariables(); @@ -331,6 +498,19 @@ public BpnDiscovery getBpnDiscovery(String id, String type){ } } + /** + * Searches for all DTRs for a given edcEndpoints and updates the DTR data model of the given process accordingly. + *

+ * @param edcEndpoints + * the {@code List} of EDC endpoints to search. + * @param processId + * the {@code String} id of the application's process. + * + * @return a {@code BpnDiscovery} object found with the BPN discovery endpoint data. + * + * @throws ServiceException + * if unable to get the BPN discovery endpoint. + */ public void searchDTRs (List edcEndpoints, String processId) { try { Thread thread = ThreadUtil.runThread(dtrSearchManager.startProcess(edcEndpoints, processId), "ProcessDtrDataModel"); diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataPlaneService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataPlaneService.java index cba91bb2d..395f77895 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataPlaneService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataPlaneService.java @@ -25,8 +25,6 @@ import org.eclipse.tractusx.productpass.exceptions.ServiceException; import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.eclipse.tractusx.productpass.models.auth.JwtToken; -import org.eclipse.tractusx.productpass.models.dtregistry.DigitalTwin; import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; import org.eclipse.tractusx.productpass.models.passports.Passport; import org.eclipse.tractusx.productpass.models.passports.PassportV3; @@ -42,18 +40,39 @@ import java.util.List; import java.util.Map; +/** + * This class consists exclusively of methods to operate on executing the Data Plane operations. + * + *

The methods defined here are intended to do every needed operations in order to be able to transfer data or passport from Data Plane Endpoint. + * + */ @Service public class DataPlaneService extends BaseService { + /** ATTRIBUTES **/ @Autowired HttpUtil httpUtil; - @Autowired JsonUtil jsonUtil; + /** CONSTRUCTOR(S) **/ public DataPlaneService() throws ServiceInitializationException { this.checkEmptyVariables(); } + + /** METHODS **/ + + /** + * Gets the Transfer data from the given data plane endpoint. + *

+ * @param endpointData + * the {@code DataPlaneEndpoint} object with data plane endpoint data. + * + * @return a {@code Object} object with the body of the response. + * + * @throws ServiceException + * if unable to get the transfer data. + */ public Object getTransferData(DataPlaneEndpoint endpointData) { try { Map params = httpUtil.getParams(); @@ -67,6 +86,18 @@ public Object getTransferData(DataPlaneEndpoint endpointData) { "It was not possible to get transfer from transfer id ["+endpointData.getId()+"]"); } } + + /** + * Parses the Transfer Data to a Passport from the given data plane endpoint. + *

+ * @param endpointData + * the {@code DataPlaneEndpoint} object with data plane endpoint data. + * + * @return a {@code Passport} object parsed with transfer data. + * + * @throws ServiceException + * if unable to parse the data to the passport. + */ public Passport getPassport(DataPlaneEndpoint endpointData) { try { return (PassportV3) jsonUtil.bindObject(this.getTransferData(endpointData), PassportV3.class); @@ -77,6 +108,13 @@ public Passport getPassport(DataPlaneEndpoint endpointData) { } } + /** + * Creates an empty variables List. + *

+ * + * @return an empty {@code Arraylist}. + * + */ @Override public List getEmptyVariables() { return new ArrayList<>(); diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataTransferService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataTransferService.java index 830ef9479..76fb76662 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataTransferService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataTransferService.java @@ -24,8 +24,6 @@ package org.eclipse.tractusx.productpass.services; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.type.LogicalType; -import com.google.common.math.Stats; import org.eclipse.tractusx.productpass.config.DtrConfig; import org.eclipse.tractusx.productpass.exceptions.ControllerException; import org.eclipse.tractusx.productpass.exceptions.ServiceException; @@ -33,14 +31,12 @@ import org.eclipse.tractusx.productpass.managers.ProcessDataModel; import org.eclipse.tractusx.productpass.managers.ProcessManager; import org.eclipse.tractusx.productpass.models.catenax.Dtr; -import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; import org.eclipse.tractusx.productpass.models.http.requests.Search; import org.eclipse.tractusx.productpass.models.http.responses.IdResponse; import org.eclipse.tractusx.productpass.models.manager.History; import org.eclipse.tractusx.productpass.models.manager.Status; -import org.eclipse.tractusx.productpass.models.negotiation.*; -import org.eclipse.tractusx.productpass.models.negotiation.Properties; import org.eclipse.tractusx.productpass.models.negotiation.Set; +import org.eclipse.tractusx.productpass.models.negotiation.*; import org.eclipse.tractusx.productpass.models.passports.PassportV3; import org.eclipse.tractusx.productpass.models.service.BaseService; import org.springframework.beans.factory.annotation.Autowired; @@ -50,37 +46,36 @@ import org.springframework.stereotype.Service; import utils.*; -import javax.xml.crypto.Data; -import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; +/** + * This class consists exclusively of methods to operate on executing the Data Transfer operations. + * + *

The methods and inner classes defined here are intended to do every needed operations in order to be able to Transfer the Passport Data of a given request. + * + */ @Service public class DataTransferService extends BaseService { - + /** ATTRIBUTES **/ private final HttpUtil httpUtil; - private final JsonUtil jsonUtil; - public String apiKey; public String bpnNumber; - public String edcEndpoint; - public String managementPath; public String catalogPath; public String negotiationPath; public String transferPath; public Environment env; - public ProcessManager processManager; - public DtrConfig dtrConfig; + public DtrConfig dtrConfig; + /** CONSTRUCTOR(S) **/ @Autowired public DataTransferService(Environment env, HttpUtil httpUtil, JsonUtil jsonUtil, VaultService vaultService, ProcessManager processManager, DtrConfig dtrConfig) throws ServiceInitializationException { this.httpUtil = httpUtil; @@ -92,6 +87,11 @@ public DataTransferService(Environment env, HttpUtil httpUtil, JsonUtil jsonUtil this.checkEmptyVariables(List.of("apiKey")); // Add API Key as optional for initialization } + /** METHODS **/ + + /** + * Initiates the main needed variables for Data Transfer Service by loading from the environment variables and Vault. + **/ public void init(VaultService vaultService, Environment env) { this.apiKey = (String) vaultService.getLocalSecret("edc.apiKey"); this.bpnNumber = (String) vaultService.getLocalSecret("edc.participantId"); @@ -102,6 +102,13 @@ public void init(VaultService vaultService, Environment env) { this.transferPath = env.getProperty("configuration.edc.transfer", ""); } + /** + * Creates a List of missing variables needed to proceed with the request. + *

+ * + * @return an {@code Arraylist} with the environment variables missing in the configuration for the request. + * + */ @Override public List getEmptyVariables() { List missingVariables = new ArrayList<>(); @@ -129,6 +136,16 @@ public List getEmptyVariables() { return missingVariables; } + + /** + * Checks the EDC consumer connection by trying to establish a connection and retrieve an empty catalog. + *

+ * + * @return a {@code String} participantId of the retrieved catalog. + * + * @throws ControllerException + * if unable to check the EDC consumer connection. + */ public String checkEdcConsumerConnection() throws ControllerException { try { String edcConsumerDsp = this.edcEndpoint + CatenaXUtil.edcDataEndpoint; @@ -137,10 +154,24 @@ public String checkEdcConsumerConnection() throws ControllerException { throw new ControllerException(this.getClass().getName()+".checkEdcConsumerConnection", "The catalog response is null or the participant id is not set!"); } return catalog.getParticipantId(); - }catch (Exception e) { + } catch (Exception e) { throw new ControllerException(this.getClass().getName()+".checkEdcConsumerConnection", e, "It was not possible to establish connection with the EDC consumer endpoint [" + this.edcEndpoint+"]"); } } + + /** + * Gets the Contract Offer from the given AssetId in the given provider URL. + *

+ * @param assetId + * the {@code String} identification of the EDC's asset to lookup for. + * @param providerUrl + * the {@code String} provider URL of the asset. + * + * @return a {@code Dataset} object with the contract offer information. + * + * @throws ControllerException + * if unable to get the contract offer for the assetId. + */ public Dataset getContractOfferByAssetId(String assetId, String providerUrl) throws ControllerException { /* * This method receives the assetId and looks up for targets with the same name. @@ -178,6 +209,20 @@ public Dataset getContractOfferByAssetId(String assetId, String providerUrl) thr throw new ControllerException(this.getClass().getName(), e, "It was not possible to get Contract Offer for assetId [" + assetId + "]"); } } + + /** + * Builds a negotiation request with the given data. + *

+ * @param dataset + * the {@code Dataset} data for the contract offer. + * @param status + * the {@code Status} status of the process. + * @param bpn + * the {@code String} BPN number from BNP discovery for the request. + * + * @return a {@code NegotiationRequest} object with the given data. + * + */ public NegotiationRequest buildRequest(Dataset dataset, Status status, String bpn) { Offer contractOffer = this.buildOffer(dataset, 0); return new NegotiationRequest( @@ -187,6 +232,18 @@ public NegotiationRequest buildRequest(Dataset dataset, Status status, String bp contractOffer ); } + + /** + * Builds a negotiation request with the given data. + *

+ * @param dataset + * the {@code Dataset} data for the offer. + * @param defaultIndex + * the {@code Integer} default index for the policy. + * + * @return a {@code Offer} object with the given data built offer. + * + */ public Offer buildOffer(Dataset dataset, Integer defaultIndex) { Object rawPolicy = dataset.getPolicy(); Set policy = null; @@ -204,378 +261,176 @@ public Offer buildOffer(Dataset dataset, Integer defaultIndex) { policyCopy ); } - public class NegotiateContract implements Runnable { - private NegotiationRequest negotiationRequest; - private ProcessDataModel dataModel; - private Dataset dataset; - - private Negotiation negotiation; - private Transfer transfer; - private TransferRequest transferRequest; - private IdResponse negotiationResponse; - private IdResponse tranferResponse; - private Integer negotiationAttempts; - - private Integer transferAttempts; - private Status status; - - private String bpn; - - private String processId; + /** + * Gets the Contract Offer's Catalog from the provider. + *

+ * @param providerUrl + * the {@code String} URL from the provider. + * @param assetId + * the {@code String} identification of the EDC's asset. + * + * @return a {@code Catalog} object for the given AssetId . + * + * @throws ServiceException + * if unable to retrieve the catalog. + */ + public Catalog getContractOfferCatalog(String providerUrl, String assetId) { + try { + this.checkEmptyVariables(); - public NegotiateContract(ProcessDataModel dataModel, String processId, String bpn, Dataset dataset, Status status) { - this.dataModel = dataModel; - this.processId = processId; - this.dataset = dataset; - this.status = status; - this.bpn = bpn; - this.negotiationRequest = buildRequest(dataset, status, bpn); + String url = CatenaXUtil.buildManagementEndpoint(env, this.catalogPath); + // Simple catalog request query with no limitation. + CatalogRequest.QuerySpec querySpec = new CatalogRequest.QuerySpec(); + CatalogRequest.QuerySpec.FilterExpression filterExpression = new CatalogRequest.QuerySpec.FilterExpression( + "https://w3id.org/edc/v0.0.1/ns/id", + "=", + assetId + ); // Filter by asset id + querySpec.setFilterExpression(List.of(filterExpression)); + Object body = new CatalogRequest( + jsonUtil.newJsonNode(), + providerUrl, + querySpec + ); + HttpHeaders headers = httpUtil.getHeaders(); + headers.add("Content-Type", "application/json"); + headers.add("X-Api-Key", this.apiKey); + ResponseEntity response = httpUtil.doPost(url, JsonNode.class, headers, httpUtil.getParams(), body, false, false); + JsonNode result = (JsonNode) response.getBody(); + return (Catalog) jsonUtil.bindJsonNode(result, Catalog.class); + } catch (Exception e) { + throw new ServiceException(this.getClass().getName() + "." + "getContractOfferCatalog", + e, + "It was not possible to retrieve the catalog!"); } + } - public TransferRequest buildTransferRequest(Dataset dataset, Status status, Negotiation negotiation, String bpn) { - try { - Offer contractOffer = buildOffer(dataset, 0); - String receiverEndpoint = env.getProperty("configuration.edc.receiverEndpoint") + "/" + this.processId; // Send process Id to identification the session. - TransferRequest.TransferType transferType = new TransferRequest.TransferType(); - - transferType.setContentType("application/octet-stream"); - transferType.setIsFinite(true); - + /** + * Searches for the Digital Twin's Catalog from the provider. + *

+ * @param providerUrl + * the {@code String} URL from the provider. + * + * @return a {@code Catalog} object of the given provider, if exists. + * + * @throws ServiceException + * if unable to retrieve the catalog. + */ + public Catalog searchDigitalTwinCatalog(String providerUrl) throws ServiceException { + try { + this.checkEmptyVariables(); - TransferRequest.DataDestination dataDestination = new TransferRequest.DataDestination(); - dataDestination.setType("HttpProxy"); + String url = CatenaXUtil.buildManagementEndpoint(env, this.catalogPath); + // Simple catalog request query with no limitation. + CatalogRequest.QuerySpec querySpec = new CatalogRequest.QuerySpec(); + CatalogRequest.QuerySpec.FilterExpression filterExpression = new CatalogRequest.QuerySpec.FilterExpression( + "https://w3id.org/edc/v0.0.1/ns/id", + "=", + this.dtrConfig.getAssetId() + ); // Filter by asset id + querySpec.setFilterExpression(List.of(filterExpression)); + Object body = new CatalogRequest( + jsonUtil.newJsonNode(), + CatenaXUtil.buildDataEndpoint(providerUrl), + querySpec + ); - TransferRequest.PrivateProperties privateProperties = new TransferRequest.PrivateProperties(); - privateProperties.setReceiverHttpEndpoint(receiverEndpoint); - return new TransferRequest( - jsonUtil.toJsonNode(Map.of("odrl", "http://www.w3.org/ns/odrl/2/")), - dataset.getAssetId(), - status.getEndpoint(), - bpn, - negotiation.getContractAgreementId(), - dataDestination, - false, - privateProperties, - "dataspace-protocol-http", - transferType - ); - } catch (Exception e) { - throw new ServiceException(this.getClass().getName(), e, "Failed to build the transfer request!"); + HttpHeaders headers = httpUtil.getHeaders(); + headers.add("Content-Type", "application/json"); + headers.add("X-Api-Key", this.apiKey); + ResponseEntity response = httpUtil.doPost(url, JsonNode.class, headers, httpUtil.getParams(), body, false, false); + if(response == null){ + return null; } + JsonNode result = (JsonNode) response.getBody(); + return (Catalog) jsonUtil.bindJsonNode(result, Catalog.class); + } catch (Exception e) { + throw new ServiceException(this.getClass().getName() + "." + "getContractOfferCatalog", + e, + "It was not possible to retrieve the catalog!"); } + } - @Override - public void run() { - // NEGOTIATIONGIH PROCESS - try { - processManager.saveNegotiationRequest(processId, negotiationRequest, new IdResponse(processId, null), false); - this.negotiationResponse = this.requestNegotiation(this.negotiationRequest); - processManager.saveNegotiationRequest(processId, negotiationRequest, negotiationResponse, false); - this.negotiation = this.getNegotiationData(negotiationResponse); - if (this.negotiation == null) { - return; - } - processManager.saveNegotiation(this.processId, this.negotiation, false); - String state = this.negotiation.getState(); - if (!(state.equals("CONFIRMED") || state.equals("FINALIZED"))) { - throw new ServiceException(this.getClass().getName(), "Contract Negotiation Process Failed [" + this.negotiation.getId() + "]"); - } - } catch (Exception e) { - processManager.setStatus(this.processId, "negotiation-failed", new History( - this.processId, - "FAILED" - )); - this.dataModel.setState(processId, "FAILED"); - throw new ServiceException(this.getClass().getName(), e, "Failed to do the contract negotiation!"); - } - - if (this.dataModel.getState(processId).equals("TERMINATED")) { - LogUtil.printMessage("Terminated process " + processId + "stopped transfer!"); - return; - } - ; - this.dataModel.setState(processId, "NEGOTIATED"); - LogUtil.printStatus("[PROCESS " + this.processId + "] Negotiation Finished with status [" + negotiation.getState() + "]!"); - // TRANSFER PROCESS - try { - this.transferRequest = buildTransferRequest(this.dataset, this.status, this.negotiation, this.bpn); - processManager.saveTransferRequest(this.processId, transferRequest, new IdResponse(processId, null), false); - this.tranferResponse = this.requestTransfer(transferRequest); - processManager.saveTransferRequest(this.processId, transferRequest, this.tranferResponse, false); - this.transfer = this.getTransferData(this.tranferResponse); - if (this.transfer == null) { - return; - } - processManager.saveTransfer(this.processId, transfer, false); - if (!transfer.getState().equals("COMPLETED")) { - throw new ServiceException(this.getClass().getName(), "Transfer Process Failed [" + this.tranferResponse.getId() + "]"); - } - } catch (Exception e) { - processManager.setStatus(processId, "transfer-failed", new History( - processId, - "FAILED" - )); - this.dataModel.setState(processId, "FAILED"); - throw new ServiceException(this.getClass().getName(), e, "Failed to do the contract transfer"); - } - this.dataModel.setState(processId, "COMPLETED"); - LogUtil.printStatus("[PROCESS " + this.processId + "] Negotiation and Transfer Completed!"); + /** + * Initiates the Contract Negotiation in order to retrieve it. + *

+ * @param negotiationRequest + * the {@code NegotiationRequest} object with negotiation request data. + * + * @return a {@code IdResponse} object with the contract negotiation response. + * + * @throws ServiceException + * if unable to retrieve the contract negotiation. + */ + public IdResponse doContractNegotiation(NegotiationRequest negotiationRequest) { + try { + this.checkEmptyVariables(); + LogUtil.printDebug("[" + negotiationRequest.getOffer().getOfferId() + "] ===== [INITIALIZING CONTRACT NEGOTIATION] ==========================================="); + String url = CatenaXUtil.buildManagementEndpoint(env, this.negotiationPath); + HttpHeaders headers = httpUtil.getHeaders(); + headers.add("Content-Type", "application/json"); + headers.add("X-Api-Key", this.apiKey); + ResponseEntity response = httpUtil.doPost(url, JsonNode.class, headers, httpUtil.getParams(), negotiationRequest, false, false); + JsonNode result = (JsonNode) response.getBody(); + return (IdResponse) jsonUtil.bindJsonNode(result, IdResponse.class); + } catch (Exception e) { + throw new ServiceException(this.getClass().getName() + "." + "doContractNegotiations", + e, + "It was not possible to retrieve the contract negotiation!"); } + } - public Negotiation getNegotiationData(IdResponse negotiationResponse) { - Negotiation negotiation = null; - try { - negotiation = seeNegotiation(negotiationResponse.getId(), this.processId, this.dataModel); - } catch (Exception e) { - throw new ServiceException(this.getClass().getName(), e, "Failed to get the negotiation [" + negotiationResponse.getId() + "]"); - } - return negotiation; + /** + * Initiates the Contract Negotiation in order to retrieve it. + *

+ * @param contractOffer + * the {@code Offer} object with contract offer data. + * @param bpn + * the {@code String} BPN number from BNP discovery for the request. + * @param providerUrl + * the {@code String} URL from the provider. + * + * @return a {@code IdResponse} object with the contract negotiation response. + * + * @throws ServiceException + * if unable to retrieve the contract negotiation. + */ + public IdResponse doContractNegotiation(Offer contractOffer, String bpn, String providerUrl) { + try { + this.checkEmptyVariables(); + NegotiationRequest body = new NegotiationRequest( + jsonUtil.toJsonNode(Map.of("odrl", "http://www.w3.org/ns/odrl/2/")), + providerUrl, + bpn, + contractOffer + ); + return this.doContractNegotiation(body); + } catch (Exception e) { + throw new ServiceException(this.getClass().getName() + "." + "doContractNegotiations", + e, + "It was not possible to execute the contract negotiation!"); } + } - public IdResponse requestNegotiation(NegotiationRequest negotiationRequest) { - IdResponse negotiationResponse = null; - try { - negotiationResponse = doContractNegotiation(negotiationRequest); - } catch (Exception e) { - throw new ServiceException(this.getClass().getName(), e, "Failed to start the negotiation for offer [" + negotiationRequest.getOffer().getOfferId() + "]"); - } - - if (negotiationResponse.getId() == null) { - throw new ServiceException(this.getClass().getName(), "The ID from the Offer is null [" + negotiationRequest.getOffer().getOfferId() + "]"); - } - LogUtil.printMessage("[PROCESS " + this.processId + "] Negotiation Requested [" + negotiationResponse.getId() + "]"); - return negotiationResponse; - } - - public IdResponse requestTransfer(TransferRequest transferRequest) { - IdResponse transferResponse = null; - try { - transferResponse = initiateTransfer(transferRequest); - } catch (Exception e) { - throw new ServiceException(this.getClass().getName(), e, "Failed to start the transfer for contract [" + transferRequest.getContractId() + "]"); - } - if (transferResponse.getId() == null) { - throw new ServiceException(this.getClass().getName(), "The ID from the transfer is null for contract [" + transferRequest.getContractId() + "]"); - } - LogUtil.printStatus("[PROCESS " + this.processId + "] Transfer Requested [" + transferResponse.getId() + "]"); - return transferResponse; - } - - public Transfer getTransferData(IdResponse transferData) { - /*[8]=========================================*/ - // Check for transfer updates and the status - Transfer transfer = null; - try { - transfer = seeTransfer(transferData.getId(), this.processId, this.dataModel); - } catch (Exception e) { - throw new ServiceException(this.getClass().getName(), e, "Failed to get the negotiation [" + transferData.getId() + "]"); - } - return transfer; - } - - public void setNegotiationRequest(NegotiationRequest negotiationRequest) { - this.negotiationRequest = negotiationRequest; - } - - public Dataset getDataset() { - return dataset; - } - - public void setDataset(Dataset dataset) { - this.dataset = dataset; - } - - - - public Negotiation getNegotiation() { - return negotiation; - } - - public void setNegotiation(Negotiation negotiation) { - this.negotiation = negotiation; - } - - public NegotiationRequest getNegotiationRequest() { - return negotiationRequest; - } - - public ProcessDataModel getDataModel() { - return dataModel; - } - - public void setDataModel(ProcessDataModel dataModel) { - this.dataModel = dataModel; - } - - public Integer getNegotiationAttempts() { - return negotiationAttempts; - } - - public void setNegotiationAttempts(Integer negotiationAttempts) { - this.negotiationAttempts = negotiationAttempts; - } - - public Integer getTransferAttempts() { - return transferAttempts; - } - - public void setTransferAttempts(Integer transferAttempts) { - this.transferAttempts = transferAttempts; - } - - public Status getStatus() { - return status; - } - - public void setStatus(Status status) { - this.status = status; - } - - public String getProcessId() { - return processId; - } - - public void setProcessId(String processId) { - this.processId = processId; - } - - public Transfer getTransfer() { - return transfer; - } - - public void setTransfer(Transfer transfer) { - this.transfer = transfer; - } - - public TransferRequest getTransferRequest() { - return transferRequest; - } - - public void setTransferRequest(TransferRequest transferRequest) { - this.transferRequest = transferRequest; - } - - public IdResponse getNegotiationResponse() { - return negotiationResponse; - } - - public void setNegotiationResponse(IdResponse negotiationResponse) { - this.negotiationResponse = negotiationResponse; - } - - public IdResponse getTranferResponse() { - return tranferResponse; - } - - public void setTranferResponse(IdResponse tranferResponse) { - this.tranferResponse = tranferResponse; - } - } - - public Catalog getContractOfferCatalog(String providerUrl, String assetId) { - try { - this.checkEmptyVariables(); - - String url = CatenaXUtil.buildManagementEndpoint(env, this.catalogPath); - // Simple catalog request query with no limitation. - CatalogRequest.QuerySpec querySpec = new CatalogRequest.QuerySpec(); - CatalogRequest.QuerySpec.FilterExpression filterExpression = new CatalogRequest.QuerySpec.FilterExpression( - "https://w3id.org/edc/v0.0.1/ns/id", - "=", - assetId - ); // Filter by asset id - querySpec.setFilterExpression(List.of(filterExpression)); - Object body = new CatalogRequest( - jsonUtil.newJsonNode(), - providerUrl, - querySpec - ); - HttpHeaders headers = httpUtil.getHeaders(); - headers.add("Content-Type", "application/json"); - headers.add("X-Api-Key", this.apiKey); - ResponseEntity response = httpUtil.doPost(url, JsonNode.class, headers, httpUtil.getParams(), body, false, false); - JsonNode result = (JsonNode) response.getBody(); - return (Catalog) jsonUtil.bindJsonNode(result, Catalog.class); - } catch (Exception e) { - throw new ServiceException(this.getClass().getName() + "." + "getContractOfferCatalog", - e, - "It was not possible to retrieve the catalog!"); - } - } - public Catalog searchDigitalTwinCatalog(String providerUrl) throws ServiceException { - try { - this.checkEmptyVariables(); - - String url = CatenaXUtil.buildManagementEndpoint(env, this.catalogPath); - // Simple catalog request query with no limitation. - CatalogRequest.QuerySpec querySpec = new CatalogRequest.QuerySpec(); - CatalogRequest.QuerySpec.FilterExpression filterExpression = new CatalogRequest.QuerySpec.FilterExpression( - "https://w3id.org/edc/v0.0.1/ns/id", - "=", - this.dtrConfig.getAssetId() - ); // Filter by asset id - querySpec.setFilterExpression(List.of(filterExpression)); - Object body = new CatalogRequest( - jsonUtil.newJsonNode(), - CatenaXUtil.buildDataEndpoint(providerUrl), - querySpec - ); - - HttpHeaders headers = httpUtil.getHeaders(); - headers.add("Content-Type", "application/json"); - headers.add("X-Api-Key", this.apiKey); - ResponseEntity response = httpUtil.doPost(url, JsonNode.class, headers, httpUtil.getParams(), body, false, false); - if(response == null){ - return null; - } - JsonNode result = (JsonNode) response.getBody(); - return (Catalog) jsonUtil.bindJsonNode(result, Catalog.class); - } catch (Exception e) { - throw new ServiceException(this.getClass().getName() + "." + "getContractOfferCatalog", - e, - "It was not possible to retrieve the catalog!"); - } - } - - public IdResponse doContractNegotiation(NegotiationRequest negotiationRequest) { - try { - this.checkEmptyVariables(); - LogUtil.printDebug("[" + negotiationRequest.getOffer().getOfferId() + "] ===== [INITIALIZING CONTRACT NEGOTIATION] ==========================================="); - String url = CatenaXUtil.buildManagementEndpoint(env, this.negotiationPath); - HttpHeaders headers = httpUtil.getHeaders(); - headers.add("Content-Type", "application/json"); - headers.add("X-Api-Key", this.apiKey); - ResponseEntity response = httpUtil.doPost(url, JsonNode.class, headers, httpUtil.getParams(), negotiationRequest, false, false); - JsonNode result = (JsonNode) response.getBody(); - return (IdResponse) jsonUtil.bindJsonNode(result, IdResponse.class); - } catch (Exception e) { - throw new ServiceException(this.getClass().getName() + "." + "doContractNegotiations", - e, - "It was not possible to retrieve the contract negotiation!"); - } - } - - public IdResponse doContractNegotiations(Offer contractOffer, String bpn, String providerUrl) { - try { - this.checkEmptyVariables(); - NegotiationRequest body = new NegotiationRequest( - jsonUtil.toJsonNode(Map.of("odrl", "http://www.w3.org/ns/odrl/2/")), - providerUrl, - bpn, - contractOffer - ); - return this.doContractNegotiation(body); - } catch (Exception e) { - throw new ServiceException(this.getClass().getName() + "." + "doContractNegotiations", - e, - "It was not possible to execute the contract negotiation!"); - } - } - - public Negotiation seeNegotiation(String id, String processId, ProcessDataModel dataModel) { - try { - this.checkEmptyVariables(); + /** + * Gets the Negotiation data object from a Negotiation Response related to a Process. + *

+ * @param id + * the {@code String} id of the negotiation response. + * @param processId + * the {@code String} id of the application's process. + * @param dataModel + * the {@code ProcessDataModel} object of the process's data model. + * + * @return a {@code Negotiation} object with the negotiation data. + * + * @throws ServiceException + * if unable to see the negotiation. + */ + public Negotiation seeNegotiation(String id, String processId, ProcessDataModel dataModel) { + try { + this.checkEmptyVariables(); String endpoint = CatenaXUtil.buildManagementEndpoint(env, this.negotiationPath); // Get variables from configuration @@ -630,6 +485,18 @@ public Negotiation seeNegotiation(String id, String processId, ProcessDataModel "It was not possible to see the contract negotiation!"); } } + + /** + * Gets the Negotiation data object from a Negotiation Response. + *

+ * @param id + * the {@code String} id of the negotiation response. + * + * @return a {@code Negotiation} object with the negotiation data. + * + * @throws ServiceException + * if unable to see the negotiation. + */ public Negotiation seeNegotiation(String id) { try { this.checkEmptyVariables(); @@ -684,6 +551,17 @@ public Negotiation seeNegotiation(String id) { } } + /** + * Initiates a transfer regarding a transfer request. + *

+ * @param transferRequest + * the {@code TransferRequest} object with transfer request data. + * + * @return a {@code IdResponse} object with the transfer response. + * + * @throws ServiceException + * if unable to see the negotiation. + */ public IdResponse initiateTransfer(TransferRequest transferRequest) { try { this.checkEmptyVariables(); @@ -704,7 +582,17 @@ public IdResponse initiateTransfer(TransferRequest transferRequest) { } } - + /** + * Gets the Transfer data object from a Transfer Response. + *

+ * @param id + * the {@code String} id of the transfer response. + * + * @return a {@code Negotiation} object with the negotiation data. + * + * @throws ServiceException + * if unable to get the transfer data. + */ public Transfer seeTransfer(String id) { try { this.checkEmptyVariables(); @@ -754,7 +642,21 @@ public Transfer seeTransfer(String id) { } } - + /** + * Gets the Transfer data object from a Transfer Response related to a Process. + *

+ * @param id + * the {@code String} id of the transfer response. + * @param processId + * the {@code String} id of the application's process. + * @param dataModel + * the {@code ProcessDataModel} object of the process's data model. + * + * @return a {@code Negotiation} object with the negotiation data. + * + * @throws ServiceException + * if unable to get the transfer data. + */ public Transfer seeTransfer(String id, String processId, ProcessDataModel dataModel) { try { this.checkEmptyVariables(); @@ -808,7 +710,20 @@ public Transfer seeTransfer(String id, String processId, ProcessDataModel dataMo } } - + /** + * Gets the Passport version 3 from the Process. + *

+ * @param transferProcessId + * the {@code String} id of the target passport. + * @param endpoint + * the {@code String} endpoint URL of the target passport. + * + * @return a {@code PassportV3} object with the passport data. + * + * @throws ServiceException + * if unable to get the passport. + */ + @SuppressWarnings("Unused") public PassportV3 getPassportV3(String transferProcessId, String endpoint) { try { this.checkEmptyVariables(); @@ -832,31 +747,400 @@ public PassportV3 getPassportV3(String transferProcessId, String endpoint) { } } - /* - STATIC FUNCTIONS + /** STATIC METHODS **/ + + /** + * Gets the Passport version 3 from the Process. + *

+ * @param negotiation + * the {@code Negotiation} object for the request. + * @param connectorId + * the {@code String} identification of the connector. + * @param connectorAddress + * the {@code String} URL address the of the connector. + * + * @return a {@code PassportV3} object with the passport data. + * + * @throws ServiceException + * if unable to get the passport. */ + @SuppressWarnings("Unused") public static String generateTransferId(Negotiation negotiation, String connectorId, String connectorAddress) { return CrypUtil.sha256(DateTimeUtil.getDateTimeFormatted("yyyyMMddHHmmssSSS") + negotiation.getId() + connectorId + connectorAddress); } + /** INNER CLASSES **/ + + /** + * This inner class consists exclusively of methods to operate on executing the Contract Negotiation . + * + *

The methods defined here are intended to do every needed operation in order to be able to Negotiate the Contract. + * + */ + public class NegotiateContract implements Runnable { + + /** ATTRIBUTES **/ + private NegotiationRequest negotiationRequest; + private ProcessDataModel dataModel; + private Dataset dataset; + private Negotiation negotiation; + private Transfer transfer; + private TransferRequest transferRequest; + private IdResponse negotiationResponse; + private IdResponse tranferResponse; + private Integer negotiationAttempts; + private Integer transferAttempts; + private Status status; + private String bpn; + private String processId; + + /** CONSTRUCTOR(S) **/ + public NegotiateContract(ProcessDataModel dataModel, String processId, String bpn, Dataset dataset, Status status) { + this.dataModel = dataModel; + this.processId = processId; + this.dataset = dataset; + this.status = status; + this.bpn = bpn; + this.negotiationRequest = buildRequest(dataset, status, bpn); + } + + /** GETTERS AND SETTERS **/ + @SuppressWarnings("Unused") + public void setNegotiationRequest(NegotiationRequest negotiationRequest) { + this.negotiationRequest = negotiationRequest; + } + + public Dataset getDataset() { + return dataset; + } + + public void setDataset(Dataset dataset) { + this.dataset = dataset; + } + + public Negotiation getNegotiation() { + return negotiation; + } + + public void setNegotiation(Negotiation negotiation) { + this.negotiation = negotiation; + } + + @SuppressWarnings("Unused") + public NegotiationRequest getNegotiationRequest() { + return negotiationRequest; + } + + @SuppressWarnings("Unused") + public ProcessDataModel getDataModel() { + return dataModel; + } + + @SuppressWarnings("Unused") + public void setDataModel(ProcessDataModel dataModel) { + this.dataModel = dataModel; + } + + @SuppressWarnings("Unused") + public Integer getNegotiationAttempts() { + return negotiationAttempts; + } + + @SuppressWarnings("Unused") + public void setNegotiationAttempts(Integer negotiationAttempts) { + this.negotiationAttempts = negotiationAttempts; + } + + @SuppressWarnings("Unused") + public Integer getTransferAttempts() { + return transferAttempts; + } + + @SuppressWarnings("Unused") + public void setTransferAttempts(Integer transferAttempts) { + this.transferAttempts = transferAttempts; + } + + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + public String getProcessId() { + return processId; + } + + public void setProcessId(String processId) { + this.processId = processId; + } + + public Transfer getTransfer() { + return transfer; + } + + public void setTransfer(Transfer transfer) { + this.transfer = transfer; + } + + @SuppressWarnings("Unused") + public TransferRequest getTransferRequest() { + return transferRequest; + } + + @SuppressWarnings("Unused") + public void setTransferRequest(TransferRequest transferRequest) { + this.transferRequest = transferRequest; + } + + @SuppressWarnings("Unused") + public IdResponse getNegotiationResponse() { + return negotiationResponse; + } + + @SuppressWarnings("Unused") + public void setNegotiationResponse(IdResponse negotiationResponse) { + this.negotiationResponse = negotiationResponse; + } + + @SuppressWarnings("Unused") + public IdResponse getTranferResponse() { + return tranferResponse; + } + + @SuppressWarnings("Unused") + public void setTranferResponse(IdResponse tranferResponse) { + this.tranferResponse = tranferResponse; + } + + /** METHODS **/ + + /** + * Builds a transfer request with the given data. + *

+ * @param dataset + * the {@code Dataset} data for the contract offer. + * @param status + * the {@code Status} object of the process. + * @param negotiation + * the {@code Negotiation} object for the request. + * @param bpn + * the {@code String} BPN number from BNP discovery for the request. + * + * @return a {@code TransferRequest} object with the given data. + * + * @throws ServiceException + * if unable to build the transfer request. + */ + public TransferRequest buildTransferRequest(Dataset dataset, Status status, Negotiation negotiation, String bpn) { + try { + String receiverEndpoint = env.getProperty("configuration.edc.receiverEndpoint") + "/" + this.processId; // Send process Id to identification the session. + TransferRequest.TransferType transferType = new TransferRequest.TransferType(); + + transferType.setContentType("application/octet-stream"); + transferType.setIsFinite(true); + + + DataDestination dataDestination = new DataDestination(); + dataDestination.setType("HttpProxy"); + + TransferRequest.PrivateProperties privateProperties = new TransferRequest.PrivateProperties(); + privateProperties.setReceiverHttpEndpoint(receiverEndpoint); + return new TransferRequest( + jsonUtil.toJsonNode(Map.of("odrl", "http://www.w3.org/ns/odrl/2/")), + dataset.getAssetId(), + status.getEndpoint(), + bpn, + negotiation.getContractAgreementId(), + dataDestination, + false, + privateProperties, + "dataspace-protocol-http", + transferType + ); + } catch (Exception e) { + throw new ServiceException(this.getClass().getName(), e, "Failed to build the transfer request!"); + } + } + + /** + * This method is exclusively for the Negotiation Process. + * + *

It's a Thread level method from Runnable interface and does the Negotiation Request, gets the Negotiation Response and saves in the Process. + * Also builds Transfer Request, and gets the data from the Transfer Response and save it in the Process. + * + * @throws ServiceException + * if unable to do the negotiation and/or transferring the data. + */ + @Override + public void run() { + // NEGOTIATION PROCESS + try { + processManager.saveNegotiationRequest(processId, negotiationRequest, new IdResponse(processId, null), false); + this.negotiationResponse = this.requestNegotiation(this.negotiationRequest); + processManager.saveNegotiationRequest(processId, negotiationRequest, negotiationResponse, false); + this.negotiation = this.getNegotiationData(negotiationResponse); + if (this.negotiation == null) { + return; + } + processManager.saveNegotiation(this.processId, this.negotiation, false); + String state = this.negotiation.getState(); + if (!(state.equals("CONFIRMED") || state.equals("FINALIZED"))) { + throw new ServiceException(this.getClass().getName(), "Contract Negotiation Process Failed [" + this.negotiation.getId() + "]"); + } + } catch (Exception e) { + processManager.setStatus(this.processId, "negotiation-failed", new History( + this.processId, + "FAILED" + )); + this.dataModel.setState(processId, "FAILED"); + throw new ServiceException(this.getClass().getName(), e, "Failed to do the contract negotiation!"); + } + + if (this.dataModel.getState(processId).equals("TERMINATED")) { + LogUtil.printMessage("Terminated process " + processId + "stopped transfer!"); + return; + } + ; + this.dataModel.setState(processId, "NEGOTIATED"); + LogUtil.printStatus("[PROCESS " + this.processId + "] Negotiation Finished with status [" + negotiation.getState() + "]!"); + // TRANSFER PROCESS + try { + this.transferRequest = buildTransferRequest(this.dataset, this.status, this.negotiation, this.bpn); + processManager.saveTransferRequest(this.processId, transferRequest, new IdResponse(processId, null), false); + this.tranferResponse = this.requestTransfer(transferRequest); + processManager.saveTransferRequest(this.processId, transferRequest, this.tranferResponse, false); + this.transfer = this.getTransferData(this.tranferResponse); + if (this.transfer == null) { + return; + } + processManager.saveTransfer(this.processId, transfer, false); + if (!transfer.getState().equals("COMPLETED")) { + throw new ServiceException(this.getClass().getName(), "Transfer Process Failed [" + this.tranferResponse.getId() + "]"); + } + } catch (Exception e) { + processManager.setStatus(processId, "transfer-failed", new History( + processId, + "FAILED" + )); + this.dataModel.setState(processId, "FAILED"); + throw new ServiceException(this.getClass().getName(), e, "Failed to do the contract transfer"); + } + this.dataModel.setState(processId, "COMPLETED"); + LogUtil.printStatus("[PROCESS " + this.processId + "] Negotiation and Transfer Completed!"); + } + + /** + * Gets the Negotiation data from the Negotiation Response. + *

+ * @param negotiationResponse + * the {@code IdResponse} object with negotiation response. + * + * @return a {@code Negotiation} object with the negotiation data. + * + * @throws ServiceException + * if unable to get negotiation data. + */ + public Negotiation getNegotiationData(IdResponse negotiationResponse) { + Negotiation negotiation = null; + try { + negotiation = seeNegotiation(negotiationResponse.getId(), this.processId, this.dataModel); + } catch (Exception e) { + throw new ServiceException(this.getClass().getName(), e, "Failed to get the negotiation [" + negotiationResponse.getId() + "]"); + } + return negotiation; + } + + /** + * Starts the negotiation by requesting it. + *

+ * @param negotiationRequest + * the {@code NegotiationRequest} object with negotiation request data. + * + * @return a {@code IdResponse} object with the negotiation response. + * + * @throws ServiceException + * if unable to request the negotiation. + */ + public IdResponse requestNegotiation(NegotiationRequest negotiationRequest) { + IdResponse negotiationResponse = null; + try { + negotiationResponse = doContractNegotiation(negotiationRequest); + } catch (Exception e) { + throw new ServiceException(this.getClass().getName(), e, "Failed to start the negotiation for offer [" + negotiationRequest.getOffer().getOfferId() + "]"); + } + + if (negotiationResponse.getId() == null) { + throw new ServiceException(this.getClass().getName(), "The ID from the Offer is null [" + negotiationRequest.getOffer().getOfferId() + "]"); + } + LogUtil.printMessage("[PROCESS " + this.processId + "] Negotiation Requested [" + negotiationResponse.getId() + "]"); + return negotiationResponse; + } + + /** + * Starts the transfer by requesting it. + *

+ * @param transferRequest + * the {@code TransferRequest} object with transfer request data. + * + * @return a {@code IdResponse} object with the transfer response. + * + * @throws ServiceException + * if unable to request the transfer. + */ + public IdResponse requestTransfer(TransferRequest transferRequest) { + IdResponse transferResponse = null; + try { + transferResponse = initiateTransfer(transferRequest); + } catch (Exception e) { + throw new ServiceException(this.getClass().getName(), e, "Failed to start the transfer for contract [" + transferRequest.getContractId() + "]"); + } + if (transferResponse.getId() == null) { + throw new ServiceException(this.getClass().getName(), "The ID from the transfer is null for contract [" + transferRequest.getContractId() + "]"); + } + LogUtil.printStatus("[PROCESS " + this.processId + "] Transfer Requested [" + transferResponse.getId() + "]"); + return transferResponse; + } + + /** + * Gets the Transfer data from the response. + *

+ * @param transferResponse + * the {@code IdResponse} object with transfer response data. + * + * @return a {@code Transfer} object with the transfer data. + * + * @throws ServiceException + * if unable to get the transfer data. + */ + public Transfer getTransferData(IdResponse transferResponse) { + /*[8]=========================================*/ + // Check for transfer updates and the status + Transfer transfer = null; + try { + transfer = seeTransfer(transferResponse.getId(), this.processId, this.dataModel); + } catch (Exception e) { + throw new ServiceException(this.getClass().getName(), e, "Failed to get the transfer data [" + transferResponse.getId() + "]"); + } + return transfer; + } + } + public class DigitalTwinRegistryTransfer implements Runnable{ + /** ATTRIBUTES **/ Dtr dtr; - TransferRequest dtrRequest; - String processId; - String endpointId; - Search search; - Status status; - Transfer transfer; - IdResponse transferResponse; + /** CONSTRUCTOR(S) **/ public DigitalTwinRegistryTransfer(String processId, String endpointId, Status status, Search search, Dtr dtr) { this.dtr = dtr; this.endpointId = endpointId; @@ -864,14 +1148,29 @@ public DigitalTwinRegistryTransfer(String processId, String endpointId, Status s this.status = status; this.search = search; } + + /** METHODS **/ + + /** + * This method is exclusively for the Digital Twin Registry (DTR) transfer. + * + *

It's a Thread level method from Runnable interface and builds the Transfer Request, requests the Transfer for the DTR, gets the Transfer data + * and saves in the Process. + * + * @throws ServiceException + * if unable to do the contract transfer for the DTR. + */ @Override public void run() { try { this.dtrRequest = this.buildTransferRequest(this.processId,this.dtr, this.endpointId); + LogUtil.printWarning("DTR REQUEST:\n" + jsonUtil.toJson(this.dtrRequest, true)); processManager.saveTransferRequest(this.processId, dtrRequest, new IdResponse(processId, null), true); this.transferResponse = this.requestTransfer(dtrRequest); + processManager.saveTransferRequest(this.processId, dtrRequest, this.transferResponse, true); this.transfer = this.getTransferData(this.transferResponse); + LogUtil.printWarning("TRANSFER:\n" + jsonUtil.toJson(this.transfer, true)); if (this.transfer == null) { return; } @@ -885,15 +1184,31 @@ public void run() { throw new ServiceException(this.getClass().getName(), e, "Failed to do the contract transfer for Digital Twin Registry"); } } + + /** + * Builds a transfer request for a given DTR. + *

+ * @param processId + * the {@code String} identification of the Process. + * @param dtr + * the {@code DTR} object data of the Digital Twin Registry. + * @param endpointId + * the {@code String} identification of the receiver endpoint. + * + * @return a {@code TransferRequest} object with transfer request data. + * + * @throws ServiceException + * if unable to build the DTR's transfer request. + */ public TransferRequest buildTransferRequest(String processId, Dtr dtr, String endpointId) { try { // Build transfer request to make the Digital Twin Query - String receiverEndpoint = env.getProperty("configuration.edc.receiverEndpoint") + "/" + processId + "/" + this.endpointId; + String receiverEndpoint = env.getProperty("configuration.edc.receiverEndpoint") + "/" + processId + "/" + endpointId; TransferRequest.TransferType transferType = new TransferRequest.TransferType(); transferType.setContentType("application/octet-stream"); transferType.setIsFinite(true); - TransferRequest.DataDestination dataDestination = new TransferRequest.DataDestination(); + DataDestination dataDestination = new DataDestination(); dataDestination.setType("HttpProxy"); TransferRequest.PrivateProperties privateProperties = new TransferRequest.PrivateProperties(); @@ -914,6 +1229,18 @@ public TransferRequest buildTransferRequest(String processId, Dtr dtr, String en throw new ServiceException(this.getClass().getName(), e, "Failed to build the transfer request!"); } } + + /** + * Gets the Transfer response of a given DTR's Transfer request. + *

+ * @param transferRequest + * the {@code TransferRequest} object with transfer request data. + * + * @return a {@code IdResponse} object with transfer response data. + * + * @throws ServiceException + * if unable to transfer the DTR's transfer response. + */ public IdResponse requestTransfer(TransferRequest transferRequest) { IdResponse transferResponse = null; try { @@ -928,18 +1255,29 @@ public IdResponse requestTransfer(TransferRequest transferRequest) { return transferResponse; } - public Transfer getTransferData(IdResponse transferData) { + /** + * Gets the Transfer data from the response. + *

+ * @param transferResponse + * the {@code IdResponse} object with transfer response data. + * + * @return a {@code Transfer} object with the transfer data. + * + * @throws ServiceException + * if unable to get the transfer data. + */ + public Transfer getTransferData(IdResponse transferResponse) { /*[8]=========================================*/ // Check for transfer updates and the status Transfer transfer = null; try { - transfer = seeTransfer(transferData.getId()); + transfer = seeTransfer(transferResponse.getId()); } catch (Exception e) { - throw new ServiceException(this.getClass().getName(), e, "Failed to get the negotiation [" + transferData.getId() + "]"); + throw new ServiceException(this.getClass().getName(), e, "Failed to get the transfer data [" + transferResponse.getId() + "]"); } return transfer; } } -} \ No newline at end of file +} diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/VaultService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/VaultService.java index 2e9b4d961..e4748ab90 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/VaultService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/VaultService.java @@ -23,17 +23,13 @@ package org.eclipse.tractusx.productpass.services; -import com.fasterxml.jackson.databind.ObjectMapper; import org.eclipse.tractusx.productpass.config.VaultConfig; import org.eclipse.tractusx.productpass.exceptions.ServiceException; import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; import org.eclipse.tractusx.productpass.models.service.BaseService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; -import org.springframework.validation.ObjectError; import utils.*; -import utils.exceptions.UtilException; import java.nio.file.Path; import java.util.ArrayList; @@ -41,18 +37,22 @@ import java.util.List; import java.util.Map; +/** + * This class consists exclusively of methods to operate on Vault storage system. + * + *

The methods defined here are intended to set, save, check, read or create Vault's variables. + * + */ @Service public class VaultService extends BaseService { - + /** ATTRIBUTES **/ private final FileUtil fileUtil; - private final JsonUtil jsonUtil; - private final YamlUtil yamlUtil; - private final VaultConfig vaultConfig; + /** CONSTRUCTOR(S) **/ @Autowired public VaultService(VaultConfig vaultConfig, FileUtil fileUtil, JsonUtil jsonUtil, YamlUtil yamlUtil) throws ServiceInitializationException { this.fileUtil = fileUtil; @@ -62,6 +62,22 @@ public VaultService(VaultConfig vaultConfig, FileUtil fileUtil, JsonUtil jsonUti this.createLocalVaultFile(true); this.checkEmptyVariables(); } + + /** METHODS **/ + + /** + * Sets a new value to an existent parameter in the Vault. + *

+ * @param localSecretPath + * the path to the Vault's secret parameter. + * @param value + * the {@code Object} value to set. + * + * @return true if the value was successfully update, false otherwise. + * + * @throws ServiceException + * if unable to get the secret. + */ public Boolean setLocalSecret(String localSecretPath, Object value) { try { Object response = null; @@ -84,6 +100,20 @@ public Boolean setLocalSecret(String localSecretPath, Object value) { "It was not possible to get secret from file."); } } + + /** + * Saves a given data into the Vault. + *

+ * @param filePath + * the path to the Vault's file. + * @param response + * the {@code Object} data to save. + * + * @return true if the data was successfully saved, false otherwise. + * + * @throws ServiceException + * if unable to save the data into the vault. + */ public Boolean saveVault(String filePath, Object response){ try { String vaultYAML = yamlUtil.dumpYml(response, this.vaultConfig.getIndent(), this.vaultConfig.getPrettyPrint()); @@ -98,7 +128,17 @@ public Boolean saveVault(String filePath, Object response){ } } - + /** + * Checks if a secret parameter exists in the Vault. + *

+ * @param localSecretPath + * the path to the Vault's secret parameter. + * + * @return true if the secret exists in the vault, false otherwise. + * + * @throws ServiceException + * if unable to get the secret. + */ public Boolean secretExists(String localSecretPath){ try { String filePath = this.createLocalVaultFile(true); @@ -111,7 +151,17 @@ public Boolean secretExists(String localSecretPath){ } } - + /** + * Gets the value of a secret parameter from the Vault. + *

+ * @param localSecretPath + * the path to the Vault's secret parameter. + * + * @return the {@code Object} value of the given secret parameter. + * + * @throws ServiceException + * if unable to get the secret's value. + */ public Object getLocalSecret(String localSecretPath) { try { String secret = null; @@ -132,6 +182,18 @@ public Object getLocalSecret(String localSecretPath) { "It was not possible to get secret from file."); } } + + /** + * Creates a new File in the Vault. + *

+ * @param searchSystemVariables + * {@code Boolean} to specify if it's to use the default values configured in Vault environment variables. + * + * @return the {@code String} path of the new file created. + * + * @throws ServiceException + * if unable create the new file. + */ public String createLocalVaultFile(Boolean searchSystemVariables){ try { String dataDir = fileUtil.createDataDir("VaultConfig"); @@ -194,6 +256,13 @@ public String createLocalVaultFile(Boolean searchSystemVariables){ } } + /** + * Creates an empty variables List. + *

+ * + * @return an empty {@code Arraylist}. + * + */ @Override public List getEmptyVariables() { return new ArrayList<>(); diff --git a/consumer-backend/productpass/src/main/java/utils/CatenaXUtil.java b/consumer-backend/productpass/src/main/java/utils/CatenaXUtil.java index 3ab9fd7ac..e11b95bf4 100644 --- a/consumer-backend/productpass/src/main/java/utils/CatenaXUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/CatenaXUtil.java @@ -23,35 +23,72 @@ package utils; -import org.apache.juli.logging.Log; -import org.checkerframework.checker.units.qual.A; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; import utils.exceptions.UtilException; -import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; +/** + * This class consists exclusively of methods to operate on Catena-X related classes and models. + * + *

The methods defined here are intended to check, build or get Catena-X related information. + * + */ public final class CatenaXUtil { public final static String bpnNumberPattern = "BPN[LSA][A-Z0-9]{12}"; public final static String edcDataEndpoint = "/api/v1/dsp"; + /** + * Checks if the given String contains a BPN number pattern in it. + *

+ * @param str + * the {@code String} object to check. + * + * @return true if the BPN number pattern is found, false otherwise. + * + */ public static Boolean containsBPN(String str) { return str.matches(".*" + bpnNumberPattern + ".*"); } + /** + * Checks if the given String contains the known EDC data endpoint suffix. + *

+ * @param str + * the {@code String} object to check. + * + * @return true if the String contains the EDC data endpoint, false otherwise. + * + */ public static Boolean containsEdcEndpoint(String str) { return str.matches(".*" + edcDataEndpoint); } + /** + * Builds an EDC data endpoint by attaching needed suffix at the given {@code String} endpoint. + *

+ * @param endpoint + * the {@code String} base endpoint. + * + * @return a {@code String} endpoint with the given endpoint attached with the EDC data endpoint suffix. + * + */ public static String buildDataEndpoint(String endpoint) { return endpoint + edcDataEndpoint; } + /** + * Gets the BPN number from a given String, if exists. + *

+ * @param str + * the {@code String} object to get BPN number from. + * + * @return the {@code String} BPN number found in the given String or null if it doesn't exist. + * + */ public static String getBPN(String str) { Pattern pattern = Pattern.compile(bpnNumberPattern); Matcher matcher = pattern.matcher(str); @@ -62,6 +99,19 @@ public static String getBPN(String str) { return matcher.group(); } + /** + * Builds the Management Endpoint for a given path suffix for the endpoint. + *

+ * @param env + * the {@code Environment} object of the application environment variables. + * @param path + * the {@code String} path suffix for the intended endpoint (e.g: transferPath, negotiationPath, etc.). + * + * @return the built {@code String} endpoint by concatenating the EDC endpoint, management endpoint and the given path suffix. + * + * @throws UtilException + * if the EDC endpoint or management endpoint in the Environment variables are invalid. + */ public static String buildManagementEndpoint(Environment env, String path) { try { String edcEndpoint = env.getProperty("configuration.edc.endpoint"); @@ -75,6 +125,17 @@ public static String buildManagementEndpoint(Environment env, String path) { } } + /** + * Builds the full Endpoint for a given partial endpoint. + *

+ * @param endpoint + * the {@code String} partial endpoint. + * + * @return the built {@code String} endpoint by cleaning the given endpoint and adding the EDC data endpoint and BPN number (if applied). + * + * @throws UtilException + * if the given endpoint is an invalid one. + */ public static String buildEndpoint(String endpoint) { try { if (CatenaXUtil.containsEdcEndpoint(endpoint)) { diff --git a/consumer-backend/productpass/src/main/java/utils/CrypUtil.java b/consumer-backend/productpass/src/main/java/utils/CrypUtil.java index 802f2bc4a..dc07276e2 100644 --- a/consumer-backend/productpass/src/main/java/utils/CrypUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/CrypUtil.java @@ -28,64 +28,169 @@ import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; -import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Arrays; +import java.util.Base64; import java.util.UUID; -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; - +/** + * This class consists exclusively of methods related to Cryptography. + * + *

The methods defined here are intended to encode, decode, encrypt, decrypt or hash data and messages. + * + */ public final class CrypUtil { private CrypUtil() { throw new IllegalStateException("Tool/Utility Class Illegal Initialization"); } + + /** + * Encode a {@code String} message to Base64. + *

+ * @param str + * the {@code String} message to encode. + * + * @return a {@code String} base64 encoded message. + * + */ public static String toBase64(String str){ return Base64.getEncoder().encodeToString(str.getBytes()); } + + /** + * Encode a {@code byte[]} data to Base64. + *

+ * @param bytes + * the {@code byte[]} data to encode. + * + * @return a {@code String} base64 encoded data. + * + */ public static String toBase64(byte[] bytes){ return Base64.getEncoder().encodeToString(bytes); } + + /** + * Decode a {@code String} message from Base64. + *

+ * @param base64 + * the {@code String} base 64 encoded message. + * + * @return the {@code String} message decoded. + * + */ public static String fromBase64(String base64){ return new String(Base64.getDecoder().decode(base64)); } + + /** + * Decode a {@code byte[]} data from Base64. + *

+ * @param base64 + * {@code String} base64 encoded datat. + * + * @return he {@code byte[]} decoded data. + * + */ public static byte[] fromBase64ToByte(String base64){ return Base64.getDecoder().decode(base64); } + + /** + * Encode a {@code String} message to Base64 URL. + *

+ * @param str + * the {@code String} message to encode. + * + * @return a {@code String} base64 URL encoded message. + * + */ public static String toBase64Url(String str){ return Base64.getUrlEncoder().encodeToString(str.getBytes()); } + + /** + * Decode a {@code String} message from Base64 URL. + *

+ * @param base64 + * the {@code String} base 64 URL encoded message. + * + * @return the {@code String} message decoded. + * + */ public static String fromBase64Url(String base64){ return new String(Base64.getUrlDecoder().decode(base64)); } + /** + * Check if a {@code String} message is base64 encoded. + *

+ * @param str + * the {@code String} encoded message. + * + * @return true if the {@code String} message is base64 encoded, false otherwise. + * + */ public static Boolean isBase64(String str){ return org.apache.commons.net.util.Base64.isArrayByteBase64(str.getBytes()); // Check if string is Base64 encoded } + /** + * Generates an Universally Unique Identifier (UUID). + *

+ * + * @return a {@code String} random UUID. + * + */ public static String getUUID(){ return UUID.randomUUID().toString(); } + /** + * Creates a SHA256 hash of the given {@code String} message. + *

+ * @param digest + * the {@code String} message to hash code. + * + * @return a {@code String} SHA256 hash coded message. + * + */ public static String sha256(final String digest){ return Hashing.sha256() .hashString(digest, StandardCharsets.UTF_8) .toString(); } + + /** + * Creates a MD5 hash of the given {@code String} message. + *

+ * @param digest + * the {@code String} message to hash code. + * + * @return a {@code String} MD5 hash coded message. + * + */ public static String md5(final String digest){ return Hashing.md5() .hashString(digest, StandardCharsets.UTF_8) .toString(); } + + /** + * Creates a SHA1 hash of the given {@code String} message. + *

+ * @param digest + * the {@code String} message to hash code. + * + * @return a {@code byte[]} sha256 hash coded data. + * + * @throws UtilException + * if unable to generate the sha1 hash. + */ public static byte[] sha1Bytes(final String digest){ try { return MessageDigest.getInstance("SHA-1").digest(digest.getBytes("UTF-8")); @@ -94,12 +199,46 @@ public static byte[] sha1Bytes(final String digest){ throw new UtilException(CrypUtil.class,"It was not possible to generate sha1 hash" + e.getMessage()) ; } } + + /** + * Decode a {@code String} message from UTF-8. + *

+ * @param encodedURL + * the {@code String} URL encoded message. + * + * @return the {@code String} message decoded. + * + */ + @SuppressWarnings("Unused") public static String decodeFromUtf8(String encodedURL){ return URLDecoder.decode(encodedURL, StandardCharsets.UTF_8); } + + /** + * Encode a {@code String} message to UTF-8. + *

+ * @param decodedURL + * the {@code String} message to encode. + * + * @return the {@code String} URL message encoded as UTF-8. + * + */ + @SuppressWarnings("Unused") public static String encodeToUtf8(String decodedURL){ return URLEncoder.encode(decodedURL, StandardCharsets.UTF_8); } + + /** + * Creates an Advanced Encryption Secret (AES) key from a given secret key. + *

+ * @param secret + * the {@code String} secret key. + * + * @return the {@code SecretKeySpec} object with the generated AES key. + * + * @throws UtilException + * if unable to generate the AES key. + */ public static SecretKeySpec buildAesKey(final String secret) { try { byte[] bytesKey = CrypUtil.sha1Bytes(secret); @@ -108,6 +247,20 @@ public static SecretKeySpec buildAesKey(final String secret) { throw new UtilException(CrypUtil.class,"It was not possible to set key " + e.getMessage()) ; } } + + /** + * Encrypts a given message with AES cypher. + *

+ * @param decoded + * the {@code String} message to encrypt. + * @param key + * the {@code String} secret key to encrypt. + * + * @return the {@code String} object with the AES encrypted message. + * + * @throws UtilException + * if unable encrypt the message. + */ public static String encryptAes(final String decoded, final String key) { try { SecretKeySpec secretKey = CrypUtil.buildAesKey(key); @@ -119,6 +272,19 @@ public static String encryptAes(final String decoded, final String key) { } } + /** + * Decrypts a given AES encrypted message. + *

+ * @param encoded + * the {@code String} AES encrypted message. + * @param key + * the {@code String} secret key to decrypt. + * + * @return the {@code String} message decrypted. + * + * @throws UtilException + * if unable to decrypt the message. + */ public static String decryptAes(final String encoded, final String key) { try { SecretKeySpec secretKey = CrypUtil.buildAesKey(key); diff --git a/consumer-backend/productpass/src/main/java/utils/CsvUtil.java b/consumer-backend/productpass/src/main/java/utils/CsvUtil.java index fd8ed9779..d60e962a4 100644 --- a/consumer-backend/productpass/src/main/java/utils/CsvUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/CsvUtil.java @@ -23,13 +23,17 @@ package utils; -import com.opencsv.*; +import com.opencsv.CSVParser; +import com.opencsv.CSVParserBuilder; +import com.opencsv.CSVReader; +import com.opencsv.CSVReaderBuilder; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +@SuppressWarnings("Unused") public final class CsvUtil { private CsvUtil() { diff --git a/consumer-backend/productpass/src/main/java/utils/DateTimeUtil.java b/consumer-backend/productpass/src/main/java/utils/DateTimeUtil.java index 4b812b763..d9791aada 100644 --- a/consumer-backend/productpass/src/main/java/utils/DateTimeUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/DateTimeUtil.java @@ -23,19 +23,35 @@ package utils; +import utils.exceptions.UtilException; + import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +/** + * This class consists exclusively of methods to operate on DateTime type instances. + * + *

The methods defined here are intended to parse datetime formats and get current timestamps for logging purposes. + * + */ public final class DateTimeUtil { - /** - * Static tools to get current dateTime used for logging. - * - */ private DateTimeUtil() { throw new IllegalStateException("Tool/Utility Class Illegal Initialization"); } + + /** + * Gets the current datetime with a given format. + *

+ * @param pattern + * the intended datetime format to apply. + * + * @return a {@code String} object with the current datetime formatted with the given pattern or a default one if the patter is null. + * + * @apiNote default Format: "dd/MM/yyyy HH:mm:ss.SSS" + * + */ public static String getDateTimeFormatted(String pattern){ String defaultPattern = "dd/MM/yyyy HH:mm:ss.SSS"; if(pattern == null){ @@ -45,6 +61,19 @@ public static String getDateTimeFormatted(String pattern){ LocalDateTime now = LocalDateTime.now(); return dtf.format(now); } + + /** + * Gets the current datetime with a given format. + *

+ * @param pattern + * the intended datetime format to apply. + * + * @return a {@code String} object with the current datetime formatted with the given pattern or a default one if the patter is null. + * + * @apiNote default Format: "dd-MM-yyyy_HHmmss" + * + */ + @SuppressWarnings("Unused") public static String getFileDateTimeFormatted(String pattern){ String defaultPattern = "dd-MM-yyyy_HHmmss"; if(pattern == null){ @@ -55,6 +84,13 @@ public static String getFileDateTimeFormatted(String pattern){ return dtf.format(now); } + /** + * Gets the current timestamp. + *

+ * + * @return a {@code Long} object representing the current timestamp. + * + */ public static Long getTimestamp(){ return new Timestamp(System.currentTimeMillis()).getTime(); } diff --git a/consumer-backend/productpass/src/main/java/utils/EdcUtil.java b/consumer-backend/productpass/src/main/java/utils/EdcUtil.java index d8aa19cf1..2f383a714 100644 --- a/consumer-backend/productpass/src/main/java/utils/EdcUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/EdcUtil.java @@ -30,6 +30,12 @@ import org.springframework.stereotype.Component; import utils.exceptions.UtilException; +/** + * This class consists exclusively of methods to operate on Eclipse Dataspace Connector (EDC) data. + * + *

The methods defined here are intended to check or manipulate EDC's related data. + * + */ @Component public class EdcUtil { @@ -38,6 +44,18 @@ public class EdcUtil { public EdcUtil(JsonUtil jsonUtil) { this.jsonUtil = jsonUtil; } + + /** + * Parses the data from HTTP request {@code Object} body to a {@code DataPLaneEndpoint} object data. + *

+ * @param body + * the {@code Object} object representing the body for the request. + * + * @return a {@code DataPlaneEndpoint} object with the parsed date retrieved from the body. + * + * @throws UtilException + * if unable to parse to the data. + */ public DataPlaneEndpoint parseDataPlaneEndpoint(Object body){ try { return (DataPlaneEndpoint) this.jsonUtil.bindObject(body, DataPlaneEndpoint.class); @@ -47,6 +65,18 @@ public DataPlaneEndpoint parseDataPlaneEndpoint(Object body){ } // This method is responsible for finding if the EDC is version v0.5.0 basing itself in the contractId format. + /** + * Checks if the EDC is version v0.5.0 basing on the contractId format. + *

+ * @param contractId + * the contractId of the Digital Twin Registry (DTR) as a String. + * + * @return true if the EDC's version is v0.5.0, false otherwise. + * + * @throws UtilException + * if unable to check the EDC's version. + */ + @SuppressWarnings("Unused") public Boolean isEdc5(String contractId){ try { String[] parts = contractId.split(String.format("\\%s",":")); diff --git a/consumer-backend/productpass/src/main/java/utils/FileUtil.java b/consumer-backend/productpass/src/main/java/utils/FileUtil.java index ff5cf98fb..5c66f0e97 100644 --- a/consumer-backend/productpass/src/main/java/utils/FileUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/FileUtil.java @@ -23,8 +23,6 @@ package utils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import utils.exceptions.UtilException; @@ -36,10 +34,31 @@ import java.util.Comparator; import java.util.stream.Stream; + +/** + * This class consists exclusively of methods to operate on Files and Folders. + * + *

The methods defined here are intended to create, get, check, read and delete folders and files. + * + */ @Service public final class FileUtil { - + /** + * Writes the given {@code String} content into the file specified by the filePath with optional appending. + *

+ * @param filePath + * the path to the target file as a String. + * @param content + * the content to write on the file as a String. + * @param append + * if true, then data will be written to the end of the file rather than the beginning. + * + * @return a {@code String} filePath to the file. + * + * @throws UtilException + * if unable to write to the file. + */ public String toFile(String filePath, String content, Boolean append) throws IOException { this.createFile(filePath); try( @@ -54,18 +73,56 @@ public String toFile(String filePath, String content, Boolean append) throws IOE return filePath; } + + /** + * Creates a new File instance. + *

+ * @param filePath + * the path to the target file as a String. + * + * @return an empty {@code File} object with the given file path. + * + */ public File newFile(String filePath){ return new File(filePath); } + /** + * Gets the user's work directory. + *

+ * + * @return a {@code String} path of the user's work directory. + * + */ public static String getWorkdirPath(){ return Paths.get(System.getProperty("user.dir")).toString(); } + /** + * Gets the given Class base directory. + *

+ * @param selectedClass + * the Class type to get the base directory from. + * + * @return a {@code String} path of the class base directory. + * + */ + @SuppressWarnings("Unused") public String getBaseClassDir(Class selectedClass){ return this.normalizePath(selectedClass.getProtectionDomain().getCodeSource().getLocation().getPath()); } + /** + * Creates a new File. + *

+ * @param filePath + * the path to the target file as a String. + * + * @return a {@code String} filePath to the file. + * + * @throws UtilException + * if unable to create the file. + */ public String createFile(String filePath){ try { File myObj = new File(filePath); @@ -76,6 +133,19 @@ public String createFile(String filePath){ throw new UtilException(FileUtil.class,"It was not possible to create new file at ["+filePath+"], " + e.getMessage()) ; } } + + /** + * Parses the content of the given InputStream to a String. + *

+ * @param fileContent + * the {@code InputStream} representing the file content. + * + * @return a {@code String} object with input stream content. + * + * @throws UtilException + * if unable to read the input stream. + */ + @SuppressWarnings("Unused") public String getResourceAsString(InputStream fileContent){ InputStreamReader fileContentReader = new InputStreamReader( fileContent, @@ -95,6 +165,20 @@ public String getResourceAsString(InputStream fileContent){ return text.toString(); } + /** + * Parses a given resource to an InputStream. + *

+ * @param selectedClass + * the Class type of the resource. + * @param resourcePath + * the resource name. + * + * @return a {@code InputStream} object for reading the resource. + * + * @throws UtilException + * if unable to read the resource name. + */ + @SuppressWarnings("Unused") public InputStream getResourceContent(Class selectedClass, String resourcePath){ try { return selectedClass.getClassLoader().getResourceAsStream(resourcePath); @@ -102,6 +186,21 @@ public InputStream getResourceContent(Class selectedClass, String resourcePath){ throw new UtilException(FileUtil.class,"[ERROR] Something when wrong when reading file in path [" + resourcePath + "], " + e.getMessage()); } } + + /** + * Gets the path of a given Resource. + *

+ * @param selectedClass + * the Class type of the resource. + * @param resourcePath + * the resource name. + * + * @return a {@code String} object with the resource's path. + * + * @throws UtilException + * if unable to read the resource name. + */ + @SuppressWarnings("Unused") public String getResourcePath(Class selectedClass, String resourcePath){ try { return this.normalizePath(selectedClass.getClassLoader().getResource(resourcePath).getPath()); @@ -109,33 +208,93 @@ public String getResourcePath(Class selectedClass, String resourcePath){ throw new UtilException(FileUtil.class,"[ERROR] Something when wrong when reading file in path [" + resourcePath + "], " + e.getMessage()); } } + + /** + * Gets the path of the data directory of the application. + *

+ * + * @return a {@code String} path of the app's data directory. + * + */ public String getDataDir(){ String workDir = this.getWorkdirPath(); return Paths.get(workDir ,"data").toAbsolutePath().toString(); } + + /** + * Gets the path of the tmp directory of the application. + *

+ * + * @return a {@code String} path of the app's tmp directory. + * + */ public String getTmpDir(){ String workDir = this.getWorkdirPath(); return Paths.get(workDir ,"tmp").toAbsolutePath().toString(); } + + /** + * Creates a directory in the data directory of the application. + *

+ * @param name + * the name of the new directory. + * + * @return a {@code String} path of the created directory. + * + */ public String createDataDir(String name){ String workDir = this.getWorkdirPath(); String path = Paths.get(workDir ,"data" , name).toAbsolutePath().toString(); return this.createDir(path); } + + /** + * Creates a directory in the tmp directory of the application. + *

+ * @param name + * the name of the new directory. + * + * @return a {@code String} path of the created directory. + * + */ + @SuppressWarnings("Unused") public String createTmpDir(String name){ String workDir = this.getWorkdirPath(); String path = Paths.get(workDir ,"tmp" , name).toAbsolutePath().toString(); return this.createDir(path); } + /** + * Creates a temporary directory in the work directory of the application. + *

+ * @param dirName + * the name of the temporary directory. + * + * @return a {@code String} path of the created directory. + * + * @throws UtilException + * if unable to create the directory. + */ + @SuppressWarnings("Unused") public String createTempDir(String dirName){ try { return Files.createTempDirectory(dirName).toFile().getAbsolutePath(); } catch (IOException e) { - throw new RuntimeException(e); + throw new UtilException(FileUtil.class, "It was not possible to create dir [" + dirName + "]"); } } + /** + * Creates a directory in the given path and creates all the non-existent directories in the path. + *

+ * @param dirPath + * the complete path to the new directory as a String. + * + * @return a {@code String} path of the created directory. + * + * @throws UtilException + * if unable to create the directory. + */ public String createDir(String dirPath){ try { return Files.createDirectories(Path.of(dirPath)).toAbsolutePath().toString(); @@ -143,6 +302,18 @@ public String createDir(String dirPath){ throw new UtilException(FileUtil.class, "It was not possible to create dir [" + dirPath + "]"); } } + + /** + * Reads a file from the given path, if exists. + *

+ * @param path + * the path to the file as a String. + * + * @return a {@code String} with the content of the file. + * + * @throws UtilException + * if unable to read the file. + */ public String readFile(String path){ try { @@ -157,6 +328,15 @@ public String readFile(String path){ } + /** + * Deletes a directory from the given path, if exists. + *

+ * @param path + * the path to the intended directory as a String. + * + * @throws UtilException + * if unable to delete the directory. + */ public void deleteDir(String path){ try { Path dir = Path.of(path); @@ -180,6 +360,15 @@ public void deleteDir(String path){ } } + /** + * Deletes a file from the given path, if exists. + *

+ * @param path + * the path to the intended file as a String. + * + * @throws UtilException + * if unable to delete the file. + */ public Boolean deleteFile(String path){ try { if(!this.pathExists(path)) { @@ -192,6 +381,15 @@ public Boolean deleteFile(String path){ } } + /** + * Gets the root path of the user's working directory of the application. + *

+ * @return a {@code String} with the root path. + * + * @throws UtilException + * if unable to get the root path. + */ + @SuppressWarnings("Unused") public String getRootPath(){ try { return System.getProperty("user.dir"); @@ -199,6 +397,19 @@ public String getRootPath(){ throw new UtilException(FileUtil.class, "It was not possible to get root path"); } } + + /** + * Reads a file from the given path, if exists. + *

+ * @param path + * the path to the file as a Path. + * + * @return a {@code String} with the content of the file. + * + * @throws UtilException + * if unable to read the file. + */ + @SuppressWarnings("Unused") public String readFile(Path path){ try { @@ -212,6 +423,19 @@ public String readFile(Path path){ } } + + /** + * Creates a directory in the given path and creates all the non-existent directories in the path. + *

+ * @param dirPath + * the complete path to the new directory as a Path. + * + * @return a {@code String} path of the created directory. + * + * @throws UtilException + * if unable to create the directory. + */ + @SuppressWarnings("Unused") public String createDir(Path dirPath){ try { return Files.createDirectories(dirPath).toAbsolutePath().toString(); @@ -219,6 +443,21 @@ public String createDir(Path dirPath){ throw new UtilException(FileUtil.class, "It was not possible to create dir [" + dirPath + "]"); } } + + /** + * Creates a subdirectory in the given path and creates all the non-existent directories in the path. + *

+ * @param dirPath + * the complete path to the new subdirectory as a String. + * @param subDirName + * the new subdirectory name. + * + * @return a {@code String} path of the created subdirectory. + * + * @throws UtilException + * if unable to create the subdirectory. + */ + @SuppressWarnings("Unused") public String createSubDir(String dirPath, String subDirName){ try { if(!this.pathExists(dirPath)){ @@ -229,7 +468,22 @@ public String createSubDir(String dirPath, String subDirName){ throw new UtilException(FileUtil.class, "It was not possible to create subdir [" + subDirName + "] in [" + dirPath + "]"); } } - public String getTmpFile(String fileName, String extension){ + + /** + * Creates a temporary file in the work directory of the application. + *

+ * @param fileName + * the name of the temporary file. + * @param extension + * the extension of the file as a String (e.g: ".json", ".txt", etc.). + * + * @return a {@code String} path of the new file created. + * + * @throws UtilException + * if unable to create the temporary file. + */ + @SuppressWarnings("Unused") + public String createTmpFile(String fileName, String extension){ try { return Files.createTempFile(fileName, extension).getFileName().toAbsolutePath().toString(); } catch (Exception e) { @@ -237,15 +491,57 @@ public String getTmpFile(String fileName, String extension){ } } + /** + * Checks if a path exists. + *

+ * @param path + * the path to check as a String. + * + * @return true if the path exists, false otherwise. + * + */ public Boolean pathExists(String path){ return Files.exists(Path.of(path)); } + + /** + * Checks if a path exists. + *

+ * @param file + * the {@code File} instance. + * + * @return true if the file exists, false otherwise. + * + */ + @SuppressWarnings("Unused") public Boolean fileExists(File file){ return file.exists(); } + + /** + * Checks if a path exists. + *

+ * @param path + * the path to check as a Path. + * + * @return true if the path exists, false otherwise. + * + */ public Boolean pathExists(Path path){ return Files.exists(path); } + + /** + * Normalizes the given path to its canonical path. + *

+ * @param path + * the path to normalize as a String. + * + * @return the {@code String} canonical path string denoting the same file or directory. + * + * @throws UtilException + * if unable to normalize the path. + */ public String normalizePath(String path) { try { return new File(path).getCanonicalPath(); @@ -253,9 +549,31 @@ public String normalizePath(String path) { throw new UtilException(FileUtil.class,"[ERROR] It was not possible to normalize path ["+path+"]"); } } + + /** + * Gets the Java file of the given Class type. + *

+ * @param selectedClass + * the Class type to get the Java file from. + * + * @return the {@code String} Java file name of the given Class type (the ".java" file). + * + */ + @SuppressWarnings("Unused") public String getClassFile(Class selectedClass){ return selectedClass.getName().replace(".", "/") + ".java"; } + + /** + * Gets the Package directory of the given Class type. + *

+ * @param selectedClass + * the Class type to get the Java file from. + * + * @return the {@code String} package directory of the given Class type. + * + */ + @SuppressWarnings("Unused") public String getClassPackageDir(Class selectedClass){ return selectedClass.getPackageName().replace(".", "/"); } diff --git a/consumer-backend/productpass/src/main/java/utils/HttpUtil.java b/consumer-backend/productpass/src/main/java/utils/HttpUtil.java index 9e88f9f05..f0668a8d5 100644 --- a/consumer-backend/productpass/src/main/java/utils/HttpUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/HttpUtil.java @@ -23,8 +23,8 @@ package utils; -import org.apache.juli.logging.Log; -import org.checkerframework.checker.units.qual.C; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.eclipse.tractusx.productpass.models.edc.Jwt; import org.eclipse.tractusx.productpass.models.http.Response; import org.springframework.beans.factory.annotation.Autowired; @@ -34,7 +34,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder; @@ -46,14 +45,15 @@ import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Base64; import java.util.HashMap; import java.util.Map; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - +/** + * This class consists exclusively of methods to operate on the HTTP protocol. + * + *

The methods defined here are intended to get, set, parse and manipulate HTTP requests and responses. + * + */ @Component public class HttpUtil { @@ -72,18 +72,63 @@ public HttpUtil(Environment env) { private final String POST_ERROR_MESSAGE = "It was not possible to do POST request to "; + /** + * Gets a session value of an HTTP Request. + *

+ * @param httpRequest + * the HTTP request. + * @param key + * the session's key to lookup for. + * + * @return a {@code Object} object with the value of the given key. + * + */ public Object getSessionValue(HttpServletRequest httpRequest, String key) { return httpRequest.getSession().getAttribute(key); } + /** + * Sets a session value on an HTTP Request. + *

+ * @param httpRequest + * the HTTP request. + * @param key + * the session's key to lookup for. + * @param value + * the object value to update. + * + * @return a {@code Object} object with the value of the given key. + * + */ public void setSessionValue(HttpServletRequest httpRequest, String key, Object value) { httpRequest.getSession().setAttribute(key, value); } + + /** + * Gets the session Id of an HTTP Request. + *

+ * @param httpRequest + * the HTTP request. + * + * @return a {@code String} object with the value of the session Id. + * + */ public String getSessionId(HttpServletRequest httpRequest) { return httpRequest.getSession().getId(); } - + /** + * Checks if a session key exists on the HTTP Request. + *

+ * @param httpRequest + * the HTTP request. + * @param key + * the session's key to lookup for. + * + * @return true if the key exists, false otherwise. + * + */ + @SuppressWarnings("Unused") public Boolean isInSession(HttpServletRequest httpRequest, String key) { try { Object value = httpRequest.getSession().getAttribute(key); @@ -102,13 +147,47 @@ public Boolean isInSession(HttpServletRequest httpRequest, String key) { * @param httpRequest + Extra details **************************************************/ + /** + * Gets HTTP information like the protocol, method and the request URI used in the given HTTP Request and concatenates with the given HTTP response status + *

+ * @param httpRequest + * the HTTP request. + * @param status + * the HTTP response status. + * + * @return a {@code String} object with the HTTP information from the given HTTP Request concatenated with the given HTTP response status. + * + */ public String getHttpInfo(HttpServletRequest httpRequest, Integer status) { return "[" + httpRequest.getProtocol() + " " + httpRequest.getMethod() + "] " + status + ": " + httpRequest.getRequestURI(); } + + /** + * Gets HTTP information like the status, statusText and the message related with the given HTTP response. + *

+ * @param response + * the HTTP response. + * + * @return a {@code String} object with the HTTP information from the given HTTP Request concatenated with the given HTTP response status. + * + */ public String getResponseHttpInfo(Response response) { return "[HTTP Response] " + response.status + " " + response.statusText+ ": " + response.getMessage(); } + /** + * Gets the parameter from the HTTP request or a defaultValue if otherwise. + *

+ * @param httpRequest + * the HTTP request. + * @param param + * parameter to look up for in the given HTTP request. + * @param defaultPattern + * default value to return if the parameter doesn't exist. + * + * @return a {@code String} with the value of the parameter, if found or the defaultPattern otherwise. + * + */ public String getParamOrDefault(HttpServletRequest httpRequest, String param, String defaultPattern) { String requestParam = httpRequest.getParameter(param); if (requestParam == null) { @@ -117,6 +196,15 @@ public String getParamOrDefault(HttpServletRequest httpRequest, String param, S return requestParam; } + /** + * Gets the authorization token for the given HTTP request. + *

+ * @param httpRequest + * the HTTP request. + * + * @return a {@code String} with the value of the token to be able to communicate. + * + */ public String getAuthorizationToken(HttpServletRequest httpRequest){ final String authorizationHeaderValue = httpRequest.getHeader("Authorization"); String token = null; @@ -128,6 +216,21 @@ public String getAuthorizationToken(HttpServletRequest httpRequest){ } return token; } + + /** + * Builds the URL with the key/value pair within the given parameters map with or without enconding. + *

+ * @param url + * the base URL. + * @param params + * the Map with key/value pair from each parameter. + * @param encode + * if true will encode the value of each parameter. + * + * @return a {@code String} with the build URL. + * + */ + @SuppressWarnings("Unused") public String buildUrl(String url, Map params, Boolean encode){ StringBuilder finalUrl = new StringBuilder(url); for(Map.Entry entry : params.entrySet()){ @@ -143,6 +246,18 @@ public String buildUrl(String url, Map params, Boolean encode){ } return finalUrl.toString(); } + + /** + * Parses the Map of parameters to a String as URL parameters structure. + *

+ * @param params + * the Map with key/value pair from each parameter. + * @param encode + * if true will encode the value of each parameter. + * + * @return a {@code String} with all parameters as URL parameters structure. + * + */ public String mapToParams(Map params, Boolean encode){ StringBuilder finalUrl = new StringBuilder(); for(Map.Entry entry : params.entrySet()){ @@ -156,6 +271,16 @@ public String mapToParams(Map params, Boolean encode){ return finalUrl.toString(); } + /** + * Encodes the value of each parameter in the given Map. + *

+ * @param params + * the Map with key/value pair from each parameter. + * + * @return a {@code Map} with the value of each parameter encoded. + * + */ + @SuppressWarnings("Unused") public Map encodeParams(Map params){ Map encodedParams = new HashMap<>(); for(Map.Entry entry : params.entrySet()){ @@ -166,6 +291,17 @@ public String mapToParams(Map params, Boolean encode){ return encodedParams; } + /** + * Gets the current Host for the given HTTP request. + *

+ * @param httpRequest + * the HTTP request. + * + * @return a {@code String} with the URL of the current Host. + * + * @throws UtilException + * if unable to get the host URL. + */ public String getCurrentHost(HttpServletRequest httpRequest){ try { return ServletUriComponentsBuilder.fromRequestUri(httpRequest) @@ -177,6 +313,17 @@ public String getCurrentHost(HttpServletRequest httpRequest){ } } + /** + * Parses the given token as a {@code Jwt} object. + *

+ * @param token + * the {@code String} token. + * + * @return a {@code Jwt} object parsed with the values from the token. + * + * @throws UtilException + * if unable to parse the token. + */ public Jwt parseToken(String token){ try { String[] chunks = token.split("\\."); @@ -192,6 +339,19 @@ public Jwt parseToken(String token){ } } + + /** + * Gets the URL from the given HTTP request. + *

+ * @param httpRequest + * the HTTP request. + * + * @return a {@code String} with the request's URL. + * + * @throws UtilException + * if unable to get the URL. + */ + @SuppressWarnings("Unused") public String getCurrentUrl(HttpServletRequest httpRequest){ try { return httpRequest.getRequestURL().toString(); @@ -200,20 +360,73 @@ public String getCurrentUrl(HttpServletRequest httpRequest){ } } + /** + * Gets the Host from the given URL. + *

+ * @param url + * the {@code String} URL. + * + * @return a {@code String} with the Host name of the URL. + * + */ + @SuppressWarnings("Unused") public String getHost(String url) throws MalformedURLException { return new URL(url).getHost(); } + + /** + * Gets the Protocol from the given URL. + *

+ * @param url + * the {@code String} URL. + * + * @return a {@code String} with the Protocol name of the URL. + * + */ + @SuppressWarnings("Unused") public String getProtocol(String url) throws MalformedURLException { return new URL(url).getProtocol(); } + + /** + * Gets the Port from the given URL. + *

+ * @param url + * the {@code String} URL. + * + * @return a {@code Integer} with the Port number of the URL. + * + */ + @SuppressWarnings("Unused") public Integer getPort(String url) throws MalformedURLException { int port = new URL(url).getPort(); return (port!=-1)?port:null; } + + /** + * Gets the Authority part from the given URL. + *

+ * @param url + * the {@code String} URL. + * + * @return a {@code String} with the Authority part of the URL. + * + */ + @SuppressWarnings("Unused") public String getAuthority(String url) throws MalformedURLException { return new URL(url).getAuthority(); } + /** + * Parses the given URL to a key/value pair Map with the protocol, host, port and authorirty part information. + *

+ * @param strUrl + * the {@code String} URL. + * + * @return a {@code Map} object with the main URL parameters. + * + */ + @SuppressWarnings("Unused") public HashMap splitUrl(String strUrl) throws MalformedURLException{ HashMap retObj = new HashMap<>(); URL url = new URL(strUrl); @@ -224,6 +437,16 @@ public HashMap splitUrl(String strUrl) throws MalformedURLExcep retObj.put("authority", url.getAuthority()); return retObj; } + + /** + * Parses the given {@code String} URL into a String format with protocol and authority information + *

+ * @param strUrl + * the {@code String} URL. + * + * @return a {@code String} object with format result. + * + */ public static String cleanUrl(String strUrl) throws MalformedURLException{ URL url = new URL(strUrl); String protocol = url.getProtocol(); @@ -237,6 +460,17 @@ public static String cleanUrl(String strUrl) throws MalformedURLException{ **************************************************/ + /** + * Builds an {@code HttpServletResponse} object with the given response message. + *

+ * @param response + * the response message. + * @param servletResponse + * the HTTP response. + * + * @return the {@code Response} given object after setting some parameters of HTTP response. + * + */ public Response buildResponse(Response response, HttpServletResponse servletResponse){ servletResponse.setStatus(response.getStatus()); servletResponse.setHeader("Access-Control-Allow-Origin", "*"); @@ -246,6 +480,7 @@ public Response buildResponse(Response response, HttpServletResponse servletRes } return response; } + public Response getResponse() { return new Response( null, @@ -267,6 +502,8 @@ public Response getResponse(String message, Object data) { data ); } + + @SuppressWarnings("Unused") public Response getBadRequest() { return new Response( null, @@ -281,6 +518,7 @@ public Response getBadRequest(String message) { "Bad Request" ); } + @SuppressWarnings("Unused") public Response getNotFound() { return new Response( null, @@ -306,6 +544,7 @@ public Response getInternalError() { ); } + @SuppressWarnings("Unused") public Response getInternalError(String message) { return new Response( message, @@ -334,6 +573,7 @@ public Response getNotAuthorizedResponse() { "Not Authorized" ); } + public void redirect(HttpServletResponse httpResponse, String url) { try { httpResponse.sendRedirect(url); @@ -342,6 +582,19 @@ public void redirect(HttpServletResponse httpResponse, String url) { } } + /** + * Builds an {@code URI} object with the given URL and parameters. + *

+ * @param url + * the base URL. + * @param params + * the Map with key/value pair from each parameter. + * @param encoded + * if true will encode the value of each parameter. + * + * @return the built {@code URI} object set with the given URL and parameters with or without enconding. + * + */ public URI buildUri(String url, Map params, Boolean encoded){ UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url); for(Map.Entry entry : params.entrySet()){ @@ -353,6 +606,29 @@ public URI buildUri(String url, Map params, Boolean encoded){ /************************************************** * Generic Request Methods ************************ **************************************************/ + + + /** + * Builds and make an HTTP request with the given parameters. + *

+ * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param method + * the HTTP method (e.g: GET, POST, etc.) + * @param payload + * the payload for the request as an {@code HttpEntity}. + * @param params + * the Map with key/value pair from each parameter. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the request. + * + */ public ResponseEntity doRequest(String url, Class responseType, HttpMethod method, HttpEntity payload, Map params, Boolean retry, Boolean encode) { RestTemplate restTemplate = new RestTemplate(); URI finalUri = this.buildUri(url, params, encode); @@ -380,14 +656,30 @@ public ResponseEntity doRequest(String url, Class responseType, HttpMethod return response; } - /// ============================================================ - /// REQUEST Methods -------------------------------------------- - /// ============================================================ - - - - /* - * GET With PARAMS + HEADERS + /** + ============================================================ + REQUEST Methods -------------------------------------------- + ============================================================ + **/ + + /** + * Builds and make an HTTP GET request with headers and parameters, without body. + *

+ * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param headers + * the HTTP headers to configure. + * @param params + * the Map with key/value pair from each parameter. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the GET request. + * */ public ResponseEntity doGet(String url, Class responseType, HttpHeaders headers, Map params, Boolean retry, Boolean encode) { try { @@ -398,9 +690,24 @@ public ResponseEntity doGet(String url, Class responseType, HttpHeaders h } } - /* - * GET With HEADERS + /** + * Builds and make an HTTP GET request with headers, without parameters and body. + *

+ * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param headers + * the HTTP headers to configure. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the GET request. + * */ + @SuppressWarnings("Unused") public ResponseEntity doGet(String url, Class responseType, HttpHeaders headers, Boolean retry, Boolean encode) { try { HttpEntity requestEntity = new HttpEntity<>(headers); @@ -410,9 +717,29 @@ public ResponseEntity doGet(String url, Class responseType, HttpHeaders h } } - /* - * GET With PARAMS + HEADERS + BODY + + /** + * Builds and make an HTTP GET request with headers, parameters and body. + *

+ * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param headers + * the HTTP headers to configure. + * @param params + * the Map with key/value pair from each parameter. + * @param body + * the {@code Object} object representing the body for the request. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the GET request. + * */ + @SuppressWarnings("Unused") public ResponseEntity doGet(String url, Class responseType, HttpHeaders headers, Map params, Object body, Boolean retry, Boolean encode) { try { HttpEntity requestEntity = new HttpEntity<>(body, headers); @@ -422,9 +749,24 @@ public ResponseEntity doGet(String url, Class responseType, HttpHeaders } } - /* - * GET With PARAMS + /** + * Builds and make an HTTP GET request with parameters, without headers and body. + *

+ * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param params + * the Map with key/value pair from each parameter. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the GET request. + * */ + @SuppressWarnings("Unused") public ResponseEntity doGet(String url, Class responseType, Map params, Boolean retry, Boolean encode) { try { HttpEntity requestEntity = new HttpEntity<>(this.getHeaders()); @@ -434,9 +776,26 @@ public ResponseEntity doGet(String url, Class responseType, Map + * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param params + * the Map with key/value pair from each parameter. + * @param body + * the {@code Object} object representing the body for the request. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the GET request. + * */ + @SuppressWarnings("Unused") public ResponseEntity doGet(String url, Class responseType, Map params,Object body, Boolean retry, Boolean encode) { try { HttpEntity requestEntity = new HttpEntity<>(body, this.getHeaders()); @@ -445,9 +804,21 @@ public ResponseEntity doGet(String url, Class responseType, Map + * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param retry + * if true it will retry to do the request a predefined couple of times. + * + * @return the {@code ResponseEntity} with the result of the GET request. + * */ + @SuppressWarnings("Unused") public ResponseEntity doGet(String url, Class responseType, Boolean retry) { try { HttpEntity requestEntity = new HttpEntity<>(this.getHeaders()); @@ -458,8 +829,24 @@ public ResponseEntity doGet(String url, Class responseType, Boolean retr } - /* - * POST With PARAMS + HEADERS + /** + * Builds and make an HTTP POST request with headers and parameters, without body. + *

+ * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param headers + * the HTTP headers to configure. + * @param params + * the Map with key/value pair from each parameter. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the POST request. + * */ public ResponseEntity doPost(String url, Class responseType, HttpHeaders headers, Map params, Boolean retry, Boolean encode) { try { @@ -470,8 +857,26 @@ public ResponseEntity doPost(String url, Class responseType, HttpHeaders } } - /* - * POST With PARAMS + HEADERS + BODY + /** + * Builds and make an HTTP POST request with headers, parameters and body. + *

+ * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param headers + * the HTTP headers to configure. + * @param params + * the Map with key/value pair from each parameter. + * @param body + * the {@code Object} object representing the body for the request. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the POST request. + * */ public ResponseEntity doPost(String url, Class responseType, HttpHeaders headers, Map params, Object body, Boolean retry, Boolean encode) { try { @@ -482,9 +887,24 @@ public ResponseEntity doPost(String url, Class responseType, HttpHeaders } } - /* - * POST With PARAMS + /** + * Builds and make an HTTP POST request with parameters, without headers and body. + *

+ * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param params + * the Map with key/value pair from each parameter. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the POST request. + * */ + @SuppressWarnings("Unused") public ResponseEntity doPost(String url, Class responseType, Map params, Boolean retry, Boolean encode) { try { HttpEntity requestEntity = new HttpEntity<>(this.getHeaders()); @@ -494,9 +914,26 @@ public ResponseEntity doPost(String url, Class responseType, Map + * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param params + * the Map with key/value pair from each parameter. + * @param body + * the {@code Object} object representing the body for the request. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * @param encode + * if true will encode the value of each parameter. + * + * @return the {@code ResponseEntity} with the result of the POST request. + * + */ + @SuppressWarnings("Unused") public ResponseEntity doPost(String url, Class responseType, Map params,Object body, Boolean retry, Boolean encode) { try { HttpEntity requestEntity = new HttpEntity<>(body, this.getHeaders()); @@ -505,9 +942,23 @@ public ResponseEntity doPost(String url, Class responseType, Map + * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param headers + * the HTTP headers to configure. + * @param retry + * if true it will retry to do the request a predefined couple of times. + * + * @return the {@code ResponseEntity} with the result of the POST request. + * */ + @SuppressWarnings("Unused") public ResponseEntity doPost(String url, Class responseType, HttpHeaders headers, Boolean retry) { try { HttpEntity requestEntity = new HttpEntity<>(headers); @@ -516,9 +967,21 @@ public ResponseEntity doPost(String url, Class responseType, HttpHeaders throw new UtilException(HttpUtil.class, e, POST_ERROR_MESSAGE + url); } } - /* - * POST Without anything + + /** + * Builds and make an empty HTTP POST request without headers, parameters and body. + *

+ * @param url + * the base URL. + * @param responseType + * the class type of the response (e.g: a String, an Object, etc.) + * @param retry + * if true it will retry to do the request a predefined couple of times. + * + * @return the {@code ResponseEntity} with the result of the POST request. + * */ + @SuppressWarnings("Unused") public ResponseEntity doPost(String url, Class responseType, Boolean retry) { try { HttpEntity requestEntity = new HttpEntity<>(this.getHeaders()); @@ -527,6 +990,7 @@ public ResponseEntity doPost(String url, Class responseType, Boolean ret throw new UtilException(HttpUtil.class, e, POST_ERROR_MESSAGE + url); } } + public HttpHeaders getHeaders() { return new HttpHeaders(); } diff --git a/consumer-backend/productpass/src/main/java/utils/JsonUtil.java b/consumer-backend/productpass/src/main/java/utils/JsonUtil.java index 699ef6488..275992f32 100644 --- a/consumer-backend/productpass/src/main/java/utils/JsonUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/JsonUtil.java @@ -23,24 +23,28 @@ package utils; -import com.fasterxml.jackson.core.*; +import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.json.JsonWriteFeature; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import io.netty.handler.codec.serialization.ObjectEncoder; -import org.eclipse.tractusx.productpass.models.catenax.EdcDiscoveryEndpoint; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; import utils.exceptions.UtilException; -import java.io.File; import java.util.*; +/** + * This class consists exclusively of methods to operate on JSON type files. + * + *

The methods defined here are intended to load, save, parse and manipulate JSON files or objects. + * + */ @Component public final class JsonUtil { @@ -57,6 +61,20 @@ public ArrayList getObjectArray(Object... data){ data) ); } + + /** + * Loads the JSON file from the given file path and maps it to an object. + *

+ * @param jsonString + * the path representation to the target JSON file as a String. + * @param classType + * the class type to map the json structure from the file to an object. + * + * @return a {@code Object} object mapped with the json file structure. + * + * @throws UtilException + * if unable to load the JSON file. + */ public Object loadJson(String jsonString, Class classType){ try { ObjectMapper mapper = new ObjectMapper(); @@ -66,6 +84,17 @@ public Object loadJson(String jsonString, Class classType){ } } + /** + * Loads the JSON file from the given file path as a String. + *

+ * @param jsonString + * the path representation to the target JSON file as a String. + * + * @return a {@code String} object with the json file data. + * + * @throws UtilException + * if unable to load the JSON file. + */ public String escapeJson(String jsonString){ try { ObjectMapper mapper = new ObjectMapper(); @@ -77,6 +106,17 @@ public String escapeJson(String jsonString){ } } + /** + * Parses the JSON file from the given file path as an Object. + *

+ * @param jsonString + * the path representation to the target JSON file as a String. + * + * @return a {@code Object} object with the json file data. + * + * @throws UtilException + * if unable to load the JSON file. + */ public Object parseJson(String jsonString){ try { ObjectMapper mapper = new ObjectMapper(); @@ -85,6 +125,20 @@ public Object parseJson(String jsonString){ throw new UtilException(JsonUtil.class, "I was not possible to parse JSON! -> [" + e.getMessage() + "]"); } } + + /** + * Parses the JSON file from the given file path and maps it to the specified Class type. + *

+ * @param jsonString + * the path representation to the target JSON file as a String. + * @param bindClass + * the class type to map the json structure from the file to an object. + * + * @return a {@code Object} object mapped with the json file structure. + * + * @throws UtilException + * if unable to load the JSON file. + */ public Object parseJson(String jsonString, Class bindClass){ try { ObjectMapper mapper = new ObjectMapper(); @@ -93,13 +147,32 @@ public Object parseJson(String jsonString, Class bindClass){ throw new UtilException(JsonUtil.class, "I was not possible to parse JSON! -> [" + e.getMessage() + "]"); } } + + @SuppressWarnings("Unused") public ObjectNode newJson(){ return JsonNodeFactory.instance.objectNode(); } + + /** + * Creates an object of JsonNode type. + *

+ * + * @return a {@code JsonNode} object. + * + */ public JsonNode newJsonNode(){ return JsonNodeFactory.instance.objectNode(); } + /** + * Checks if the given JSON file path is actually a JSON file by checking the components tree. + *

+ * @param jsonString + * the path representation to the target JSON file as a String. + * + * @return true if the file is a JSON file and false otherwise or if some exception is thrown. + * + */ public Boolean isJson(String jsonString){ try { ObjectMapper mapper = new ObjectMapper() @@ -110,6 +183,20 @@ public Boolean isJson(String jsonString){ } return true; } + + /** + * Parses the given object into a JSON type structure with or without a pretty print. + *

+ * @param json + * the object data to save into a JSON file. + * @param prettyPrint + * boolean to specify a pretty or compact structure in the JSON file. + * + * @return a {@code String} object representing the given object data with a JSON type structure. + * + * @throws UtilException + * if unable to load the JSON file. + */ public String toJson(Object json, Boolean prettyPrint){ try { ObjectMapper mapper = new ObjectMapper(); @@ -122,6 +209,22 @@ public String toJson(Object json, Boolean prettyPrint){ throw new UtilException(JsonUtil.class, "I was not possible to dump JSON! -> [" + e.getMessage() + "]"); } } + + /** + * Parses the given object into a JSON file with or without a pretty print. + *

+ * @param path + * the path representation to the target JSON file as a String. + * @param json + * the object data to save into a JSON file. + * @param prettyPrint + * boolean to specify a pretty or compact structure in the JSON file. + * + * @return a {@code String} object representing the path to the JSON file. + * + * @throws UtilException + * if unable to load the JSON file. + */ public String toJsonFile(String path, Object json, Boolean prettyPrint){ try { return fileUtil.toFile(path, this.toJson(json, prettyPrint), false); @@ -129,6 +232,19 @@ public String toJsonFile(String path, Object json, Boolean prettyPrint){ throw new UtilException(JsonUtil.class, "I was not possible to create JSON file ["+path+"]! -> [" + e.getMessage() + "]"); } } + + /** + * Parses the given JSON file path to an Object. + *

+ * @param path + * the path representation to the target JSON file as a String. + * + * @return a {@code Object} object mapped with the json file structure. + * + * @throws UtilException + * if unable to load the JSON file. + */ + @SuppressWarnings("Unused") public Object fromJsonFile(String path){ try { String fileContent = fileUtil.readFile(path); @@ -137,6 +253,20 @@ public Object fromJsonFile(String path){ throw new UtilException(JsonUtil.class, "I was not possible to create JSON file ["+path+"]! -> [" + e.getMessage() + "]"); } } + + /** + * Parses the given JSON file path to an object of the specified Class type. + *

+ * @param path + * the path representation to the target JSON file as a String. + * @param bindClass + * the class type to map the json structure from the file to an object. + * + * @return a {@code Object} object mapped with the json file structure. + * + * @throws UtilException + * if unable to load the JSON file. + */ public Object fromJsonFileToObject(String path, Class bindClass){ try { if(!fileUtil.pathExists(path)) { @@ -150,6 +280,19 @@ public Object fromJsonFileToObject(String path, Class bindClass){ } } + /** + * Checks if a given key exists within the given object. + *

+ * @param sourceObj + * Map, JsonNode or other Object able to parse to a Map type object. + * @param key + * the key name to lookup for in the given object. + * + * @return true if the key exists in the given object, false otherwise. + * + * @throws UtilException + * if unable to parse the given object to a Map type class. + */ public Boolean keyExists(Object sourceObj,String key){ try { if(sourceObj == null){ @@ -173,6 +316,24 @@ public Boolean keyExists(Object sourceObj,String key){ } } + /** + * Checks if a given key exists within the given object with depper search. + *

+ * @param sourceObj + * Map, JsonNode or other Object able to parse to a Map type object. + * @param key + * the key name to lookup for in the given object. + * @param pathSep + * separator used to read keyPath like "." or "/" for example + * @param allowEmpty + * when true checks if the key exists even if the value is empty. + * + * @return true if the key exists in the given object, false otherwise. + * + * @throws UtilException + * if unable to parse the given object to a Map type class. + */ + @SuppressWarnings("Unused") public Boolean keyExistsDeep(Object sourceObj, String key, String pathSep, Boolean allowEmpty){ try { if(sourceObj == null){ @@ -195,6 +356,23 @@ public Boolean keyExistsDeep(Object sourceObj, String key, String pathSep, Boole } } + /** + * Checks if a list of given keys exists within the given object. + *

+ * @param sourceObj + * Map, JsonNode or other Object able to parse to a Map type object. + * @param keyPaths + * list of keys to look for in the given object. + * @param pathSep + * separator used to read keyPath like "." or "/" for example + * @param allowEmpty + * when true checks if the keys exists even if the value is empty. + * + * @return true if all the keys exists in the given object, false otherwise. + * + * @throws UtilException + * if unable to parse the given object to a Map type class. + */ public Boolean checkJsonKeys(Object sourceObj, List keyPaths, String pathSep, Boolean allowEmpty){ try { if(sourceObj == null){ @@ -223,7 +401,23 @@ public Boolean checkJsonKeys(Object sourceObj, List keyPaths, String pat } - + /** + * Gets the value of a given key from the given object. + *

+ * @param sourceObj + * Map, JsonNode or other Object able to parse to a Map type object. + * @param keyPath + * Path to the key in the given object. + * @param pathSep + * separator used to read keyPath like "." or "/" for example + * @param defaultValue + * to specify a default value if the value for the given keyPath doesn't exist. + * + * @return an {@Code Object} value of the given key or the default value if an error occurs. + * + * @throws UtilException + * if unable to parse the given object to a Map type class. + */ public Object getValue(Object sourceObj, String keyPath, String pathSep, Object defaultValue){ try { if(sourceObj == null){ @@ -261,18 +455,25 @@ public Object getValue(Object sourceObj, String keyPath, String pathSep, Object throw new UtilException(JsonUtil.class, "It was not possible to get value in path ["+keyPath+"] -> [" + e.getMessage() + "]"); } } - /* - * @param sourceObject: HashMap, JsonNode or other Object Able to parse to HashMap - * @param keyPath: Path to key in json - * @param keyValue: Value to update - * @param pathSep: Separator used to read keyPath like "." or "/" for example - * @param defaultValue: Default value returned in case of minor error. - * - * @throws UtilExeception when error is fatal - * - * @returns: - * defaultValue if error - * HashMap updated with new value (keyValue) in keyPath + + /** + * Sets the value of a given key from the given object. + *

+ * @param sourceObj + * Map, JsonNode or other Object able to parse to a Map type object. + * @param keyPath + * Path to the key in the given object. + * @param keyValue + * The value to update. + * @param pathSep + * separator used to read keyPath like "." or "/" for example + * @param defaultValue + * to specify a default value if the value for the given keyPath doesn't exist. + * + * @return an {@Code Object} of type Map updated with the given value. + * + * @throws UtilException + * if unable to parse the given object to a Map type class. */ public Object setValue(Object sourceObj, String keyPath, Object keyValue, String pathSep, Object defaultValue){ try { @@ -341,6 +542,18 @@ public Object setValue(Object sourceObj, String keyPath, Object keyValue, String throw new UtilException(JsonUtil.class, "It was not possible to set value in path ["+keyPath+"] -> [" + e.getMessage() + "] ["+e.getClass()+"]"); } } + + /** + * Parses the JSON string object to a JsonNode object. + *

+ * @param json + * the json object as a String + * + * @return a {@code JsonObject} object parsed with the json data. + * + * @throws UtilException + * if unable to parse the json string. + */ public JsonNode toJsonNode(String json){ ObjectMapper mapper = new ObjectMapper(); try { @@ -350,6 +563,17 @@ public JsonNode toJsonNode(String json){ } } + /** + * Parses the JSON Map object to a JsonNode object. + *

+ * @param json + * the json object as a map type class. + * + * @return a {@code JsonObject} object parsed with the json data. + * + * @throws UtilException + * if unable to parse the json map. + */ public JsonNode toJsonNode(Map json){ ObjectMapper mapper = new ObjectMapper(); try { @@ -359,7 +583,17 @@ public JsonNode toJsonNode(Map json){ } } - + /** + * Parses the JSON object to a Map type object. + *

+ * @param obj + * the json object with json properties annotations. + * + * @return a {@code JsonObject} object parsed with the json data. + * + * @throws UtilException + * if unable to parse the json object. + */ public Map toMap(Object obj){ ObjectMapper mapper = new ObjectMapper(); try { @@ -369,6 +603,19 @@ public Map toMap(Object obj){ } } + /** + * Binds the JsonNode object to the given class type object. + *

+ * @param jsonNode + * the json object as a JsonNode. + * @param bindClass + * the class type to map the JsonNode structure. + * + * @return a {@code Object} object parsed with the json data of the given type class. + * + * @throws UtilException + * if unable to parse the json object. + */ public Object bindJsonNode(JsonNode jsonNode, Class bindClass){ ObjectMapper mapper = new ObjectMapper(); try { @@ -377,6 +624,21 @@ public Object bindJsonNode(JsonNode jsonNode, Class bindClass){ throw new UtilException(JsonUtil.class, "It was not possible to parse json -> [" + e.getMessage() + "]"); } } + + /** + * Binds the json Map object to the given class type object. + *

+ * @param json + * the json object as a Map. + * @param bindClass + * the class type to map the json map structure. + * + * @return a {@code Object} object parsed with the json data of the given type class. + * + * @throws UtilException + * if unable to parse the json object. + */ + @SuppressWarnings("Unused") public Object bindMap(Map json, Class bindClass){ ObjectMapper mapper = new ObjectMapper(); try { @@ -385,6 +647,20 @@ public Object bindMap(Map json, Class bindClass){ throw new UtilException(JsonUtil.class, "It was not possible to parse json -> [" + e.getMessage() + "]"); } } + + /** + * Binds the json object to the given class type object. + *

+ * @param json + * the json object with json properties annotations. + * @param bindClass + * the class type to map the json object structure. + * + * @return a {@code Object} object parsed with the json data of the given type class. + * + * @throws UtilException + * if unable to parse the json object. + */ public Object bindObject(Object json, Class bindClass){ ObjectMapper mapper = new ObjectMapper(); try { @@ -394,6 +670,19 @@ public Object bindObject(Object json, Class bindClass){ } } + /** + * Binds the json object to the given type reference object. + *

+ * @param json + * the json object with json properties annotations. + * @param reference + * the type reference of an object to bind the json object. + * + * @return a {@code Object} object parsed with the json data of the given reference type object. + * + * @throws UtilException + * if unable to parse the json object. + */ public Object bindReferenceType (Object json, TypeReference reference) { ObjectMapper mapper = new ObjectMapper(); try{ diff --git a/consumer-backend/productpass/src/main/java/utils/LogUtil.java b/consumer-backend/productpass/src/main/java/utils/LogUtil.java index a8294f30c..6edb85883 100644 --- a/consumer-backend/productpass/src/main/java/utils/LogUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/LogUtil.java @@ -23,15 +23,17 @@ package utils; -import org.apache.juli.logging.Log; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; +import utils.exceptions.UtilException; -import java.util.Map; +/** + * This class consists exclusively of methods for logging purposes. + * + *

The methods defined here are intended to print all type of information for all type of Logs level when needed to log information. + * + */ public final class LogUtil { /** @@ -51,6 +53,13 @@ public final class LogUtil { + /** + * Log used for printing logs of level TEST and for usage on Unit Tests + *

+ * @param strMessage + * the String message intended to print on the log. + * + */ public static void printTest(String strMessage){ Level logLevel = TEST; Long pid = SystemUtil.getPid(); @@ -58,36 +67,110 @@ public static void printTest(String strMessage){ String message = "|"+pid+"|"+ memoryUsage+"| [" + logLevel.name()+"] " + strMessage; ThreadUtil.runThread(new LogPrinter(logLevel, message), "testLogThread"); } + + /** + * Log used for printing logs of level INFO + *

+ * @param strMessage + * the String message intended to print on the log. + * + */ public static void printMessage(String strMessage){ LogUtil.printLog(INFO, strMessage); } + + /** + * Log used for printing logs of level HTTP + *

+ * @param strMessage + * the String message intended to print on the log. + * + */ public static void printHTTPMessage(String strMessage){ LogUtil.printLog(HTTP, strMessage); } + + /** + * Log used for printing logs of level HTTPError + *

+ * @param strMessage + * the String message intended to print on the log. + * + */ public static void printHTTPErrorMessage(String strMessage){ LogUtil.printLog(HTTPError, strMessage); } + + /** + * Log used for printing logs Exceptions + *

+ * @param e + * the {@code Exception} object thrown. + * @param strMessage + * the String message intended to print on the log. + * + */ public static void printException(Exception e, String strMessage){ String message = " ["+e.getMessage()+"] "+strMessage; LogUtil.printLog(EXCEPTION, message); } + + /** + * Log used for printing logs of level ERROR + *

+ * @param strMessage + * the String message intended to print on the log. + * + */ public static void printError(String strMessage){ LogUtil.printLog(ERROR, strMessage); } + + /** + * Log used for printing logs of level WARNING + *

+ * @param strMessage + * the String message intended to print on the log. + * + */ public static void printWarning(String strMessage){ LogUtil.printLog(WARNING, strMessage); } + /** + * Log used for printing logs for Debugging. + *

+ * @param strMessage + * the String message intended to print on the log. + * + */ public static void printDebug(String strMessage) { Long pid = SystemUtil.getPid(); String memoryUsage = SystemUtil.getUsedHeapMemory(); - String message = "|"+pid+"|"+ memoryUsage+"| [DEBUG] " + strMessage; + String message = "|"+pid+"|"+ memoryUsage+"| ["+ DEBUG + "] " + strMessage; logger.debug(message); } + + /** + * Log used for printing logs of level STATUS + *

+ * @param strMessage + * the String message intended to print on the log. + * + */ public static void printStatus(String strMessage) { LogUtil.printLog(STATUS, strMessage); } + /** + * Log used for printing logs of a given level + *

+ * @param logLevel + * the intended level of log to print. + * @param strMessage + * the String message intended to print on the log. + * + */ public static void printLog(Level logLevel, String strMessage){ //String date = dateTimeTools.getDateTimeFormatted(null); Long pid = SystemUtil.getPid(); @@ -95,10 +178,22 @@ public static void printLog(Level logLevel, String strMessage){ String message = "|"+pid+"|"+ memoryUsage+"| [" + logLevel.name()+"] " + strMessage; logger.log(logLevel, message); } + + /** + * Log used for printing logs of level FATAL + *

+ * @param strMessage + * the String message intended to print on the log. + * + */ public static void printFatal(String strMessage){ LogUtil.printLog(FATAL, strMessage); } + /** + * This inner class consists exclusively to create a Runnable class to use with Threads for Logging. + * + */ private static class LogPrinter implements Runnable { private String message; diff --git a/consumer-backend/productpass/src/main/java/utils/NumericUtil.java b/consumer-backend/productpass/src/main/java/utils/NumericUtil.java index 8a0ef378e..f2db66b0f 100644 --- a/consumer-backend/productpass/src/main/java/utils/NumericUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/NumericUtil.java @@ -23,6 +23,7 @@ package utils; +@SuppressWarnings("Unused") public final class NumericUtil { /** * Static Tools to parse numbers if is possible diff --git a/consumer-backend/productpass/src/main/java/utils/PassportUtil.java b/consumer-backend/productpass/src/main/java/utils/PassportUtil.java index 02e1a55ef..7f5d343f0 100644 --- a/consumer-backend/productpass/src/main/java/utils/PassportUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/PassportUtil.java @@ -25,19 +25,22 @@ package utils; -import org.eclipse.tractusx.productpass.exceptions.ManagerException; import org.eclipse.tractusx.productpass.managers.ProcessManager; import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; -import org.eclipse.tractusx.productpass.models.edc.Jwt; import org.eclipse.tractusx.productpass.models.passports.Passport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import utils.exceptions.UtilException; -import java.io.File; import java.nio.file.Path; +/** + * This class consists exclusively of methods to operate on Passports. + * + *

The methods defined here are intended to read, save and parse Passport's type objects. + * + */ @Component public class PassportUtil { private final JsonUtil jsonUtil; @@ -53,6 +56,25 @@ public PassportUtil(JsonUtil jsonUtil, FileUtil fileUtil,ProcessManager processM this.fileUtil = fileUtil; this.processManager = processManager; } + + /** + * Saves the target {@code Passport} object to a JSON file. + *

+ * @param passport + * the passport object to save. + * @param endpointData + * the data plane object containing information related to the endpoint from where the specified passport was retrieved. + * @param prettyPrint + * boolean to specify a pretty or compact print of the passport into the JSON file. + * @param encrypted + * boolean to specify if the passport is to be saved with encryption. + * + * @return a {@code String} object representing the target JSON file path. + * + * @throws UtilException + * if unable to save the Passport to a JSON file. + */ + @SuppressWarnings("Unused") public String savePassport(Passport passport, DataPlaneEndpoint endpointData, Boolean prettyPrint, Boolean encrypted){ try { fileUtil.createDir(this.transferDir); @@ -63,6 +85,25 @@ public String savePassport(Passport passport, DataPlaneEndpoint endpointData, Bo } } + /** + * Saves the target {@code Passport} object to a JSON file specified by a {@code String} filePath. + *

+ * @param passport + * the passport object to save. + * @param endpointData + * the data plane object containing information related to the endpoint from where the specified passport was retrieved. + * @param prettyPrint + * boolean to specify a pretty or compact print of the passport into the JSON file. + * @param encrypted + * boolean to specify if the passport is to be saved with encryption. + * @param filePath + * the path representation to the target JSON file as a String. + * + * @return a {@code String} object representing the target JSON file path. + * + * @throws UtilException + * if unable to save the Passport to a JSON file. + */ public String savePassport(Passport passport, DataPlaneEndpoint endpointData, Boolean prettyPrint, Boolean encrypted, String filePath){ try { if(!encrypted) { diff --git a/consumer-backend/productpass/src/main/java/utils/ReflectionUtil.java b/consumer-backend/productpass/src/main/java/utils/ReflectionUtil.java index 320d64a7a..b6a59537e 100644 --- a/consumer-backend/productpass/src/main/java/utils/ReflectionUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/ReflectionUtil.java @@ -23,13 +23,34 @@ package utils; +import utils.exceptions.UtilException; + +/** + * This class consists exclusively of methods to operate at runtime execution (Reflection). + * + *

The methods defined here are intended to inspect, retrieve or manipulate other code in the same system at the runtime. + * + */ public final class ReflectionUtil { private ReflectionUtil() { throw new IllegalStateException("Tool/Utility Class Illegal Initialization"); } + + /** + * Gets the simple class name of a given {@code Class} object. + *

+ * @param classObj + * the Class object to retrieve the name. + * + * @return a {@code String} object representing the name of the Class. + * + * @throws UtilException + * if unable to read the YAML file. + */ public static String getCurrentClassName(Class classObj){ return classObj.getSimpleName(); } + @SuppressWarnings("Unused") public static Boolean classIsTest(Class classObj){ return ReflectionUtil.getCurrentClassName(classObj).contains("test"); } diff --git a/consumer-backend/productpass/src/main/java/utils/StringUtil.java b/consumer-backend/productpass/src/main/java/utils/StringUtil.java index 18003edf2..ec3951533 100644 --- a/consumer-backend/productpass/src/main/java/utils/StringUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/StringUtil.java @@ -23,6 +23,7 @@ package utils; +@SuppressWarnings("Unused") public final class StringUtil { private StringUtil() { throw new IllegalStateException("Tool/Utility Class Illegal Initialization"); diff --git a/consumer-backend/productpass/src/main/java/utils/SystemUtil.java b/consumer-backend/productpass/src/main/java/utils/SystemUtil.java index 23677a95c..cb5662ffa 100644 --- a/consumer-backend/productpass/src/main/java/utils/SystemUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/SystemUtil.java @@ -23,51 +23,135 @@ package utils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import java.io.File; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; +/** + * This class consists exclusively of methods to operate on System information. + * + *

The methods defined here are intended to give information related with System's usage (Memory, Disk, etc.). + * + */ public final class SystemUtil { + /** + * Returns the Memory usage by the Application. + *

+ * + * @return the result of the subtraction between the total memory and the estimated free memory left on the system. + * + */ public static Long getMemoryUsage(){ return SystemUtil.getTotalMemory() - SystemUtil.getFreeMemory(); } + + /** + * Returns the total amount of memory in the Java virtual machine. + *

+ * + * @return the total amount of memory currently available for current and future objects, measured in bytes. + * + */ public static Long getTotalMemory(){ return Runtime.getRuntime().totalMemory(); } + + /** + * Returns the native process Id for the application. + *

+ * + * @return the pid number given to the application by the Operating System. + * + */ public static Long getPid(){ return ProcessHandle.current().pid(); } + + /** + * Returns the remaining free memory in the Java virtual machine. + *

+ * + * @return an approximation to the total amount of memory currently available for future allocated objects, measured in bytes. + * + */ public static Long getFreeMemory(){ return Runtime.getRuntime().freeMemory(); } + /** + * Returns the amount of memory that is committed for the Java virtual machine to use. + * This amount of memory is guaranteed for the Java virtual machine to use. + *

+ * + * @return the amount of committed memory in bytes as a String. + * + */ public static String getCommitedMemory(){ MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); return String.format("%.2f",(double)memoryMXBean.getHeapMemoryUsage().getCommitted()/1073741824); } + + /** + * Returns the amount of memory that the Java virtual machine initially requests from the operating system for memory management. + *

+ * + * @return the initial size of memory in bytes as a String. + * + */ public static String getInitialMemory(){ MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); return String.format("%.2f",(double)memoryMXBean.getHeapMemoryUsage().getInit()/1073741824); } + + /** + * Returns the current memory usage of the heap that is used for object allocation. + *

+ * + * @return the amount of used memory in bytes as a String. + * + */ public static String getUsedHeapMemory(){ MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); return java.lang.String.format("%.2f",(double)memoryMXBean.getHeapMemoryUsage().getUsed()/1073741824); } + + /** + * Returns the maximum amount of memory that can be used for memory management. + *

+ * + * @return the maximum amount of memory in bytes as a String. + * + */ public static String getMaxHeapMemory(){ MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); return java.lang.String.format("%.2f",(double)memoryMXBean.getHeapMemoryUsage().getMax()/1073741824); } + /** + * Returns the amount of disk usage by the application. + *

+ * + * @return the result of the subtraction between the total size of the partition and the free space left on the system. + * + */ public static Long getDiskUsage(){ String path = FileUtil.getWorkdirPath(); File diskPartition = new File(path); return diskPartition.getTotalSpace() - diskPartition.getFreeSpace(); } + /** + * Gets an environment variable specified by the given {@code String} name + *

+ * @param name + * the name of the environment variable to look for. + * @param defaultValue + * the default value to return in case of not finding the environment variable. + * + * @return a {@code String} object representing the target environment variable. + * + */ public static String getEnvironmentVariable(String name, String defaultValue){ return System.getenv().getOrDefault(name, defaultValue); } diff --git a/consumer-backend/productpass/src/main/java/utils/ThreadUtil.java b/consumer-backend/productpass/src/main/java/utils/ThreadUtil.java index 793de9c45..d297d0800 100644 --- a/consumer-backend/productpass/src/main/java/utils/ThreadUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/ThreadUtil.java @@ -25,16 +25,35 @@ import java.util.ArrayList; import java.util.List; -import java.util.concurrent.*; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +/** + * This class consists exclusively of methods to operate on a Thread level. + * + *

The methods defined here are intended ease the use of Threads. + * + */ public final class ThreadUtil { private ThreadUtil() { throw new IllegalStateException("Tool/Utility Class Illegal Initialization"); } + + /** + * Runs a Task represented by the {@code Runnable} runnable. + *

+ * @param runnable + * the Runnable task that does not return a result. + */ + @SuppressWarnings("Unused") public static void runTask(Runnable runnable){ Executor executor = Executors.newSingleThreadExecutor(); executor.execute(runnable); } + + @SuppressWarnings("Unfinished") public static void runTask(Callable task,String name){ List> taskList = new ArrayList>(); taskList.add(task); @@ -48,12 +67,34 @@ public static void runTask(Callable task,String name){ //do something if you care about interruption; } } + + /** + * Creates and starts a Thread defined by a {@code Runnable} task and a {@code String} name. + *

+ * @param runnable + * the Runnable task that does not return a result. + * @param name + * the name given to this new thread. + * + * @return a {@code Thread} thread initialized to perform the intended task with the given name. + * + */ public static Thread runThread(Runnable runnable,String name){ Thread thread = new Thread(runnable, name); thread.start(); return thread; } + + /** + * Creates and starts a nameless Thread defined by a {@code Runnable} task. + *

+ * @param runnable + * the Runnable task that does not return a result. + * + * @return a {@code Thread} thread initialized to perform the intended task. + * + */ public static Thread runThread(Runnable runnable){ Thread thread = new Thread(runnable); thread.start(); @@ -61,6 +102,14 @@ public static Thread runThread(Runnable runnable){ return thread; } + /** + * Puts the scheduled thread in the runtime that this method is called to sleep for a given time. + *

+ * Note: In case of an exception, the thread put to sleep is interrupted. + *

+ * @param milliseconds + * the length of time to sleep in milliseconds. + */ public static void sleep(Integer milliseconds) { try diff --git a/consumer-backend/productpass/src/main/java/utils/YamlUtil.java b/consumer-backend/productpass/src/main/java/utils/YamlUtil.java index 649fe2982..c06eaa606 100644 --- a/consumer-backend/productpass/src/main/java/utils/YamlUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/YamlUtil.java @@ -24,22 +24,21 @@ package utils; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import utils.exceptions.UtilException; -import java.io.File; import java.io.FileInputStream; import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; import java.util.Map; +/** + * This class consists exclusively of methods to operate on YAML type files. + * + *

The methods defined here are intended to read, parse and dump YAML files. + * + */ @Component public final class YamlUtil { private final FileUtil fileUtil; @@ -48,6 +47,17 @@ public YamlUtil(FileUtil fileUtil) { this.fileUtil = fileUtil; } + /** + * Reads the target YAML file defined by the filePath. + *

+ * @param filePath + * the path to the target YAML file as a String. + * + * @return a {@code Map} object representing the target YAML file. + * + * @throws UtilException + * if unable to read the YAML file. + */ public Map readFile(String filePath) { try { InputStream inputStream = new FileInputStream(fileUtil.newFile(filePath)); @@ -58,6 +68,17 @@ public Map readFile(String filePath) { } } + /** + * Parses the target YAML file defined by the fileContent. + *

+ * @param fileContent + * the path representation to the target YAML file as a String. + * + * @return a {@code Map} object representing the target parsed YAML file. + * + * @throws UtilException + * if unable to read the YAML file. + */ public Map parseYml(String fileContent) { try { Yaml yaml = new Yaml(); @@ -67,6 +88,18 @@ public Map parseYml(String fileContent) { } } + /** + * Parses the target YAML file defined by the fileContent. + *

+ * @param fileContent + * the path representation to the target YAML file as an InputStream. + * + * @return a {@code Map} object representing the target parsed YAML file. + * + * @throws UtilException + * if unable to read the YAML file. + */ + @SuppressWarnings("Unused") public Map parseYmlStream(InputStream fileContent) { try { Yaml yaml = new Yaml(); @@ -76,6 +109,21 @@ public Map parseYmlStream(InputStream fileContent) { } } + /** + * Dumps the data defined by the {@code Map} map into a YAML File. + *

+ * @param map + * the {@code Map map, Integer indent, Boolean prettyPrint) { try { DumperOptions options = new DumperOptions(); @@ -88,6 +136,22 @@ public String dumpYml(Map map, Integer indent, Boolean prettyPri throw new UtilException(YamlUtil.class, "It was not possible to dump map into yaml " + e.getMessage()); } } + + /** + * Dumps the data defined by the {@code Object} map into a YAML File. + *

+ * @param obj + * the {@code Object} object representing the data to dump into a YAML file. + * @param indent + * the indent level for the YAML file, integer between 1 and 10. + * @param prettyPrint + * boolean to specify a pretty or compact dump + * + * @return a {@code String} object representing the target parsed YAML file. + * + * @throws UtilException + * if unable to dump the YAML file. + */ public String dumpYml(Object obj, Integer indent, Boolean prettyPrint) { try { DumperOptions options = new DumperOptions(); @@ -100,6 +164,8 @@ public String dumpYml(Object obj, Integer indent, Boolean prettyPrint) { throw new UtilException(YamlUtil.class, "It was not possible to dump map into yaml " + e.getMessage()); } } + + @SuppressWarnings("Unfinished") public Map getValue(String key) { try { return null; diff --git a/consumer-backend/productpass/src/main/java/utils/exceptions/UtilException.java b/consumer-backend/productpass/src/main/java/utils/exceptions/UtilException.java index 8d72fb3eb..dc58c96e6 100644 --- a/consumer-backend/productpass/src/main/java/utils/exceptions/UtilException.java +++ b/consumer-backend/productpass/src/main/java/utils/exceptions/UtilException.java @@ -23,10 +23,38 @@ package utils.exceptions; +/** + * This Exception class consists exclusively to treat Runtime Exceptions thrown in the Utils class. + * + *

The methods defined here are intended to gather information like the Class that thrown the exception, the message error and the exception for logging. + * + */ public class UtilException extends RuntimeException { + + /** + * Logs the given util class name and error message. + *

+ * @param tool + * the {@code Class} util class (e.g: JsonUtil, LogUtil, CatenaXUtil, etc.). + * @param errorMessage + * the {@code String} error message. + * + */ public UtilException(Class tool, String errorMessage) { super("["+tool.getName()+"] " + errorMessage); } + + /** + * Logs the given util class name, the {@code Exception} object and the error message. + *

+ * @param tool + * the {@code Class} util class (e.g: JsonUtil, LogUtil, CatenaXUtil, etc.). + * @param e + * the {@code Exception} object thrown. + * @param errorMessage + * the {@code String} error message. + * + */ public UtilException(Class tool, Exception e, String errorMessage) { super("["+tool.getName()+"] " + errorMessage+", "+e.getMessage()); } diff --git a/consumer-backend/productpass/src/main/resources/application.yml b/consumer-backend/productpass/src/main/resources/application.yml index 98fa990ab..d163a17ac 100644 --- a/consumer-backend/productpass/src/main/resources/application.yml +++ b/consumer-backend/productpass/src/main/resources/application.yml @@ -72,10 +72,10 @@ configuration: digitalTwin: "/shell-descriptors" subModel: "/submodel-descriptors" timeouts: - search: 10 - negotiation: 40 - transfer: 10 - digitalTwin: 20 + search: 100 + negotiation: 100 + transfer: 100 + digitalTwin: 120 temporaryStorage: true discovery: @@ -98,8 +98,16 @@ configuration: encrypt: true indent: true dir: "data/transfer" - versions: - - 'v3.0.1' + digitalProductPass: + versions: + - '1.0.0' + semanticId: "urn:bamm:io.catenax.generic.digital_product_passport" + aspectId: "DigitalProductPassport" + batteryPass: + versions: + - '3.0.1' + semanticId: "urn:bamm:io.catenax.battery.battery_pass" + aspectId: "BatteryPass" vault: type: 'local'