diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..acb74c498e6f45d16d48a10480856e7401e0d2fd --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target +*.iml +.classpath +.project \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..40be386b981d8564ef04539edebb44dc6a389d39 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,40 @@ +include: + - project: osl/code/org.etsi.osl.main + ref: main + file: + - ci-templates/default.yml + - ci-templates/build.yml + rules: + - if: '$CI_COMMIT_REF_NAME == "main"' + + - project: osl/code/org.etsi.osl.main + ref: develop + file: + - ci-templates/default.yml + - ci-templates/build.yml + rules: + - if: '$CI_COMMIT_REF_NAME == "develop"' + + - project: osl/code/org.etsi.osl.main + ref: $CI_COMMIT_REF_NAME + file: + - ci-templates/default.yml + - ci-templates/build.yml + rules: + - if: '$CI_COMMIT_REF_PROTECTED == "true" && $CI_COMMIT_REF_NAME != "main" && $CI_COMMIT_REF_NAME != "develop"' + + - project: osl/code/org.etsi.osl.main + ref: develop + file: + - ci-templates/default.yml + - ci-templates/build_unprotected.yml + rules: + - if: '$CI_COMMIT_REF_NAME != "main" && $CI_COMMIT_REF_NAME != "develop" && $CI_COMMIT_REF_PROTECTED == "false"' + +maven_build: + extends: .maven_build + +docker_build: + extends: .docker_build + needs: + - maven_build diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000000000000000000000000000000000000..18308defdbd17a8bd5837fef98d92d04e0014ed4 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,6 @@ +eclipse.preferences.version=1 +encoding//src/main/java=utf-8 +encoding//src/main/resources=utf-8 +encoding//src/test/java=utf-8 +encoding//src/test/resources=utf-8 +encoding/<project>=UTF-8 diff --git a/.settings/org.eclipse.jdt.apt.core.prefs b/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 0000000000000000000000000000000000000000..dfa4f3adb289a4f7d73e0694f9045f99325604d7 --- /dev/null +++ b/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=true +org.eclipse.jdt.apt.genSrcDir=target/generated-sources/annotations +org.eclipse.jdt.apt.genTestSrcDir=target/generated-test-sources/test-annotations diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000000000000000000000000000000000..87f474ba76f5340f448a1601feef33881f04043b --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,9 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=17 +org.eclipse.jdt.core.compiler.compliance=17 +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore +org.eclipse.jdt.core.compiler.processAnnotations=enabled +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=17 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000000000000000000000000000000000000..f897a7f1cb2389f85fe6381425d29f0a9866fb65 --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..08d8bc13d63e35aa8b69d9258c6360089a510d4d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,5 @@ +FROM ibm-semeru-runtimes:open-17.0.7_7-jdk +RUN mkdir /opt/shareclasses +RUN mkdir -p /opt/openslice/lib/ +COPY target/org.etsi.osl.metrico-0.9-exec.jar /opt/openslice/lib/ +CMD ["java", "-Xshareclasses:cacheDir=/opt/shareclasses", "-jar", "/opt/openslice/lib/org.etsi.osl.metrico-0.9-exec.jar"] diff --git a/Documentation/Documentation.md b/Documentation/Documentation.md new file mode 100644 index 0000000000000000000000000000000000000000..34eb57ab996b0cead8f1f447af7eb19af1f8a605 --- /dev/null +++ b/Documentation/Documentation.md @@ -0,0 +1,23 @@ +# Metrics Component (METRICO) + +## Definitions of the problem + +Services (& resources) created through OSL provide a vast amount of data and metrics. The data can be used to perform actions on the said services. Up until now (OSL v1.0) external tools are used to leverage those data. + +The goal of this feature is to create a mechanism that, through OSL, can retrieve the data and return them to the services (and/or resources) they are associated with. + +This goal creates challenges on multiple levels: + +* How does OSL retrieves data that come from multiple, non-homogenous environments? +* How does OSL associates the data with their respective services? +* How the services receive the data that were retrieved by the MDAS? +* What mechanisms are trigered to perform actions based on the data recieved? + +Most of the above challenges can be split in further tecnhical and technology challenges. + +## High Level Design + +* METRICO enables users to retrieve metrics monitored via a Prometheus. +* The infrastructure has to be monitored with any monitoring tool that has a Prometheus exporter and will export the collected data to a Prometheus. + + diff --git a/Documentation/FlowDiagram.puml b/Documentation/FlowDiagram.puml new file mode 100644 index 0000000000000000000000000000000000000000..288b565f4542eff08ec4397057974fce7fe507f6 --- /dev/null +++ b/Documentation/FlowDiagram.puml @@ -0,0 +1,39 @@ +@startuml FlowDiagram +actor "ACTOR" as actor +participant "OSOM" as osom +participant "TMF API" as tmf_api +queue amq as amq +participant "METRICO" as metrico +participant prometheus as prom + + +actor -> tmf_api: CREATE: Service Order Monitoring aaS +osom -> osom: PROCESS ORDER + +osom -> tmf_api: CREATE: service instance of monitoring aaS (RFS)(Initial Status: Reseved) +osom -> tmf_api: CREATE: service instance of monitoring aaS (CFS)(Initial Status: Reseved) + +osom -> amq: CREATE: TMF628 Measurement Collection Job \n<color:green>queue:PM_MEASUREMENT_COLLECTION_JOB_ADD \n<color:green>payload: MeasurementCollectionJobFVO +amq -> tmf_api: CREATE: TMF628 Measurement Collection Job \n<color:green>queue:PM_MEASUREMENT_COLLECTION_JOB_ADD \n<color:green>payload: MeasurementCollectionJobFVO (Here I can find the MCJ ID) +tmf_api -> amq: CREATE: TMF628 Measurement Collection Job \n<color:green>queue:PM_MEASUREMENT_COLLECTION_JOB_ADD \n<color:green>payload: MeasurementCollectionJob (Here I can find the MCJ ID) +osom -> tmf_api: CREATE: Resource Instance (Initial Status: Reseved)(associate to RFS)(add the MCJ UUID) +amq -> osom: CREATE: TMF628 Measurement Collection Job \n<color:green>queue:PM_MEASUREMENT_COLLECTION_JOB_ADD \n<color:green>payload: MeasurementCollectionJob (Here I can find the MCJ ID) +tmf_api -> amq: PUBLISH EVENT: Monitoring Job Created\n<color:green>topic: PM_MEASUREMENT_COLLECTION_JOB_CREATED\n<color:green>payload: Measurement Collection Job Ref +amq -> metrico: RECEIVE EVENT: Monitoring Job Created\n<color:green>topic: PM_MEASUREMENT_COLLECTION_JOB_CREATED\n<color:green>payload: Measurement Collection Job Ref +metrico -> tmf_api: fetch Measurement Collection Job from ref +tmf_api -> metrico: fetch Measurement Collection Job from ref +metrico -> metrico: create METRICO job +metrico -> amq: UPDATE Measurement Collection Job Status + + +group "java job" + metrico -> metrico : set how often job is done + metrico -> prom : send prom req + prom -> metrico : reply to prom req + metrico -> metrico : parse data from reply and cast them to data access endpoint + + metrico -> amq : UPDATE: Related service to the Service Inventory\n<color:green>queue:jms:queue:CATALOG.UPD.SERVICE \n<color:green>payload: ServiceUpdate, serviceId + amq -> tmf_api: UPDATE: Related service to the Service Inventory\n<color:green>queue:jms:queue:CATALOG.UPD.SERVICE \n<color:green>payload: ServiceUpdate, serviceId +end + +@enduml \ No newline at end of file diff --git a/ci_settings.xml b/ci_settings.xml new file mode 100644 index 0000000000000000000000000000000000000000..69ad06ed6c63795d191555afde6ea2d1da4e133d --- /dev/null +++ b/ci_settings.xml @@ -0,0 +1,16 @@ +<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd"> + <servers> + <server> + <id>gitlab-maven</id> + <configuration> + <httpHeaders> + <property> + <name>Job-Token</name> + <value>${CI_JOB_TOKEN}</value> + </property> + </httpHeaders> + </configuration> + </server> + </servers> +</settings> diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..932fca3e36ba6295899c70f2e40199ff04a1c806 --- /dev/null +++ b/pom.xml @@ -0,0 +1,314 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.etsi.osl</groupId> + <artifactId>org.etsi.osl.main</artifactId> + <version>2024Q4</version> + <relativePath>../org.etsi.osl.main</relativePath> + </parent> + + + <artifactId>org.etsi.osl.metrico</artifactId> + <name>org.etsi.osl.metrico</name> + <version>${org.etsi.osl.metrico.version}</version> + + + <organization> + <name>OpenSlice by ETSI</name> + <url>https://osl.etsi.org</url> + </organization> + + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> + <spring.boot-version>3.2.2</spring.boot-version> + <spring.boot-version>${spring-boot-version}</spring.boot-version> + <camel.version>4.0.0-RC1</camel.version> + <slf4j-api.version>1.7.5</slf4j-api.version> + <slf4j-simple.version>1.7.28</slf4j-simple.version> + <mysql-connector.version>${mysql.connector.version}</mysql-connector.version> + </properties> + + <repositories> + <repository> + <id>gitlab-maven</id> + <url>https://labs.etsi.org/rep/api/v4/groups/260/-/packages/maven</url> + </repository> + </repositories> + <distributionManagement> + <repository> + <id>gitlab-maven</id> + <url>${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/maven</url> + </repository> + <snapshotRepository> + <id>gitlab-maven</id> + <url>${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/maven</url> + </snapshotRepository> + </distributionManagement> + + <dependencyManagement> + <dependencies> + <!-- Spring Boot BOM --> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-dependencies</artifactId> + <version>${spring.boot-version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + + <!-- Camel BOM --> + <dependency> + <groupId>org.apache.camel.springboot</groupId> + <artifactId>camel-spring-boot-dependencies</artifactId> + <version>${camel.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> + </dependencyManagement> + + <dependencies> + <!-- org.etsi.osl --> + <dependency> + <groupId>org.etsi.osl</groupId> + <artifactId>org.etsi.osl.model.tmf</artifactId> + <version>${org.etsi.osl.model.tmf.version}</version> + </dependency> + <dependency> + <groupId>org.etsi.osl</groupId> + <artifactId>org.etsi.osl.centrallog.client</artifactId> + <version>${org.etsi.osl.centrallog.client.version}</version> + </dependency> + +<!-- Lombok --> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-actuator</artifactId> + </dependency> + + <!-- security --> + + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-webflux</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.security</groupId> + <artifactId>spring-security-oauth2-client</artifactId> + </dependency> + +<!-- activeMQ --> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-activemq</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-amqp</artifactId> + <scope>test</scope> + <exclusions> + <exclusion> + <groupId>org.apache.qpid</groupId> + <artifactId>proton-j</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.messaginghub</groupId> + <artifactId>pooled-jms</artifactId> + </dependency> + + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + </dependency> + + <!-- Camel --> + <dependency> + <groupId>org.apache.camel.springboot</groupId> + <artifactId>camel-spring-boot-starter</artifactId> + </dependency> + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-pool</artifactId> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-activemq</artifactId> + <exclusions> + <exclusion> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-broker</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.apache.camel.springboot</groupId> + <artifactId>camel-service-starter</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.camel.springboot</groupId> + <artifactId>camel-http-starter</artifactId> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-jackson</artifactId> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-stream</artifactId> + </dependency> + + + <!-- slf4j --> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-simple</artifactId> + </dependency> + + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </dependency> + + <dependency> + <groupId>mysql</groupId> + <artifactId>mysql-connector-java</artifactId> + <scope>runtime</scope> + <version>${mysql-connector.version}</version> + </dependency> + + + <!-- Testing --> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-api</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>5.7.0</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-test-autoconfigure</artifactId> + <version>3.2.2</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-test</artifactId> + <version>6.1.3</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.data</groupId> + <artifactId>spring-data-jpa</artifactId> + </dependency> + + </dependencies> + + <build> + <pluginManagement> + <plugins> + <plugin> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-maven-plugin</artifactId> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <source>17</source> + <target>17</target> + <annotationProcessorPaths> + <path> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <version>1.18.28</version> + </path> + </annotationProcessorPaths> + </configuration> + </plugin> + <plugin> + <!-- run mvn license:update-file-header to manually update all headers + everywhere --> + <groupId>org.codehaus.mojo</groupId> + <artifactId>license-maven-plugin</artifactId> + <version>${maven-license-plugin.version}</version> + <configuration> + <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage> + <processStartTag>========================LICENSE_START=================================</processStartTag> + <processEndTag>=========================LICENSE_END==================================</processEndTag> + <excludes>*.json</excludes> + </configuration> + <executions> + <execution> + <id>generate-license-headers</id> + <goals> + <goal>update-file-header</goal> + </goals> + <phase>process-sources</phase> + <configuration> + <licenseName>${license.licenseName}</licenseName> + + </configuration> + </execution> + <execution> + <id>download-licenses</id> + <goals> + <goal>download-licenses</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </pluginManagement> + <plugins> + <plugin> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-maven-plugin</artifactId> + <version>${spring-boot-version}</version> + <configuration> + <classifier>exec</classifier> + </configuration> + <executions> + <execution> + <goals> + <goal>repackage</goal> + </goals> + </execution> + </executions> + </plugin> + + </plugins> + + </build> + + + +</project> diff --git a/src/main/java/org/etsi/osl/metrico/JsonUtil.java b/src/main/java/org/etsi/osl/metrico/JsonUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..a801f496c5f22d232892748989ed761609770583 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/JsonUtil.java @@ -0,0 +1,28 @@ +package org.etsi.osl.metrico; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJobMVO; + +import java.io.IOException; + +public class JsonUtil { + + public static <T> T toJsonObj(String content, Class<T> valueType) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.readValue( content, valueType); + } + + public static <T> String toJsonString(T object) { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + try { + return mapper.writeValueAsString(object); + } catch (JsonProcessingException e) { + e.printStackTrace(); + return null; + } + } +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/LocalMysqlDialect.java b/src/main/java/org/etsi/osl/metrico/LocalMysqlDialect.java new file mode 100644 index 0000000000000000000000000000000000000000..1d8566cf19b079f1a5e574bb55443a0f4e6694cf --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/LocalMysqlDialect.java @@ -0,0 +1,29 @@ +/*- + * ========================LICENSE_START================================= + * org.etsi.osl.tmf.api + * %% + * Copyright (C) 2019 openslice.io + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * =========================LICENSE_END================================== + */ +package org.etsi.osl.metrico; + +import org.hibernate.dialect.MySQLDialect; ; + +public class LocalMysqlDialect extends MySQLDialect { + @Override + public String getTableTypeString() { + return " DEFAULT CHARSET=utf8"; + } +} diff --git a/src/main/java/org/etsi/osl/metrico/MetricoSpringBoot.java b/src/main/java/org/etsi/osl/metrico/MetricoSpringBoot.java new file mode 100644 index 0000000000000000000000000000000000000000..1040f0d5d3c861295cfe551fff73ba0c46cb3643 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/MetricoSpringBoot.java @@ -0,0 +1,75 @@ +package org.etsi.osl.metrico; + +import org.etsi.osl.metrico.services.MetricoService; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJob; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJobRef; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.context.event.ApplicationStartedEvent; +import org.springframework.context.ApplicationContext; +import org.springframework.context.event.EventListener; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import jakarta.validation.constraints.NotNull; + + +@SpringBootApplication +@EnableJpaRepositories("org.etsi.osl.metrico.repo") +@EntityScan( basePackages = { + "org.etsi.osl.metrico.repo", + "org.etsi.osl.metrico.model", + "org.etsi.osl.metrico", + "org.etsi.osl.metrico.reposervices", + "org.etsi.osl.metrico.services" +}) + public class MetricoSpringBoot implements CommandLineRunner { + + private static final Logger logger = + LoggerFactory.getLogger(MetricoSpringBoot.class.getSimpleName()); + +// +// @Autowired +// private MetricoService aMetricoService; + + + @Override + public void run(String... arg0) { + if (arg0.length > 0 && arg0[0].equals("exitcode")) { + throw new ExitException(); + } + + +// @NotNull +// MeasurementCollectionJob mcj = new MeasurementCollectionJob(); +// +// @NotNull +// MeasurementCollectionJobRef mjref = new MeasurementCollectionJobRef(); +// mjref.setId("268cd191-21ac-4a81-84d8-933445a65ec1"); +// aMetricoService.startPeriodicQueryToPrometheusRef(mjref ); + } + + + + public static void main(String[] args) { + logger.info("============================== STARTING METRICO =============================="); + ApplicationContext applicationContext = new SpringApplication(MetricoSpringBoot.class).run(args); + + + + + } + + static class ExitException extends RuntimeException implements ExitCodeGenerator { + private static final long serialVersionUID = 1L; + @Override + public int getExitCode() { + return 10; + } + } + +} diff --git a/src/main/java/org/etsi/osl/metrico/mapper/AttachmentRefMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/AttachmentRefMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..f5138b6a7b033e0c4b3328f1b82c3af07d4af825 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/AttachmentRefMapper.java @@ -0,0 +1,32 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.common.model.AttachmentRef; +import org.etsi.osl.tmf.pm628.model.AttachmentRefMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface AttachmentRefMapper { + AttachmentRefMapper INSTANCE = Mappers.getMapper(AttachmentRefMapper.class); + + @Mapping(source = "id", target = "id") + @Mapping(source = "description", target = "description") + @Mapping(source = "url", target = "url") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "type", target = "type") + @Mapping(source = "atBaseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + AttachmentRef toAttachmentRef(AttachmentRefMVO attachmentRefMVO); + + @Mapping(source = "id", target = "id") + @Mapping(source = "description", target = "description") + @Mapping(source = "url", target = "url") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + AttachmentRefMVO toAttachmentRefMVO(AttachmentRef attachmentRef); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/CharacteristicMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/CharacteristicMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..8aebd1e460cebb387b198531bfa110feea5e3035 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/CharacteristicMapper.java @@ -0,0 +1,30 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.Characteristic; +import org.etsi.osl.tmf.pm628.model.CharacteristicMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = {CharacteristicRelationshipMapper.class}) +public interface CharacteristicMapper { + CharacteristicMapper INSTANCE = Mappers.getMapper(CharacteristicMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "valueType", target = "valueType") + @Mapping(source = "characteristicRelationship", target = "characteristicRelationship") + Characteristic toCharacteristic(CharacteristicMVO characteristicMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "valueType", target = "valueType") + @Mapping(source = "characteristicRelationship", target = "characteristicRelationship") + CharacteristicMVO toCharacteristicMVO(Characteristic characteristic); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/CharacteristicRelationshipMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/CharacteristicRelationshipMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..00d87e52254b760e9bc54c65cf84798fc8cf296d --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/CharacteristicRelationshipMapper.java @@ -0,0 +1,26 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.CharacteristicRelationship; +import org.etsi.osl.tmf.pm628.model.CharacteristicRelationshipMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface CharacteristicRelationshipMapper { + CharacteristicRelationshipMapper INSTANCE = Mappers.getMapper(CharacteristicRelationshipMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "relationshipType", target = "relationshipType") + CharacteristicRelationship toCharacteristicRelationship(CharacteristicRelationshipMVO characteristicRelationshipMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "relationshipType", target = "relationshipType") + CharacteristicRelationshipMVO toCharacteristicRelationshipMVO(CharacteristicRelationship characteristicRelationship); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/DataAccessEndpointMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/DataAccessEndpointMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..96188c5cfea4f9507820c31c0d7d00ad19e1af24 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/DataAccessEndpointMapper.java @@ -0,0 +1,45 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.DataAccessEndpoint; +import org.etsi.osl.tmf.pm628.model.DataAccessEndpointMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface DataAccessEndpointMapper { + DataAccessEndpointMapper INSTANCE = Mappers.getMapper(DataAccessEndpointMapper.class); + + @Mapping(target = "type", source = "type") + @Mapping(target = "baseType", source = "baseType") + @Mapping(target = "schemaLocation", source = "schemaLocation") + @Mapping(target = "href", source = "href") + @Mapping(target = "uuid", source = "uuid") + @Mapping(target = "category", source = "category") + @Mapping(target = "description", source = "description") + @Mapping(target = "name", source = "name") + @Mapping(target = "endOperatingDate", source = "endOperatingDate") + @Mapping(target = "administrativeState", source = "administrativeState") + @Mapping(target = "operationalState", source = "operationalState") + @Mapping(target = "resourceStatus", source = "resourceStatus") + @Mapping(target = "usageState", source = "usageState") + @Mapping(target = "validFor", source = "validFor") + @Mapping(target = "note", source = "note") + @Mapping(target = "resourceOrderItem", source = "resourceOrderItem") + @Mapping(target = "place", source = "place") + @Mapping(target = "relatedParty", source = "relatedParty") + @Mapping(target = "resourceRelationship", source = "resourceRelationship") + @Mapping(target = "resourceCharacteristic", source = "resourceCharacteristic") + @Mapping(target = "attachment", source = "attachment") + @Mapping(target = "resourceSpecification", source = "resourceSpecification") + @Mapping(target = "startOperatingDate", source = "startOperatingDate") + @Mapping(target = "resourceVersion", source = "resourceVersion") + @Mapping(target = "activationFeature", source = "activationFeature") + @Mapping(target = "intent", source = "intent") + @Mapping(target = "externalIdentifier", source = "externalIdentifier") + @Mapping(target = "value", source = "value") + @Mapping(target = "uri", source = "uri") + @Mapping(target = "uriQueryFilter", source = "uriQueryFilter") + @Mapping(target = "apiType", source = "apiType") + DataAccessEndpointMVO toDataAccessEndpointMVO(DataAccessEndpoint dataAccessEndpoint); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/DataFilterMapItemMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/DataFilterMapItemMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..cc2586162422c2d00476d84e6cbc4732ad4745b5 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/DataFilterMapItemMapper.java @@ -0,0 +1,23 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.DataFilterMapItem; +import org.etsi.osl.tmf.pm628.model.DataFilterMapItemMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +//@Mapper(uses = { +// DataFilterTemplateMapper.class, +// DataFilterAttributeStringArrayMapper.class +//}) +public interface DataFilterMapItemMapper { + DataFilterMapItemMapper INSTANCE = Mappers.getMapper(DataFilterMapItemMapper.class); + + @Mapping(source = "filterTemplate", target = "filterTemplate") + @Mapping(source = "stringArray", target = "stringArray") + DataFilterMapItem toDataFilterMapItem(DataFilterMapItemMVO dataFilterMapItemMVO); + + @Mapping(source = "filterTemplate", target = "filterTemplate") + @Mapping(source = "stringArray", target = "stringArray") + DataFilterMapItemMVO toDataFilterMapItemMVO(DataFilterMapItem dataFilterMapItem); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/DataFilterMapMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/DataFilterMapMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..a61597f5734fdd99c0dfac7fbfc724afe77b670f --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/DataFilterMapMapper.java @@ -0,0 +1,26 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.DataFilterMap; +import org.etsi.osl.tmf.pm628.model.DataFilterMapMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + DataFilterMapItemMapper.class +}) +public interface DataFilterMapMapper { + DataFilterMapMapper INSTANCE = Mappers.getMapper(DataFilterMapMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "mappings", target = "mappings") + DataFilterMap toDataFilterMap(DataFilterMapMVO dataFilterMapMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "mappings", target = "mappings") + DataFilterMapMVO toDataFilterMapMVO(DataFilterMap dataFilterMap); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/DataFilterTemplateMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/DataFilterTemplateMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..64c4f110dfd4703f65a71027844c3aaba60502ea --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/DataFilterTemplateMapper.java @@ -0,0 +1,30 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.DataFilterTemplate; +import org.etsi.osl.tmf.pm628.model.DataFilterTemplateMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface DataFilterTemplateMapper { + DataFilterTemplateMapper INSTANCE = Mappers.getMapper(DataFilterTemplateMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "id", target = "id") + @Mapping(source = "href", target = "href") + @Mapping(source = "name", target = "name") + @Mapping(source = "description", target = "description") + DataFilterTemplate toDataFilterTemplate(DataFilterTemplateMVO dataFilterTemplateMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "id", target = "id") + @Mapping(source = "href", target = "href") + @Mapping(source = "name", target = "name") + @Mapping(source = "description", target = "description") + DataFilterTemplateMVO toDataFilterTemplateMVO(DataFilterTemplate dataFilterTemplate); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/DayOfMonthRecurrenceMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/DayOfMonthRecurrenceMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..62836b015fc418e2f0530d81898212830fc997dc --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/DayOfMonthRecurrenceMapper.java @@ -0,0 +1,24 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.DayOfMonthRecurrence; +import org.etsi.osl.tmf.pm628.model.DayOfMonthRecurrenceMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface DayOfMonthRecurrenceMapper { + DayOfMonthRecurrenceMapper INSTANCE = Mappers.getMapper(DayOfMonthRecurrenceMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "dates", target = "dates") + DayOfMonthRecurrence toDayOfMonthRecurrence(DayOfMonthRecurrenceMVO dayOfMonthRecurrenceMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "dates", target = "dates") + DayOfMonthRecurrenceMVO toDayOfMonthRecurrenceMVO(DayOfMonthRecurrence dayOfMonthRecurrence); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/DayOfWeekRecurrenceMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/DayOfWeekRecurrenceMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..a4b857d59ddb3d26f8cce251977cc89eb59f94d9 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/DayOfWeekRecurrenceMapper.java @@ -0,0 +1,24 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.DayOfWeekRecurrence; +import org.etsi.osl.tmf.pm628.model.DayOfWeekRecurrenceMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface DayOfWeekRecurrenceMapper { + DayOfWeekRecurrenceMapper INSTANCE = Mappers.getMapper(DayOfWeekRecurrenceMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "dates", target = "dates") + DayOfWeekRecurrence toDayOfWeekRecurrence(DayOfWeekRecurrenceMVO dayOfWeekRecurrenceMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "dates", target = "dates") + DayOfWeekRecurrenceMVO toDayOfWeekRecurrenceMVO(DayOfWeekRecurrence dayOfWeekRecurrence); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/ExternalIdentifierMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/ExternalIdentifierMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..0e825648d205cfe94d3cb5b264c3dd1a7fa44ad1 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/ExternalIdentifierMapper.java @@ -0,0 +1,28 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.ExternalIdentifier; +import org.etsi.osl.tmf.pm628.model.ExternalIdentifierMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface ExternalIdentifierMapper { + ExternalIdentifierMapper INSTANCE = Mappers.getMapper(ExternalIdentifierMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "owner", target = "owner") + @Mapping(source = "externalIdentifierType", target = "externalIdentifierType") + @Mapping(source = "id", target = "id") + ExternalIdentifier toExternalIdentifier(ExternalIdentifierMVO externalIdentifierMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "owner", target = "owner") + @Mapping(source = "externalIdentifierType", target = "externalIdentifierType") + @Mapping(source = "id", target = "id") + ExternalIdentifierMVO toExternalIdentifierMVO(ExternalIdentifier externalIdentifier); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/FeatureMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/FeatureMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..fff7bcdb75fe934e833ff719c4bdaa092e393466 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/FeatureMapper.java @@ -0,0 +1,34 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.Feature; +import org.etsi.osl.tmf.pm628.model.FeatureMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface FeatureMapper { + FeatureMapper INSTANCE = Mappers.getMapper(FeatureMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "name", target = "name") + @Mapping(source = "isBundle", target = "isBundle") + @Mapping(source = "featureRelationship", target = "featureRelationship") + @Mapping(source = "featureCharacteristic", target = "featureCharacteristic") + @Mapping(source = "policyConstraint", target = "policyConstraint") + @Mapping(source = "isEnabled", target = "isEnabled") + Feature toFeature(FeatureMVO featureMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "name", target = "name") + @Mapping(source = "isBundle", target = "isBundle") + @Mapping(source = "featureRelationship", target = "featureRelationship") + @Mapping(source = "featureCharacteristic", target = "featureCharacteristic") + @Mapping(source = "policyConstraint", target = "policyConstraint") + @Mapping(source = "isEnabled", target = "isEnabled") + FeatureMVO toFeatureMVO(Feature feature); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/FileTransferDataMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/FileTransferDataMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..33f90d79b712cc7cd2c0394163d31c7b5aa300a0 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/FileTransferDataMapper.java @@ -0,0 +1,32 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.FileTransferData; +import org.etsi.osl.tmf.pm628.model.FileTransferDataMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface FileTransferDataMapper { + FileTransferDataMapper INSTANCE = Mappers.getMapper(FileTransferDataMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "fileLocation", target = "fileLocation") + @Mapping(source = "fileFormat", target = "fileFormat") + @Mapping(source = "compressionType", target = "compressionType") + @Mapping(source = "retentionPeriod", target = "retentionPeriod") + @Mapping(source = "packingType", target = "packingType") + FileTransferDataMVO toFileTransferDataMVO(FileTransferData fileTransferData); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "fileLocation", target = "fileLocation") + @Mapping(source = "fileFormat", target = "fileFormat") + @Mapping(source = "compressionType", target = "compressionType") + @Mapping(source = "retentionPeriod", target = "retentionPeriod") + @Mapping(source = "packingType", target = "packingType") + FileTransferData toFileTransferData(FileTransferDataMVO fileTransferDataMVO); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/IntentRefMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/IntentRefMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..f631d622522ed4fff54a8e4a3bf391592595a9a8 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/IntentRefMapper.java @@ -0,0 +1,30 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.IntentRef; +import org.etsi.osl.tmf.pm628.model.IntentRefMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface IntentRefMapper { + IntentRefMapper INSTANCE = Mappers.getMapper(IntentRefMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "id", target = "id") + @Mapping(source = "name", target = "name") + @Mapping(source = "referredType", target = "referredType") + IntentRef toIntentRef(IntentRefMVO intentRefMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "id", target = "id") + @Mapping(source = "name", target = "name") + @Mapping(source = "referredType", target = "referredType") + IntentRefMVO toIntentRefMVO(IntentRef intentRef); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/JobMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/JobMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..0597011eb7e51f6691cf84307bb924a00f9309ab --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/JobMapper.java @@ -0,0 +1,97 @@ +package org.etsi.osl.metrico.mapper; + +import jakarta.validation.Valid; +import org.etsi.osl.metrico.model.Job; +import org.etsi.osl.metrico.model.SupportedDataAccessEndpoints; +import org.etsi.osl.tmf.pm628.model.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The {@code JobMapper} class provides methods to map between different job representations. + */ +public class JobMapper { + + private static final Logger logger = LoggerFactory.getLogger(JobMapper.class); + + /** + * Maps a {@link MeasurementCollectionJob} to a {@link Job}. + * + * @param measurementCollectionJob the measurement collection job to map + * @return the mapped job + * @throws IllegalArgumentException if the data access endpoint is not exactly one, + * if the API type is not supported or not defined, + * if the data access endpoint URI is null, + * or if there is not exactly one query + */ + + public static Job measurementCollectionJobMapToJob(MeasurementCollectionJob measurementCollectionJob) { + Job job = new Job(); + + job.setMeasurementCollectionJobRef(UUID.fromString(measurementCollectionJob.getUuid())); + + if(measurementCollectionJob.getDataAccessEndpoint().size()!=1){ // DataAccessEndpoint will provide the Monitoring API IP + throw new IllegalArgumentException("DataAccessEndpoint should be exactly one"); + }else { + DataAccessEndpoint dataAccessEndpoint = measurementCollectionJob.getDataAccessEndpoint().get(0); + job.setDataAccessEndPointRef(UUID.fromString(dataAccessEndpoint.getUuid())); + + if (SupportedDataAccessEndpoints.contains(dataAccessEndpoint.getApiType())) { // SupportedDataAccessEndpoints is an ENUM with all the supported API types + job.setApiType(dataAccessEndpoint.getApiType()); + } else if (dataAccessEndpoint.getApiType() == null) { + throw new IllegalArgumentException("API type needs to be defined"); + } else { + throw new IllegalArgumentException("API type " + dataAccessEndpoint.getApiType() + " not supported"); + } + + if (dataAccessEndpoint.getUri() != null) { + job.setDataAccessEndPointUri(dataAccessEndpoint.getUri()); + } else { + throw new IllegalArgumentException("DataAccessEndpointUri cannot be null"); + } + } + + if (measurementCollectionJob.getScheduleDefinition().size() == 1) { + job.setStartDateTime(measurementCollectionJob.getScheduleDefinition().get(0).getScheduleDefinitionStartTime()); + job.setEndDateTime(measurementCollectionJob.getScheduleDefinition().get(0).getScheduleDefinitionEndTime()); + } + + + if (measurementCollectionJob.getGranularity() != null){ + Granularity granularity = measurementCollectionJob.getGranularity(); + job.setExecutionInterval(convertGranularityToSeconds(granularity.getValue())); + } + + + logger.atDebug().setMessage("Received MeasurementCollectionJob:\n" + measurementCollectionJob + "\nConverted it to Job:\n" + job).log(); + return job; + } + + public static int convertGranularityToSeconds(String value) { + Pattern PATTERN = Pattern.compile("G_(\\d+)(SEC|MN|H|D|M|Y)", Pattern.CASE_INSENSITIVE); + if (Granularity.contains(value)) { + Matcher matcher = PATTERN.matcher(value); + if (matcher.matches()) { + int amount = Integer.parseInt(matcher.group(1)); + String unit = matcher.group(2); + if(value.equalsIgnoreCase(Granularity.NA.getValue())){ + return Integer.parseInt(null); + } + return switch (unit.toUpperCase()) { + case "SEC" -> amount; + case "MN" -> amount * 60; + case "H" -> amount * 3600; + case "D" -> amount * 86400; + case "M" -> amount * 2592000; // Approximate value for a month + case "Y" -> amount * 31536000; // Approximate value for a year + default -> throw new IllegalArgumentException("Unknown Granularity unit: " + unit); + }; + } + } + throw new IllegalArgumentException("Invalid Granularity format: " + value); + } +} diff --git a/src/main/java/org/etsi/osl/metrico/mapper/LogicalResourceMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/LogicalResourceMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..181ecc2e6b9fbfb38a16231ec7f5ef61e9a2f8f0 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/LogicalResourceMapper.java @@ -0,0 +1,18 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.LogicalResource; +import org.etsi.osl.tmf.pm628.model.LogicalResourceMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = ResourceMapper.class) +public interface LogicalResourceMapper { + LogicalResourceMapper INSTANCE = Mappers.getMapper(LogicalResourceMapper.class); + + @Mapping(source = "value", target = "value") + LogicalResource toLogicalResource(LogicalResourceMVO logicalResourceMVO); + + @Mapping(source = "value", target = "value") + LogicalResourceMVO toLogicalResourceMVO(LogicalResource logicalResource); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/ManagementJobMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/ManagementJobMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..c0ba58e3c843cf86c8504181061ff6531a012b5f --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/ManagementJobMapper.java @@ -0,0 +1,36 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.ManagementJob; +import org.etsi.osl.tmf.pm628.model.ManagementJobMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + FileTransferDataMapper.class, + DataAccessEndpointMapper.class, + ScheduleDefinitionMapper.class +}) +public interface ManagementJobMapper { + ManagementJobMapper INSTANCE = Mappers.getMapper(ManagementJobMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "fileTransferData", target = "fileTransferData") + @Mapping(source = "dataAccessEndpoint", target = "dataAccessEndpoint") + @Mapping(source = "scheduleDefinition", target = "scheduleDefinition") + ManagementJob toManagementJob(ManagementJobMVO managementJobMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "fileTransferData", target = "fileTransferData") + @Mapping(source = "dataAccessEndpoint", target = "dataAccessEndpoint") + @Mapping(source = "scheduleDefinition", target = "scheduleDefinition") + ManagementJobMVO toManagementJobMVO(ManagementJob managementJob); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/MeasurementCollectionJobMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/MeasurementCollectionJobMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..5238a66dfab581253df29ade7c5c8e73521dc185 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/MeasurementCollectionJobMapper.java @@ -0,0 +1,44 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJob; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJobMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + DataFilterMapMapper.class, + PerformanceIndicatorGroupSpecificationMapper.class, + PerformanceIndicatorSpecificationRefOrValueMapper.class, + TrackingRecordMapper.class, + FileTransferDataMapper.class, + DataAccessEndpointMapper.class, + ScheduleDefinitionMapper.class +}) +public interface MeasurementCollectionJobMapper { + MeasurementCollectionJobMapper INSTANCE = Mappers.getMapper(MeasurementCollectionJobMapper.class); + + @Mapping(source = "reportingPeriod", target = "reportingPeriod") + @Mapping(source = "jobCollectionFilter", target = "jobCollectionFilter") + @Mapping(source = "searchTaskFilter", target = "searchTaskFilter") + @Mapping(source = "jobOnDemand", target = "jobOnDemand") + @Mapping(source = "performanceIndicatorGroupSpecification", target = "performanceIndicatorGroupSpecification") + @Mapping(source = "performanceIndicatorSpecification", target = "performanceIndicatorSpecification") + @Mapping(source = "trackingRecord", target = "trackingRecord") + @Mapping(source = "fileTransferData", target = "fileTransferData") + @Mapping(source = "dataAccessEndpoint", target = "dataAccessEndpoint") + @Mapping(source = "scheduleDefinition", target = "scheduleDefinition") + MeasurementCollectionJob toMeasurementCollectionJob(MeasurementCollectionJobMVO measurementCollectionJobMVO); + + @Mapping(source = "reportingPeriod", target = "reportingPeriod") + @Mapping(source = "jobCollectionFilter", target = "jobCollectionFilter") + @Mapping(source = "searchTaskFilter", target = "searchTaskFilter") + @Mapping(source = "jobOnDemand", target = "jobOnDemand") + @Mapping(source = "performanceIndicatorGroupSpecification", target = "performanceIndicatorGroupSpecification") + @Mapping(source = "performanceIndicatorSpecification", target = "performanceIndicatorSpecification") + @Mapping(source = "trackingRecord", target = "trackingRecord") + @Mapping(source = "fileTransferData", target = "fileTransferData") + @Mapping(source = "dataAccessEndpoint", target = "dataAccessEndpoint") + @Mapping(source = "scheduleDefinition", target = "scheduleDefinition") + MeasurementCollectionJobMVO toMeasurementCollectionJobMVO(MeasurementCollectionJob measurementCollectionJob); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/MeasurementJobMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/MeasurementJobMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..8d6ed6d876e147b29c127ccc2d8e44ec9282e688 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/MeasurementJobMapper.java @@ -0,0 +1,35 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.MeasurementJob; +import org.etsi.osl.tmf.pm628.model.MeasurementJobMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + FileTransferDataMapper.class, + DataAccessEndpointMapper.class, + ScheduleDefinitionMapper.class, + PerformanceIndicatorGroupSpecificationMapper.class, + PerformanceIndicatorSpecificationRefOrValueMapper.class, + TrackingRecordMapper.class +}) +public interface MeasurementJobMapper { + MeasurementJobMapper INSTANCE = Mappers.getMapper(MeasurementJobMapper.class); + + @Mapping(source = "consumingApplicationId", target = "consumingApplicationId") + @Mapping(source = "producingApplicationId", target = "producingApplicationId") + @Mapping(source = "granularity", target = "granularity") + @Mapping(source = "performanceIndicatorGroupSpecification", target = "performanceIndicatorGroupSpecification") + @Mapping(source = "performanceIndicatorSpecification", target = "performanceIndicatorSpecification") + @Mapping(source = "trackingRecord", target = "trackingRecord") + MeasurementJob toMeasurementJob(MeasurementJobMVO measurementJobMVO); + + @Mapping(source = "consumingApplicationId", target = "consumingApplicationId") + @Mapping(source = "producingApplicationId", target = "producingApplicationId") + @Mapping(source = "granularity", target = "granularity") + @Mapping(source = "performanceIndicatorGroupSpecification", target = "performanceIndicatorGroupSpecification") + @Mapping(source = "performanceIndicatorSpecification", target = "performanceIndicatorSpecification") + @Mapping(source = "trackingRecord", target = "trackingRecord") + MeasurementJobMVO toMeasurementJobMVO(MeasurementJob measurementJob); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/MonthlyScheduleDayOfWeekDefinitionMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/MonthlyScheduleDayOfWeekDefinitionMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..e1dbf960da723c4bd8f4e09fb4db6cd29f5eb07c --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/MonthlyScheduleDayOfWeekDefinitionMapper.java @@ -0,0 +1,28 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.MonthlyScheduleDayOfWeekDefinition; +import org.etsi.osl.tmf.pm628.model.MonthlyScheduleDayOfWeekDefinitionMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + DayOfMonthRecurrenceMapper.class +}) +public interface MonthlyScheduleDayOfWeekDefinitionMapper { + MonthlyScheduleDayOfWeekDefinitionMapper INSTANCE = Mappers.getMapper(MonthlyScheduleDayOfWeekDefinitionMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "dayOfMonthRecurrence", target = "dayOfMonthRecurrence") + @Mapping(source = "recurringDaySequence", target = "recurringDaySequence") + MonthlyScheduleDayOfWeekDefinition toMonthlyScheduleDayOfWeekDefinition(MonthlyScheduleDayOfWeekDefinitionMVO monthlyScheduleDayOfWeekDefinitionMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "dayOfMonthRecurrence", target = "dayOfMonthRecurrence") + @Mapping(source = "recurringDaySequence", target = "recurringDaySequence") + MonthlyScheduleDayOfWeekDefinitionMVO toMonthlyScheduleDayOfWeekDefinitionMVO(MonthlyScheduleDayOfWeekDefinition monthlyScheduleDayOfWeekDefinition); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/NoteMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/NoteMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..6f25a3788b754ecb22c1dd29396f2f6329549c79 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/NoteMapper.java @@ -0,0 +1,24 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.common.model.service.Note; +import org.etsi.osl.tmf.pm628.model.NoteMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface NoteMapper { + NoteMapper INSTANCE = Mappers.getMapper(NoteMapper.class); + + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "author", target = "author") + @Mapping(source = "date", target = "date") + @Mapping(source = "text", target = "text") + Note toNote(NoteMVO noteMVO); + + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "author", target = "author") + @Mapping(source = "date", target = "date") + @Mapping(source = "text", target = "text") + NoteMVO toNoteMVO(Note note); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorGroupSpecificationMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorGroupSpecificationMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..1af6d2eddebd60685f70f13d30afe4480180bdcd --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorGroupSpecificationMapper.java @@ -0,0 +1,32 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorGroupSpecification; +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorGroupSpecificationMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + PerformanceIndicatorSpecificationRefOrValueMapper.class +}) +public interface PerformanceIndicatorGroupSpecificationMapper { + PerformanceIndicatorGroupSpecificationMapper INSTANCE = Mappers.getMapper(PerformanceIndicatorGroupSpecificationMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "groupCategory", target = "groupCategory") + @Mapping(source = "performanceIndicatorSpecification", target = "performanceIndicatorSpecification") + PerformanceIndicatorGroupSpecification toPerformanceIndicatorGroupSpecification(PerformanceIndicatorGroupSpecificationMVO performanceIndicatorGroupSpecificationMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "groupCategory", target = "groupCategory") + @Mapping(source = "performanceIndicatorSpecification", target = "performanceIndicatorSpecification") + PerformanceIndicatorGroupSpecificationMVO toPerformanceIndicatorGroupSpecificationMVO(PerformanceIndicatorGroupSpecification performanceIndicatorGroupSpecification); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecRelationshipMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecRelationshipMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..cefb15ae575f42cde28e6eaed2da63147fcbe493 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecRelationshipMapper.java @@ -0,0 +1,32 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorSpecRelationship; +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorSpecRelationshipMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface PerformanceIndicatorSpecRelationshipMapper { + PerformanceIndicatorSpecRelationshipMapper INSTANCE = Mappers.getMapper(PerformanceIndicatorSpecRelationshipMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "relationshipType", target = "relationshipType") + @Mapping(source = "role", target = "role") + @Mapping(source = "validFor", target = "validFor") + PerformanceIndicatorSpecRelationship toPerformanceIndicatorSpecRelationship(PerformanceIndicatorSpecRelationshipMVO performanceIndicatorSpecRelationshipMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "relationshipType", target = "relationshipType") + @Mapping(source = "role", target = "role") + @Mapping(source = "validFor", target = "validFor") + PerformanceIndicatorSpecRelationshipMVO toPerformanceIndicatorSpecRelationshipMVO(PerformanceIndicatorSpecRelationship performanceIndicatorSpecRelationship); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecificationMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecificationMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..f58269c99e213df365f263d64e6ba6bca19d1897 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecificationMapper.java @@ -0,0 +1,50 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorSpecification; +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorSpecificationMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + PerformanceIndicatorSpecRelationshipMapper.class, +}) +public interface PerformanceIndicatorSpecificationMapper { + PerformanceIndicatorSpecificationMapper INSTANCE = Mappers.getMapper(PerformanceIndicatorSpecificationMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "description", target = "description") + @Mapping(source = "perspective", target = "perspective") + @Mapping(source = "indicatorCategory", target = "indicatorCategory") + @Mapping(source = "indicatorType", target = "indicatorType") + @Mapping(source = "derivationAlgorithm", target = "derivationAlgorithm") + @Mapping(source = "derivationMethod", target = "derivationMethod") + @Mapping(source = "validFor", target = "validFor") + @Mapping(source = "collectionType", target = "collectionType") + @Mapping(source = "indicatorUnit", target = "indicatorUnit") + @Mapping(source = "performanceIndicatorSpecRelationship", target = "performanceIndicatorSpecRelationship") + PerformanceIndicatorSpecification toPerformanceIndicatorSpecification(PerformanceIndicatorSpecificationMVO performanceIndicatorSpecificationMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "description", target = "description") + @Mapping(source = "perspective", target = "perspective") + @Mapping(source = "indicatorCategory", target = "indicatorCategory") + @Mapping(source = "indicatorType", target = "indicatorType") + @Mapping(source = "derivationAlgorithm", target = "derivationAlgorithm") + @Mapping(source = "derivationMethod", target = "derivationMethod") + @Mapping(source = "validFor", target = "validFor") + @Mapping(source = "collectionType", target = "collectionType") + @Mapping(source = "indicatorUnit", target = "indicatorUnit") + @Mapping(source = "performanceIndicatorSpecRelationship", target = "performanceIndicatorSpecRelationship") + PerformanceIndicatorSpecificationMVO toPerformanceIndicatorSpecificationMVO(PerformanceIndicatorSpecification performanceIndicatorSpecification); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecificationRefMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecificationRefMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..0e56edb6c9cc36c3c937ef525b64ffd9cd28c7d1 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecificationRefMapper.java @@ -0,0 +1,32 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorSpecificationRef; +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorSpecificationRefMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface PerformanceIndicatorSpecificationRefMapper { + PerformanceIndicatorSpecificationRefMapper INSTANCE = Mappers.getMapper(PerformanceIndicatorSpecificationRefMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "version", target = "version") + PerformanceIndicatorSpecificationRef toPerformanceIndicatorSpecificationRef(PerformanceIndicatorSpecificationRefMVO performanceIndicatorSpecificationRefMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "version", target = "version") + PerformanceIndicatorSpecificationRefMVO toPerformanceIndicatorSpecificationRefMVO(PerformanceIndicatorSpecificationRef performanceIndicatorSpecificationRef); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecificationRefOrValueMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecificationRefOrValueMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..b78ed7c1f637dbcef828c2c2052a0a5778207a6b --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/PerformanceIndicatorSpecificationRefOrValueMapper.java @@ -0,0 +1,22 @@ +package org.etsi.osl.metrico.mapper; + + +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorSpecificationRefOrValue; +import org.etsi.osl.tmf.pm628.model.PerformanceIndicatorSpecificationRefOrValueMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + PerformanceIndicatorSpecificationMapper.class, + PerformanceIndicatorSpecificationRefMapper.class +}) +public interface PerformanceIndicatorSpecificationRefOrValueMapper { + PerformanceIndicatorSpecificationRefOrValueMapper INSTANCE = Mappers.getMapper(PerformanceIndicatorSpecificationRefOrValueMapper.class); + + @Mapping(source = "type", target = "type") + PerformanceIndicatorSpecificationRefOrValue toPerformanceIndicatorSpecificationRefOrValue(PerformanceIndicatorSpecificationRefOrValueMVO performanceIndicatorSpecificationRefOrValueMVO); + + @Mapping(source = "type", target = "type") + PerformanceIndicatorSpecificationRefOrValueMVO toPerformanceIndicatorSpecificationRefOrValueMVO(PerformanceIndicatorSpecificationRefOrValue performanceIndicatorSpecificationRefOrValue); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/PolicyRefMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/PolicyRefMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..851e0b43c93ba98e46dd57137bda9b7392b01ad9 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/PolicyRefMapper.java @@ -0,0 +1,32 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.PolicyRef; +import org.etsi.osl.tmf.pm628.model.PolicyRefMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface PolicyRefMapper { + PolicyRefMapper INSTANCE = Mappers.getMapper(PolicyRefMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "version", target = "version") + PolicyRef toPolicyRef(PolicyRefMVO policyRefMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "name", target = "name") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "version", target = "version") + PolicyRefMVO toPolicyRefMVO(PolicyRef policyRef); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/RelatedPartyRefOrPartyRoleRefMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/RelatedPartyRefOrPartyRoleRefMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..bc6f59a94ff472a49b7f5ea4193d6aae1e2b25ce --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/RelatedPartyRefOrPartyRoleRefMapper.java @@ -0,0 +1,26 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.RelatedPartyRefOrPartyRoleRef; +import org.etsi.osl.tmf.pm628.model.RelatedPartyRefOrPartyRoleRefMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface RelatedPartyRefOrPartyRoleRefMapper { + RelatedPartyRefOrPartyRoleRefMapper INSTANCE = Mappers.getMapper(RelatedPartyRefOrPartyRoleRefMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "role", target = "role") + @Mapping(source = "partyOrPartyRole", target = "partyOrPartyRole") + RelatedPartyRefOrPartyRoleRef toRelatedPartyRefOrPartyRoleRef(RelatedPartyRefOrPartyRoleRefMVO relatedPartyRefOrPartyRoleRefMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "role", target = "role") + @Mapping(source = "partyOrPartyRole", target = "partyOrPartyRole") + RelatedPartyRefOrPartyRoleRefMVO toRelatedPartyRefOrPartyRoleRefMVO(RelatedPartyRefOrPartyRoleRef relatedPartyRefOrPartyRoleRef); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/RelatedPlaceRefMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/RelatedPlaceRefMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..9d60c1ae9175bc5e20edbdb6d0ebdf4a99fadae5 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/RelatedPlaceRefMapper.java @@ -0,0 +1,26 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.RelatedPlaceRef; +import org.etsi.osl.tmf.pm628.model.RelatedPlaceRefMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface RelatedPlaceRefMapper { + RelatedPlaceRefMapper INSTANCE = Mappers.getMapper(RelatedPlaceRefMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "role", target = "role") + @Mapping(source = "place", target = "place") + RelatedPlaceRef toRelatedPlaceRef(RelatedPlaceRefMVO relatedPlaceRefMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "role", target = "role") + @Mapping(source = "place", target = "place") + RelatedPlaceRefMVO toRelatedPlaceRefMVO(RelatedPlaceRef relatedPlaceRef); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/RelatedResourceOrderItemMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/RelatedResourceOrderItemMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..60c1ad80087c919f687d9951e756a372f812d9e0 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/RelatedResourceOrderItemMapper.java @@ -0,0 +1,34 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.RelatedResourceOrderItem; +import org.etsi.osl.tmf.pm628.model.RelatedResourceOrderItemMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface RelatedResourceOrderItemMapper { + RelatedResourceOrderItemMapper INSTANCE = Mappers.getMapper(RelatedResourceOrderItemMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "resourceOrderHref", target = "resourceOrderHref") + @Mapping(source = "resourceOrderId", target = "resourceOrderId") + @Mapping(source = "itemAction", target = "itemAction") + @Mapping(source = "itemId", target = "itemId") + @Mapping(source = "role", target = "role") + RelatedResourceOrderItem toRelatedResourceOrderItem(RelatedResourceOrderItemMVO relatedResourceOrderItemMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "resourceOrderHref", target = "resourceOrderHref") + @Mapping(source = "resourceOrderId", target = "resourceOrderId") + @Mapping(source = "itemAction", target = "itemAction") + @Mapping(source = "itemId", target = "itemId") + @Mapping(source = "role", target = "role") + RelatedResourceOrderItemMVO toRelatedResourceOrderItemMVO(RelatedResourceOrderItem relatedResourceOrderItem); +} diff --git a/src/main/java/org/etsi/osl/metrico/mapper/ResourceMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/ResourceMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..18a5b4290ae2690a0bdbe6f6cada3d91c7e98900 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/ResourceMapper.java @@ -0,0 +1,82 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.Resource; +import org.etsi.osl.tmf.pm628.model.ResourceMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + NoteMapper.class, + RelatedResourceOrderItemMapper.class, + RelatedPlaceRefMapper.class, + RelatedPartyRefOrPartyRoleRefMapper.class, + ResourceRelationshipMapper.class, + CharacteristicMapper.class, + AttachmentRefMapper.class, + ResourceSpecificationRefMapper.class, + FeatureMapper.class, + IntentRefMapper.class, + ExternalIdentifierMapper.class +}) +public interface ResourceMapper { + ResourceMapper INSTANCE = Mappers.getMapper(ResourceMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "category", target = "category") + @Mapping(source = "description", target = "description") + @Mapping(source = "name", target = "name") + @Mapping(source = "endOperatingDate", target = "endOperatingDate") + @Mapping(source = "administrativeState", target = "administrativeState") + @Mapping(source = "operationalState", target = "operationalState") + @Mapping(source = "resourceStatus", target = "resourceStatus") + @Mapping(source = "usageState", target = "usageState") + @Mapping(source = "validFor", target = "validFor") + @Mapping(source = "note", target = "note") + @Mapping(source = "resourceOrderItem", target = "resourceOrderItem") + @Mapping(source = "place", target = "place") + @Mapping(source = "relatedParty", target = "relatedParty") + @Mapping(source = "resourceRelationship", target = "resourceRelationship") + @Mapping(source = "resourceCharacteristic", target = "resourceCharacteristic") + @Mapping(source = "attachment", target = "attachment") + @Mapping(source = "resourceSpecification", target = "resourceSpecification") + @Mapping(source = "startOperatingDate", target = "startOperatingDate") + @Mapping(source = "resourceVersion", target = "resourceVersion") + @Mapping(source = "activationFeature", target = "activationFeature") + @Mapping(source = "intent", target = "intent") + @Mapping(source = "externalIdentifier", target = "externalIdentifier") + Resource toResource(ResourceMVO resourceMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "category", target = "category") + @Mapping(source = "description", target = "description") + @Mapping(source = "name", target = "name") + @Mapping(source = "endOperatingDate", target = "endOperatingDate") + @Mapping(source = "administrativeState", target = "administrativeState") + @Mapping(source = "operationalState", target = "operationalState") + @Mapping(source = "resourceStatus", target = "resourceStatus") + @Mapping(source = "usageState", target = "usageState") + @Mapping(source = "validFor", target = "validFor") + @Mapping(source = "note", target = "note") + @Mapping(source = "resourceOrderItem", target = "resourceOrderItem") + @Mapping(source = "place", target = "place") + @Mapping(source = "relatedParty", target = "relatedParty") + @Mapping(source = "resourceRelationship", target = "resourceRelationship") + @Mapping(source = "resourceCharacteristic", target = "resourceCharacteristic") + @Mapping(source = "attachment", target = "attachment") + @Mapping(source = "resourceSpecification", target = "resourceSpecification") + @Mapping(source = "startOperatingDate", target = "startOperatingDate") + @Mapping(source = "resourceVersion", target = "resourceVersion") + @Mapping(source = "activationFeature", target = "activationFeature") + @Mapping(source = "intent", target = "intent") + @Mapping(source = "externalIdentifier", target = "externalIdentifier") + ResourceMVO toResourceMVO(Resource resource); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/ResourceRefOrValueMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/ResourceRefOrValueMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..2fae4c84907986a03cb3f9c53027fc6dc7b9345f --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/ResourceRefOrValueMapper.java @@ -0,0 +1,18 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.ResourceRefOrValue; +import org.etsi.osl.tmf.pm628.model.ResourceRefOrValueMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface ResourceRefOrValueMapper { + ResourceRefOrValueMapper INSTANCE = Mappers.getMapper(ResourceRefOrValueMapper.class); + + @Mapping(source = "type", target = "type") + ResourceRefOrValueMVO toResourceRefOrValueMVO(ResourceRefOrValue resourceRefOrValue); + + @Mapping(source = "type", target = "type") + ResourceRefOrValue toResourceRefOrValue(ResourceRefOrValueMVO resourceRefOrValueMVO); +} diff --git a/src/main/java/org/etsi/osl/metrico/mapper/ResourceRelationshipMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/ResourceRelationshipMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..f91ba647bc066da1db065c0bd6ce6e6b18f9d271 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/ResourceRelationshipMapper.java @@ -0,0 +1,30 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.ResourceRelationship; +import org.etsi.osl.tmf.pm628.model.ResourceRelationshipMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface ResourceRelationshipMapper { + ResourceRelationshipMapper INSTANCE = Mappers.getMapper(ResourceRelationshipMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "resourceRelationshipCharacteristic", target = "resourceRelationshipCharacteristic") + @Mapping(source = "resource", target = "resource") + @Mapping(source = "relationshipType", target = "relationshipType") + ResourceRelationship toResourceRelationship(ResourceRelationshipMVO resourceRelationshipMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "uuid", target = "uuid") + @Mapping(source = "resourceRelationshipCharacteristic", target = "resourceRelationshipCharacteristic") + @Mapping(source = "resource", target = "resource") + @Mapping(source = "relationshipType", target = "relationshipType") + ResourceRelationshipMVO toResourceRelationshipMVO(ResourceRelationship resourceRelationship); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/ResourceSpecificationRefMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/ResourceSpecificationRefMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..9041cab49b41f33f603ee31a3758769c5e07caf1 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/ResourceSpecificationRefMapper.java @@ -0,0 +1,32 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationRef; +import org.etsi.osl.tmf.pm628.model.ResourceSpecificationRefMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface ResourceSpecificationRefMapper { + ResourceSpecificationRefMapper INSTANCE = Mappers.getMapper(ResourceSpecificationRefMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "id", target = "id") + @Mapping(source = "name", target = "name") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "version", target = "version") + ResourceSpecificationRef toResourceSpecificationRef(ResourceSpecificationRefMVO resourceSpecificationRefMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "href", target = "href") + @Mapping(source = "id", target = "id") + @Mapping(source = "name", target = "name") + @Mapping(source = "referredType", target = "referredType") + @Mapping(source = "version", target = "version") + ResourceSpecificationRefMVO toResourceSpecificationRefMVO(ResourceSpecificationRef resourceSpecificationRef); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/ScheduleDefinitionMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/ScheduleDefinitionMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..8d62b206256e32bf66a472825ce03be0980431f9 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/ScheduleDefinitionMapper.java @@ -0,0 +1,37 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.ScheduleDefinition; +import org.etsi.osl.tmf.pm628.model.ScheduleDefinitionMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + DayOfWeekRecurrenceMapper.class, + MonthlyScheduleDayOfWeekDefinitionMapper.class +}) +public interface ScheduleDefinitionMapper { + ScheduleDefinitionMapper INSTANCE = Mappers.getMapper(ScheduleDefinitionMapper.class); + + @Mapping(source = "scheduleDefinitionStartTime", target = "scheduleDefinitionStartTime") + @Mapping(source = "scheduleDefinitionEndTime", target = "scheduleDefinitionEndTime") + @Mapping(source = "recurringFrequency", target = "recurringFrequency") + @Mapping(source = "excludedDate", target = "excludedDate") + @Mapping(source = "scheduleDefinitionHourRange", target = "scheduleDefinitionHourRange") + @Mapping(source = "weeklyScheduledDefinition", target = "weeklyScheduledDefinition") + @Mapping(source = "monthlyScheduleDayOfMonthDefinition", target = "monthlyScheduleDayOfMonthDefinition") + @Mapping(source = "monthlyScheduleDayOfWeekDefinition", target = "monthlyScheduleDayOfWeekDefinition") + @Mapping(source = "dateScheduleDefintion", target = "dateScheduleDefintion") + ScheduleDefinition toScheduleDefinition(ScheduleDefinitionMVO scheduleDefinitionMVO); + + @Mapping(source = "scheduleDefinitionStartTime", target = "scheduleDefinitionStartTime") + @Mapping(source = "scheduleDefinitionEndTime", target = "scheduleDefinitionEndTime") + @Mapping(source = "recurringFrequency", target = "recurringFrequency") + @Mapping(source = "excludedDate", target = "excludedDate") + @Mapping(source = "scheduleDefinitionHourRange", target = "scheduleDefinitionHourRange") + @Mapping(source = "weeklyScheduledDefinition", target = "weeklyScheduledDefinition") + @Mapping(source = "monthlyScheduleDayOfMonthDefinition", target = "monthlyScheduleDayOfMonthDefinition") + @Mapping(source = "monthlyScheduleDayOfWeekDefinition", target = "monthlyScheduleDayOfWeekDefinition") + @Mapping(source = "dateScheduleDefintion", target = "dateScheduleDefintion") + ScheduleDefinitionMVO toScheduleDefinitionMVO(ScheduleDefinition scheduleDefinition); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/mapper/TrackingRecordMapper.java b/src/main/java/org/etsi/osl/metrico/mapper/TrackingRecordMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..fceb1057193f93ebf5c436cc71e98db3aa13fe62 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/mapper/TrackingRecordMapper.java @@ -0,0 +1,36 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.TrackingRecord; +import org.etsi.osl.tmf.pm628.model.TrackingRecordMVO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = { + CharacteristicMapper.class +}) +public interface TrackingRecordMapper { + TrackingRecordMapper INSTANCE = Mappers.getMapper(TrackingRecordMapper.class); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "description", target = "description") + @Mapping(source = "characteristic", target = "characteristic") + @Mapping(source = "systemId", target = "systemId") + @Mapping(source = "time", target = "time") + @Mapping(source = "user", target = "user") + @Mapping(source = "uuid", target = "uuid") + TrackingRecord toTrackingRecord(TrackingRecordMVO trackingRecordMVO); + + @Mapping(source = "type", target = "type") + @Mapping(source = "baseType", target = "baseType") + @Mapping(source = "schemaLocation", target = "schemaLocation") + @Mapping(source = "description", target = "description") + @Mapping(source = "characteristic", target = "characteristic") + @Mapping(source = "systemId", target = "systemId") + @Mapping(source = "time", target = "time") + @Mapping(source = "user", target = "user") + @Mapping(source = "uuid", target = "uuid") + TrackingRecordMVO toTrackingRecordMVO(TrackingRecord trackingRecord); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/model/Job.java b/src/main/java/org/etsi/osl/metrico/model/Job.java new file mode 100644 index 0000000000000000000000000000000000000000..653a10ccea7826fdb3b02ddb4ee6164d49746056 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/model/Job.java @@ -0,0 +1,151 @@ +package org.etsi.osl.metrico.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; +import org.etsi.osl.tmf.pm628.model.DataFilterMap; +import org.etsi.osl.tmf.pm628.model.ExecutionStateType; +import org.hibernate.annotations.GenericGenerator; +import org.springframework.format.annotation.DateTimeFormat; + +import java.net.URI; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.util.concurrent.ScheduledFuture; + + +@Getter +@Setter +@Entity +@Table(name = "MetJob") +public class Job{ + + @Id + @GeneratedValue(generator = "UUID") + @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") + private UUID uuid; + + private ExecutionStateType state; + + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + private OffsetDateTime startDateTime; + + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + private OffsetDateTime endDateTime; + + private Integer executionInterval; + + private UUID dataAccessEndPointRef; // Get the prometheus IP (uri) and its state + + private UUID scheduleDefinitionRef; //Get the startDateTime, endDateTime and executionInterval (recurringFrequency) + + // Get the reporting period and collection granularity(the periods are too big), + // Consuming / producing application id, + // scheduleDefinitionRef -> Get the startDateTime, endDateTime and executionInterval (recurringFrequency) + // Should I check the granularity or the scheduleDefinitionRef for the recurringFrequency? + private UUID measurementCollectionJobRef; + + private URI dataAccessEndPointUri; + + private String apiType; + + @JsonIgnore + private boolean deleted = false; + + @Transient + private final Runnable task = new Runnable() { + @Override + public void run() { + + } + }; + + @Transient + private ScheduledFuture<?> future; + + + public Job() { + this.state = ExecutionStateType.PENDING; + this.executionInterval = 10; + this.startDateTime = OffsetDateTime.now(); + } + + public Job(OffsetDateTime stopDateTime){ + this(); + this.endDateTime = stopDateTime; + } + + public Job(OffsetDateTime startDateTime, OffsetDateTime endDateTime){ + this(endDateTime); + this.startDateTime = startDateTime; + } + + public Job(OffsetDateTime startDateTime, OffsetDateTime endDateTime, Integer executionInterval){ + this(startDateTime, endDateTime); + this.executionInterval = executionInterval; + } + + @Override + public String toString() { + return "Job{" + + "uuid=" + uuid + + ", state=" + state + + ", startDateTime=" + startDateTime + + ", endDateTime=" + endDateTime + + ", executionInterval=" + executionInterval + + ", dataAccessEndPointRef=" + dataAccessEndPointRef + + ", scheduleDefinitionRef=" + scheduleDefinitionRef + + ", measurementCollectionJobRef=" + measurementCollectionJobRef + + ", deleted=" + deleted + + '}'; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public void setState(ExecutionStateType state) { + this.state = state; + } + + public void setStartDateTime(OffsetDateTime startDateTime) { + this.startDateTime = startDateTime; + } + + public void setEndDateTime(OffsetDateTime endDateTime) { + this.endDateTime = endDateTime; + } + + public void setExecutionInterval(Integer executionInterval) { + this.executionInterval = executionInterval; + } + + public void setDataAccessEndPointRef(UUID dataAccessEndPointRef) { + this.dataAccessEndPointRef = dataAccessEndPointRef; + } + + public void setScheduleDefinitionRef(UUID scheduleDefinitionRef) { + this.scheduleDefinitionRef = scheduleDefinitionRef; + } + + public void setMeasurementCollectionJobRef(UUID measurementCollectionJobRef) { + this.measurementCollectionJobRef = measurementCollectionJobRef; + } + + public void setDataAccessEndPointUri(URI dataAccessEndPointUri) { + this.dataAccessEndPointUri = dataAccessEndPointUri; + } + + public void setApiType(String apiType) { + this.apiType = apiType; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public void setFuture(ScheduledFuture<?> future) { + this.future = future; + } +} diff --git a/src/main/java/org/etsi/osl/metrico/model/SupportedDataAccessEndpoints.java b/src/main/java/org/etsi/osl/metrico/model/SupportedDataAccessEndpoints.java new file mode 100644 index 0000000000000000000000000000000000000000..75b1b3486360df49d00fb73a26a1e02e2e2128f1 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/model/SupportedDataAccessEndpoints.java @@ -0,0 +1,16 @@ +package org.etsi.osl.metrico.model; + +public enum SupportedDataAccessEndpoints { + PROMETHEUS; + + public static boolean contains(String apiType) { + try { + SupportedDataAccessEndpoints.valueOf(apiType.toUpperCase()); + return true; + } catch (IllegalArgumentException e) { + return false; + } + } +} + + diff --git a/src/main/java/org/etsi/osl/metrico/prometheus/PrometheusQueries.java b/src/main/java/org/etsi/osl/metrico/prometheus/PrometheusQueries.java new file mode 100644 index 0000000000000000000000000000000000000000..f84a10640227008f87c1899a87522ca36f9149d5 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/prometheus/PrometheusQueries.java @@ -0,0 +1,334 @@ +package org.etsi.osl.metrico.prometheus; + +import java.io.IOException; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.camel.ProducerTemplate; +import org.etsi.osl.metrico.model.Job; +import org.etsi.osl.metrico.services.JobService; +import org.etsi.osl.tmf.common.model.Any; +import org.etsi.osl.tmf.common.model.service.Characteristic; +import org.etsi.osl.tmf.pm628.model.ExecutionStateType; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJob; +import org.etsi.osl.tmf.rcm634.model.LogicalResourceSpecification; +import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationCreate; +import org.etsi.osl.tmf.ri639.model.LogicalResource; +import org.etsi.osl.tmf.ri639.model.Resource; +import org.etsi.osl.tmf.ri639.model.ResourceUpdate; +import org.etsi.osl.tmf.sim638.model.ServiceUpdate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatusCode; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.util.UriComponentsBuilder; +import jakarta.validation.constraints.NotNull; +import reactor.core.publisher.Mono; + +@Component +public class PrometheusQueries { + + private static final Logger logger = LoggerFactory.getLogger(PrometheusQueries.class); + private final JobService jobService; + + + @Value("${CATALOG_GET_SERVICE_BY_ID}") + private String CATALOG_GET_SERVICE_BY_ID = ""; + + + @Value("${CATALOG_GET_RESOURCE_BY_ID}") + private String CATALOG_GET_RESOURCE_BY_ID = ""; + + + @Value("${CATALOG_UPD_RESOURCE}") + private String CATALOG_UPD_RESOURCE = ""; + + + @Value("${CATALOG_UPD_SERVICE}") + private String CATALOG_UPD_SERVICE = ""; + + @Value("${CATALOG_UPDADD_RESOURCESPEC}") + private String CATALOG_UPDADD_RESOURCESPEC = ""; + + + + @Autowired + private ProducerTemplate template; + + + public PrometheusQueries(JobService jobService) { + this.jobService = jobService; + } + + public String sendQueryToPrometheus(String prometheusUrl, String query, MeasurementCollectionJob mcj, Job job) { + //RestTemplate restTemplate = new RestTemplate(); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(prometheusUrl) + .path("/api/v1/query") + .query(query); + logger.atInfo().log("Sent query at prometheus with URL: " + prometheusUrl + " with query: " + query); + logger.atInfo().log("Sent query builder.toUriString(): " + builder.toUriString() ); + + //ResponseEntity<String> response = restTemplate.getForEntity(builder.toUriString(), String.class); + + WebClient webclient = WebClient.create(); + + String response=""; + + if ( webclient!=null ) { + + try { + + String url = builder.toUriString(); + + response = webclient.get() + .uri(url) + //.header("Authorization", "Basic " + encodedClientData) + //.attributes( ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId("authOpensliceProvider")) + .retrieve() + .onStatus(HttpStatusCode::is4xxClientError, r -> { + logger.error("4xx eror"); + return Mono.error(new RuntimeException("4xx")); + }) + .onStatus(HttpStatusCode::is5xxServerError, r -> { + logger.error("5xx eror"); + return Mono.error(new RuntimeException("5xx")); + }) + .bodyToMono( new ParameterizedTypeReference<String>() {}) + .block(); + + logger.atDebug().log("Received " + response); + + String [] promResponse =response.split("\n"); + + + + }catch (Exception e) { + logger.error(" error on web client request"); + response = "{\"status\":\""+ e.getLocalizedMessage() +"\""; + e.printStackTrace(); + } + + } else { + logger.error("WebClient is null. Cannot be created."); + response = "{\"status\":\"Cannot connect\""; + } + + + + ServiceUpdate su = new ServiceUpdate(); + + //patch TMF service + String serviceUUID = mcj.getConsumingApplicationId(); + logger.atDebug().log("serviceUUID= " + serviceUUID); + Characteristic serviceCharacteristicItem = new Characteristic(); + serviceCharacteristicItem.setName( mcj.getOutputFormat() ); + serviceCharacteristicItem.setValueType( "TEXT" ); + Any val = new Any(); + val.setValue( response ); + val.setAlias( ""); + serviceCharacteristicItem.setValue( val ); + su.addServiceCharacteristicItem(serviceCharacteristicItem); + updateService(serviceUUID, su , true); + + return response; + } + + + + public Job startPeriodicQuery(String prometheusUrl, String query, final Job ajob, MeasurementCollectionJob mcj) { + + Job job = ajob; + if (job.getStartDateTime() == null){ + job.setStartDateTime(OffsetDateTime.now()); + } + if (job.getEndDateTime() == null){ + job.setEndDateTime(job.getStartDateTime().plusHours(1)); + } + if(job.getExecutionInterval() == null){ + job.setExecutionInterval(180); + } + + final Runnable queryHandler = () -> sendQueryToPrometheus(prometheusUrl, query, mcj, ajob); + + job = jobService.startJob(queryHandler, job); + if (job.getState() == ExecutionStateType.FAILED) { + jobService.stopJob(job); + return job; + } + + if (job.getEndDateTime() != null) { + long stopAfterSeconds = Duration.between(OffsetDateTime.now(), job.getEndDateTime() ).getSeconds(); + + JobService.getScheduler().schedule(() -> { + jobService.stopJob(ajob); + + }, stopAfterSeconds, TimeUnit.SECONDS); + } + + return job; + } + + + + public Resource retrieveResource(@NotNull String resourceID) { + logger.info("will retrieve Resource instance from catalog resourceID=" + resourceID ); + try { + Object response = template. + requestBody( CATALOG_GET_RESOURCE_BY_ID, resourceID); + + if ( !(response instanceof String)) { + logger.error("resource object is wrong."); + return null; + } + LogicalResource rInstance = toJsonObj( (String)response, LogicalResource.class); + + return rInstance; + + }catch (Exception e) { + logger.error("Cannot retrieve LogicalResource details from catalog. " + e.toString()); + } + return null; + + } + + /** + * Ger service instance via bus + * @param serviceID + * @return + */ + public org.etsi.osl.tmf.sim638.model.Service retrieveService(String serviceID) { + logger.info("will retrieve Service instance from catalog serviceID=" + serviceID ); + try { + Object response = template. + requestBody( CATALOG_GET_SERVICE_BY_ID, serviceID); + + if ( !(response instanceof String)) { + logger.error("Service object is wrong."); + return null; + } + org.etsi.osl.tmf.sim638.model.Service serviceInstance = toJsonObj( (String)response, org.etsi.osl.tmf.sim638.model.Service.class); + //logger.debug("retrieveService response is: " + response); + return serviceInstance; + + }catch (Exception e) { + logger.error("Cannot retrieve Service details from catalog. " + e.toString()); + } + return null; + } + + + public Resource updateResourceById(String oslResourceId, ResourceUpdate rs) { + + + logger.debug("will update Resource : " + oslResourceId ); + try { + Map<String, Object> map = new HashMap<>(); + map.put("resourceId", oslResourceId ); + map.put("triggerServiceActionQueue", false ); + + Object response = template.requestBodyAndHeaders( CATALOG_UPD_RESOURCE, toJsonString(rs), map); + + if ( !(response instanceof String)) { + logger.error("Service Instance object is wrong."); + } + + LogicalResource resourceInstance = toJsonObj( (String)response, LogicalResource.class); + //logger.debug("createService response is: " + response); + return resourceInstance; + + + }catch (Exception e) { + e.printStackTrace(); + logger.error("Cannot update Service: " + oslResourceId + ": " + e.toString()); + } + return null; + } + + + /** + * @param serviceId + * @param s + * @param triggerServiceActionQueue is a cryptic thing. However it is used as follows: if FALSE, to just update the service status in catalog without further taking any action. + * if TRUE then the ServiceUpdate will trigger a ServiceActionQueue to further process the update. So this is needed to avoid these kinds of deadlocks + * @return + */ + public org.etsi.osl.tmf.sim638.model.Service updateService(String serviceId, ServiceUpdate s, boolean triggerServiceActionQueue) { + logger.info("will update Service : " + serviceId ); + try { + Map<String, Object> map = new HashMap<>(); + map.put("serviceid", serviceId ); + map.put("triggerServiceActionQueue", triggerServiceActionQueue ); + + Object response = template.requestBodyAndHeaders( CATALOG_UPD_SERVICE, toJsonString(s), map); + + if ( !(response instanceof String)) { + logger.error("Service Instance object is wrong."); + } + + org.etsi.osl.tmf.sim638.model.Service serviceInstance = toJsonObj( (String)response, org.etsi.osl.tmf.sim638.model.Service.class); + //logger.debug("createService response is: " + response); + return serviceInstance; + + + }catch (Exception e) { + logger.error("Cannot update Service: " + serviceId + ": " + e.toString()); + } + return null; + + } + + + + public LogicalResourceSpecification createOrUpdateResourceSpecByNameCategoryVersion( ResourceSpecificationCreate s) { + logger.info("will createOrUpdateResourceSpecByNameCategoryVersion " ); + try { + Map<String, Object> map = new HashMap<>(); + map.put("aname", s.getName()); + map.put("aversion", s.getVersion()); + map.put("acategory", s.getCategory()); + + Object response = template.requestBodyAndHeaders( CATALOG_UPDADD_RESOURCESPEC, toJsonString(s), map); + + if ( !(response instanceof String)) { + logger.error("ResourceSpecification object is wrong."); + } + + LogicalResourceSpecification rs = toJsonObj( (String)response, LogicalResourceSpecification.class); + return rs; + + + }catch (Exception e) { + logger.error("Cannot create ResourceSpecification"); + e.printStackTrace(); + } + return null; + + } + + static <T> T toJsonObj(String content, Class<T> valueType) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.readValue( content, valueType); + } + + static String toJsonString(Object object) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.writeValueAsString(object); + } + + +} + + diff --git a/src/main/java/org/etsi/osl/metrico/repo/JobRepository.java b/src/main/java/org/etsi/osl/metrico/repo/JobRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..17988b874539a8a9d02890da172c8900dca3746c --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/repo/JobRepository.java @@ -0,0 +1,20 @@ +package org.etsi.osl.metrico.repo; + +import org.etsi.osl.metrico.model.Job; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Repository +public interface JobRepository extends JpaRepository<Job, UUID> { + @Query("SELECT j FROM Job j WHERE j.deleted = false") + List<Job> findAllActiveJobs(); + + @Query("SELECT j FROM Job j WHERE j.uuid = :id AND j.deleted = false") + Optional<Job> findActiveById(@Param("id") UUID id); +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/reposervices/JobRepoService.java b/src/main/java/org/etsi/osl/metrico/reposervices/JobRepoService.java new file mode 100644 index 0000000000000000000000000000000000000000..59522ea0550b63ce3fc7f58e83bafbbef10264d0 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/reposervices/JobRepoService.java @@ -0,0 +1,87 @@ +package org.etsi.osl.metrico.reposervices; + +import org.etsi.osl.metrico.model.Job; +import org.etsi.osl.metrico.repo.JobRepository; +import org.etsi.osl.tmf.pm628.model.ExecutionStateType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; + +@Service +public class JobRepoService { + + private static final Logger logger = LoggerFactory.getLogger(JobRepoService.class); + + private void logJobNotFoundError(UUID jobId) { + logger.error("Job with ID {} not found.", jobId); + } + private JobRepository jobRepository; + + @Autowired + public JobRepoService(JobRepository jobRepository) { + this.jobRepository = jobRepository; + if (jobRepository == null) { + logger.error("JobRepository is null. Dependency injection failed."); + } + } + + + + public Job createAndSaveJob( Job job ) { + // Set properties on the job object as needed + return jobRepository.save(job); // This will persist the job to the database + } + + public Job updateJob(UUID jobId, ExecutionStateType newState, OffsetDateTime newStartDateTime, OffsetDateTime newEndDateTime, Integer newExecutionInterval) { + // Retrieve the existing Job + Job job = jobRepository.findById(jobId).orElse(null); + if (job == null) { + logJobNotFoundError(jobId); + return null; + } + // Update the fields as needed + if (newState != null) job.setState(newState); + if (newStartDateTime != null) job.setStartDateTime(newStartDateTime); + if (newEndDateTime != null) job.setEndDateTime(newEndDateTime); + if (newExecutionInterval != null) job.setExecutionInterval(newExecutionInterval); + + // Save the updated Job back to the database + return jobRepository.save(job); + } + + public Job updateJob(UUID jobId, ExecutionStateType newState) { + // Retrieve the existing Job + Job job = jobRepository.findById(jobId).orElse(null); + if (job == null) { + logJobNotFoundError(jobId); + return null; + } + // Update the fields as needed + if (newState != null) job.setState(newState); + // Save the updated Job back to the database + return jobRepository.save(job); + } + + public boolean softDeleteJob(Job ajob) { + Job job = jobRepository.findById(ajob.getUuid()).orElse(null); + if (job == null) { + logJobNotFoundError( ajob.getUuid() ); + return false; + } + logger.error("Job with ID {} will be DELETED.", ajob.getUuid() ); + job.setDeleted(true); + jobRepository.delete(job); + return true; + } + + public List<Job> findAll() { + + return (List<Job>) this.jobRepository.findAll(); + } + +} diff --git a/src/main/java/org/etsi/osl/metrico/services/JobService.java b/src/main/java/org/etsi/osl/metrico/services/JobService.java new file mode 100644 index 0000000000000000000000000000000000000000..35519975ebb58f9014f5b1cf399c6d67cff4416a --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/services/JobService.java @@ -0,0 +1,137 @@ +package org.etsi.osl.metrico.services; + +import lombok.Getter; +import org.etsi.osl.metrico.model.Job; +import org.etsi.osl.metrico.reposervices.JobRepoService; +import org.etsi.osl.tmf.pm628.model.ExecutionStateType; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJobRef; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.event.ApplicationStartedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.*; + +@Service +public class JobService { + + private static final Logger logger = LoggerFactory.getLogger(JobService.class); + + @Value("${METRICO_THREAD_POOL_SIZE}") + private static int threadPoolSize; + @Getter + private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(threadPoolSize); + + private final JobRepoService jobRepoService; + + public JobService(JobRepoService jobRepoService) { + this.jobRepoService = jobRepoService; + } + + + + + + /** + * Schedules a new job to be executed periodically based on the provided parameters. + * <p> + * This method initializes a new {@link Job} instance with the specified start and end date times, and execution interval. + * It calculates the initial delay as the difference in seconds between the current time and the start date time. + * The job is initially set to a PENDING state. It then attempts to schedule the job to run at a fixed rate, + * starting after the initial delay and subsequently with the specified execution interval. + * If the job is successfully scheduled, its state is updated to INPROGRESS, and it is logged. + * In case of a scheduling failure due to a {@link RejectedExecutionException}, the job's state is set to FAILED, + * and the error is logged. + * </p> + * + * @param task the {@link Runnable} task that the job will execute + * @param startDateTime the {@link OffsetDateTime} specifying when the job should start + * @param endDateTime the {@link OffsetDateTime} specifying when the job should end + * @param executionInterval the interval, in seconds, between successive executions of the job + * @return the newly created and scheduled {@link Job} instance + * @throws RejectedExecutionException if the task cannot be scheduled for execution + */ + public Job startJob(Runnable task, Job job) { + + + if ( job.getEndDateTime().isBefore( OffsetDateTime.now() )) { + job.setState(ExecutionStateType.FAILED); + logger.error("Job with ID {} End Date is before now, the job will not be scheduled.", job.getUuid()); + return job; + } + + long initialDelay = Duration.between(OffsetDateTime.now(), job.getStartDateTime()).getSeconds(); + if (initialDelay<0) { + initialDelay = 0; + } + job = jobRepoService.createAndSaveJob(job); + + try { + ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(task, initialDelay, job.getExecutionInterval(), TimeUnit.SECONDS); + job.setFuture(future); + job.setState(ExecutionStateType.INPROGRESS); + logger.info("Job with ID {} started successfully.", job.getUuid()); + } catch (RejectedExecutionException e) { + job.setState(ExecutionStateType.FAILED); + logger.error("Job with ID {} could not be scheduled.", job.getUuid(), e); + } + + + job = jobRepoService.updateJob( job.getUuid(), job.getState()); + + return job; + } + + /** + * Attempts to stop a job identified by its UUID. + * <p> + * This method checks if the job exists and its current state. If the job is already in a + * {@link ExecutionStateType#CANCELLED} or {@link ExecutionStateType#COMPLETED} state, it logs + * the status and returns. Otherwise, it attempts to cancel the job's future execution. + * If the cancellation is successful, the job's state is set to {@link ExecutionStateType#CANCELLED}, + * and it logs the successful stop. If the job cannot be stopped (e.g., already completed or cancelled), + * its state is set to {@link ExecutionStateType#PENDING}, and a warning is logged. If the job does not + * exist, it logs a warning. + * </p> + * + * @param jobId the UUID of the job to stop + */ + public void stopJob(Job job) { + + if (job != null) { + + if (job.getState() == ExecutionStateType.CANCELLED ) { + logger.info("Job with ID {} is already CANCELED.", job.getUuid()); + jobRepoService.softDeleteJob( job ); + return; + } else if (job.getState() == ExecutionStateType.COMPLETED) { + logger.info("Job with ID {} is already COMPLETED.", job.getUuid()); + jobRepoService.softDeleteJob( job ); + return; + } + if (job.getFuture() != null) { + boolean wasCancelled = job.getFuture().cancel(true); + if (wasCancelled) { + job.setState(ExecutionStateType.CANCELLED); + jobRepoService.updateJob(job.getUuid(), job.getState()); + logger.info("Job with ID {} stopped successfully.", job.getUuid()); + } else { + job.setState(ExecutionStateType.PENDING); + jobRepoService.updateJob( job.getUuid(), job.getState()); + logger.warn("Job with ID {} could not be stopped because it has already completed, has been cancelled, or could not be cancelled for some other reason.", job.getUuid()); + } + } + } else { + logger.warn("Job does not exist."); + } + } + +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/metrico/services/MetricoService.java b/src/main/java/org/etsi/osl/metrico/services/MetricoService.java new file mode 100644 index 0000000000000000000000000000000000000000..04b4d92680da9801fa81695483600080861d51a0 --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/services/MetricoService.java @@ -0,0 +1,289 @@ +package org.etsi.osl.metrico.services; + +import jakarta.validation.constraints.NotNull; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.RouteBuilder; +import org.etsi.osl.metrico.JsonUtil; +import org.etsi.osl.metrico.mapper.DataAccessEndpointMapper; +import org.etsi.osl.metrico.mapper.JobMapper; +import org.etsi.osl.metrico.model.Job; +import org.etsi.osl.metrico.prometheus.PrometheusQueries; +import org.etsi.osl.metrico.repo.JobRepository; +import org.etsi.osl.metrico.reposervices.JobRepoService; +import org.etsi.osl.tmf.common.model.Any; +import org.etsi.osl.tmf.common.model.ELifecycle; +import org.etsi.osl.tmf.common.model.EValueType; +import org.etsi.osl.tmf.common.model.service.ResourceRef; +import org.etsi.osl.tmf.pm628.model.*; +import org.etsi.osl.tmf.rcm634.model.LogicalResourceSpecification; +import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationCreate; +import org.etsi.osl.tmf.ri639.model.LogicalResource; +import org.etsi.osl.tmf.ri639.model.Resource; +import org.etsi.osl.tmf.ri639.model.ResourceUpdate; +import org.etsi.osl.tmf.so641.model.ServiceOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.event.ApplicationStartedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Service +public class MetricoService extends RouteBuilder { + + private static final Logger logger = LoggerFactory.getLogger(JobService.class); + + + public static final String OSL_METRICO_RSPEC_NAME = "METRICO_Resource_Specification"; + public static final String OSL_METRICO_RSPEC_VERSION = "0.0.1"; + public static final String OSL_METRICO_RSPEC_CATEGORY = "metrico.osl.etsi.org/v1"; + public static final String OSL_METRICO_RESOURCE_CATEGORY = "metrico.osl.etsi.org/v1"; + public static final String OSL_METRICO_RSPEC_TYPE = "LogicalResourceSpecification"; + public static final String OSL_METRICO_RSPEC_DESCRIPTION = "This Specification is used to describe a generic METRICO job resource"; + + @Value("${PM_MEASUREMENT_COLLECTION_JOB_UPDATE}") + private String PM_MEASUREMENT_COLLECTION_JOB_UPDATE = ""; + + @Value("${PM_MEASUREMENT_COLLECTION_GET_JOB_BY_ID}") + private String PM_MEASUREMENT_COLLECTION_GET_JOB_BY_ID = ""; + + @Autowired + private JobRepoService jobRepoService; + + + @Autowired + private JobRepository jobRepository; + + + @Autowired + private final PrometheusQueries prometheusQueries; + private final ProducerTemplate producerTemplate; + + public MetricoService(PrometheusQueries prometheusQueries, ProducerTemplate producerTemplate) { + this.prometheusQueries = prometheusQueries; + this.producerTemplate = producerTemplate; + } + + + /** + * This one is executed when the cridge service application starts + * @param event + */ + @EventListener(ApplicationStartedEvent.class) + public void onApplicationEvent() { + + registerMetricoResourceSpec(); + + List<Job> jobsPending = jobRepoService.findAll(); + logger.info("===== Pending jobs from previous sessions ====="); + for (Job job : jobsPending) { + logger.info("try to resume jobuuid: {}, state:{}, start: {}, end:{}, mcjid: {} ", job.getUuid(), job.getState(), job.getStartDateTime(), job.getEndDateTime(), job.getMeasurementCollectionJobRef() ); + + + //delete previous job from DB. a new one will be created + jobRepoService.softDeleteJob(job); + + MeasurementCollectionJobRef mjref = new MeasurementCollectionJobRef(); + mjref.setId( job.getMeasurementCollectionJobRef().toString() ); + this.startPeriodicQueryToPrometheusRef(mjref ); + } + + logger.info("===== Pending jobs from previous sessions done ====="); + + } + + + private void registerMetricoResourceSpec() { + logger.info("===== Pending jobs from previous sessions ====="); + + + ResourceSpecificationCreate rsc = new ResourceSpecificationCreate(); + rsc.setName( OSL_METRICO_RSPEC_NAME ); + rsc.setCategory( OSL_METRICO_RSPEC_CATEGORY ); + rsc.setVersion( OSL_METRICO_RSPEC_VERSION ); + rsc.setDescription( OSL_METRICO_RSPEC_DESCRIPTION ); + rsc.setType( OSL_METRICO_RSPEC_TYPE ); + + rsc.setLifecycleStatus( ELifecycle.ACTIVE.getValue() ); + rsc.addResourceSpecificationCharacteristicItemShort( "_MT_CHARACTERISTIC_NAME", "", EValueType.TEXT.getValue(), "The characteristic of the service with id _MT_SERVICEUUID that will be updated with monitoring metrics", false); + rsc.addResourceSpecificationCharacteristicItemShort( "_MT_SERVICEUUID", "", EValueType.TEXT.getValue(), "The id of the service to update", false); + rsc.addResourceSpecificationCharacteristicItemShort( "_MT_END_TIME", "", EValueType.TEXT.getValue(), "The ending time of the monitoring job", false); + rsc.addResourceSpecificationCharacteristicItemShort( "_MT_START_TIME", "", EValueType.TEXT.getValue(), "The starting time of the monitoring job", false); + rsc.addResourceSpecificationCharacteristicItemShort( "_MT_RECURRING_INTERVAL", "G_1MN", EValueType.TEXT.getValue(), "The polling interval of the monitoring source", false); + rsc.addResourceSpecificationCharacteristicItemShort( "_MT_TYPE", "PROMETHEUS", EValueType.TEXT.getValue(), "The monitoring source type", false); + rsc.addResourceSpecificationCharacteristicItemShort( "_MT_QUERY", "", EValueType.TEXT.getValue(), "The query towards the monitoring source (e.g. query=gnb_service_state)", false); + rsc.addResourceSpecificationCharacteristicItemShort( "_MT_URL", "", EValueType.TEXT.getValue(), "The monitoring source URL (e.g. https://prom.osl.etsi.org:9090)", false); + + + LogicalResourceSpecification result = prometheusQueries.createOrUpdateResourceSpecByNameCategoryVersion(rsc); + while ( result == null ) { + try { + logger.info("Cannot get resource for registerMetricoResourceSpec. Retrying in 10 seconds" ); + Thread.sleep( 10000 ); + } catch (InterruptedException e) { + e.printStackTrace(); + } + result = prometheusQueries.createOrUpdateResourceSpecByNameCategoryVersion(rsc); + } + } + + + @Autowired + private ProducerTemplate template; + + public String[] queryToPrometheus(@NotNull MeasurementCollectionJob givenMCJ){ + DataAccessEndpoint givenDataAccessEndpoint = givenMCJ.getDataAccessEndpoint().get(0); + Job job = JobMapper.measurementCollectionJobMapToJob(givenMCJ); + String promURL = job.getDataAccessEndPointUri().getScheme() + "://" + job.getDataAccessEndPointUri().getAuthority(); + String promQuery = job.getDataAccessEndPointUri().getQuery(); + promQuery = promQuery.replace("query=", ""); + + String [] promResponse = prometheusQueries.sendQueryToPrometheus(promURL, promQuery, givenMCJ, job).split("\n"); + + DataFilterTemplate filterTemplate = new DataFilterTemplate(); + filterTemplate.setName(promQuery); + DataFilterAttributeStringArray stringArray = new DataFilterAttributeStringArray(); + stringArray.setValue(List.of(promResponse)); + DataFilterMapItem dataFilterMapItem = new DataFilterMapItem(); + dataFilterMapItem.setFilterTemplate(filterTemplate); + dataFilterMapItem.setStringArray(stringArray); + DataFilterMap dataFilterMap = new DataFilterMap(); + dataFilterMap.addMappingsItem(dataFilterMapItem); + givenDataAccessEndpoint.setUriQueryFilter(dataFilterMap); + + List<DataAccessEndpointMVO> newDataAccessEndpointMVO = new ArrayList<>(); + newDataAccessEndpointMVO.add(DataAccessEndpointMapper.INSTANCE.toDataAccessEndpointMVO(givenDataAccessEndpoint)); + +// MeasurementCollectionJobMVO promResponseMCJ = new MeasurementCollectionJobMVO(); + +// promResponseMCJ.setDataAccessEndpoint(newDataAccessEndpointMVO); +// producerTemplate.sendBodyAndHeader(PM_MEASUREMENT_COLLECTION_JOB_UPDATE, JsonUtil.toJsonString(promResponseMCJ),"mcjid",givenMCJ.getUuid() ); + + return promResponse; + } + + public void startPeriodicQueryToPrometheus(@NotNull MeasurementCollectionJob givenMCJ){ + Job job = JobMapper.measurementCollectionJobMapToJob(givenMCJ); + String promURL = job.getDataAccessEndPointUri().getScheme() + "://" + job.getDataAccessEndPointUri().getAuthority(); + String promQuery = job.getDataAccessEndPointUri().getQuery(); + + job = prometheusQueries.startPeriodicQuery(promURL, promQuery, job, givenMCJ ); + + if (job.getState() == ExecutionStateType.FAILED) { + logger.atError().setMessage("Periodic query failed to start due to internal error.").log(); + + } else { + logger.atInfo().setMessage("Periodic query started, with ID: " + job.getUuid()).log(); + } + + givenMCJ.setExecutionState(job.getState()); + + producerTemplate.sendBodyAndHeader( PM_MEASUREMENT_COLLECTION_JOB_UPDATE, JsonUtil.toJsonString(givenMCJ), "mcjid", givenMCJ.getUuid() ); + updateRelatedResource(givenMCJ); + } + + + + public void startPeriodicQueryToPrometheusRef(@NotNull MeasurementCollectionJobRef mcjRef){ + MeasurementCollectionJob givenMCJ = retrieveMeasurementCollectionJob(mcjRef); + + startPeriodicQueryToPrometheus(givenMCJ); + } + + + public void startPeriodicQueryToPrometheusEvent(@NotNull MeasurementCollectionJobCreateEvent mcjevent){ + + MeasurementCollectionJob givenMCJ = retrieveMeasurementCollectionJob( mcjevent.getEvent().getMeasurementCollectionJob().getId() ); + + if ( givenMCJ != null) { + startPeriodicQueryToPrometheus(givenMCJ); + } else { + + logger.error("=======> CANNOT retrieve Measurement Collection Job with mcjId = " + mcjevent.getEvent().getMeasurementCollectionJob().getId() +" from activeMQ"); + } + } + + public MeasurementCollectionJob retrieveMeasurementCollectionJob(String mcjId) { + + logger.debug("will retrieve Measurement Collection Job with mcjId = " + mcjId +" from database"); + try { + Object response = template. + requestBody( PM_MEASUREMENT_COLLECTION_GET_JOB_BY_ID, mcjId); + if ( !(response instanceof String)) { + logger.error("Measurement Collection Job object is wrong."); + return null; + } + logger.debug("retrieveMeasurementCollectionJobById response is: " + response); + MeasurementCollectionJob mcj = JsonUtil.toJsonObj( (String)response, MeasurementCollectionJob.class); + return mcj; + }catch (Exception e) { + logger.error("Cannot retrieve Measurement Collection Job details from database. " + e.toString()); + } + return null; + } + + public MeasurementCollectionJob retrieveMeasurementCollectionJob(MeasurementCollectionJobRef mcjRef) { + String mcjId = mcjRef.getId(); + + return retrieveMeasurementCollectionJob(mcjId); + } + + + private void updateRelatedResource(@NotNull MeasurementCollectionJob givenMCJ) { + //retrieve related service from inventory + //retrieve related resource from inventory + //patch resource state + String servUUID = givenMCJ.getProducingApplicationId();//this contains the related ServiceUUID with this MCJ + + logger.debug("updateRelatedResource servUUID = " + servUUID ); + org.etsi.osl.tmf.sim638.model.Service aService = prometheusQueries.retrieveService(servUUID); + + if ( aService!=null && aService.getSupportingResource().size()>0) { + + ResourceRef resRef = aService.getSupportingResource().stream().findFirst().get(); + + //Resource aResource = retrieveResource(resRef.getId()); + logger.debug("updateRelatedResource resRef = " + resRef.getId() ); + + ResourceUpdate rup = new ResourceUpdate(); + org.etsi.osl.tmf.ri639.model.Characteristic resCharacteristicItem = new org.etsi.osl.tmf.ri639.model.Characteristic(); + resCharacteristicItem.setName( "_MT_MCJ_REF" ); + resCharacteristicItem.setValueType( "TEXT" ); + Any val = new Any(); + val.setValue( givenMCJ.getUuid() ); + val.setAlias( "" ); + resCharacteristicItem.setValue( val ); + rup.addResourceCharacteristicItem( resCharacteristicItem ); + + if ( givenMCJ.getExecutionState().equals( ExecutionStateType.FAILED ) ) { + rup.setResourceStatus( org.etsi.osl.tmf.ri639.model.ResourceStatusType.SUSPENDED ); + } else { + rup.setResourceStatus( org.etsi.osl.tmf.ri639.model.ResourceStatusType.AVAILABLE ); + } + + prometheusQueries.updateResourceById(resRef.getId(), rup ); + + } + + } + + @Override + public void configure() throws Exception { + // TODO Auto-generated method stub + + } + + + + +} diff --git a/src/main/java/org/etsi/osl/metrico/services/MetricoServiceRouteBuilder.java b/src/main/java/org/etsi/osl/metrico/services/MetricoServiceRouteBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..9a62a499356766a8d218f18818e3e266955c1d0c --- /dev/null +++ b/src/main/java/org/etsi/osl/metrico/services/MetricoServiceRouteBuilder.java @@ -0,0 +1,47 @@ +package org.etsi.osl.metrico.services; + +import org.apache.camel.LoggingLevel; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.model.dataformat.JsonLibrary; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJob; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJobCreateEvent; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJobRef; +import org.etsi.osl.tmf.ri639.model.ResourceCreateNotification; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; + +@Configuration +@Component +public class MetricoServiceRouteBuilder extends RouteBuilder { + + private static final transient Log logger = LogFactory.getLog(MetricoServiceRouteBuilder.class.getName()); + + @Autowired + private MetricoService metricoService; + + @Value("${EVENT_MEASUREMENT_COLLECTION_JOB_CREATE}") + private String EVENT_MEASUREMENT_COLLECTION_JOB_CREATE = ""; + + public void configure() throws Exception { + +// from(EVENT_MEASUREMENT_COLLECTION_JOB_CREATED) +// .log(LoggingLevel.INFO, log, EVENT_MEASUREMENT_COLLECTION_JOB_CREATED + " message received!") +// .to("log:DEBUG?showBody=true&showHeaders=true").unmarshal() +// .json(JsonLibrary.Jackson, MeasurementCollectionJob.class, true) +// .bean(metricoService, "startPeriodicQueryToPrometheus(${body})"); + + from(EVENT_MEASUREMENT_COLLECTION_JOB_CREATE) + .log(LoggingLevel.INFO, log, EVENT_MEASUREMENT_COLLECTION_JOB_CREATE + " message received!") + .to("log:DEBUG?showBody=true&showHeaders=true") + .unmarshal() + .json(JsonLibrary.Jackson, MeasurementCollectionJobCreateEvent.class, true) + .bean(metricoService, "startPeriodicQueryToPrometheusEvent(${body})"); + + } + + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ea2b555df598dcdf45f74ee6a8d4916ea03a3a7 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,82 @@ +spring: + config: + activate: + on-profile: "default" + application: + name: metrico + main: + web-application-type: servlet + datasource: + url: jdbc:mysql://localhost:13306/metricodb?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC + password: letmein + username: root + hikari: + minimumIdle: 2 + maximumPoolSize: 40 + idleTimeout: 120000 + connectionTimeout: 400000 + leakDetectionThreshold: 100000 + jpa: + database-platform: org.etsi.osl.metrico.LocalMysqlDialect + hibernate: + ddl-auto: update + show-sql: false + generate-ddl: true + properties: + hibernate: + connection: + characterEncoding: utf-8 + CharSet: utf-8 + useUnicode: true + activemq: + brokerUrl: tcp://localhost:61616?jms.watchTopicAdvisories=false + user: artemis + password: artemis + pool: + enabled: true + max-connections: 100 + packages: + trust-all: true + security: + oauth2: + resourceserver: + jwt: + issuer-uri: http://keycloak:8080/auth/realms/openslice + jwk-set-uri: http://keycloak:8080/auth/realms/openslice/.well-known/openid-configuration +server: + port: 8030 + + +logging: + level: + org.etsi.osl.metrico: DEBUG + root: INFO + org.springframework: INFO + org.apache.camel: INFO + reactor.netty.tcp.TcpClient: DEBUG + reactor.netty.http.client.HttpClient: DEBUG + pattern: + console: "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" + file: "%d %p %c{1.} [%t] %m%n" + +scheduling.enabled: true + +#NUMBER OF THREADS FOR THE METRICO THREAD POOL +METRICO_THREAD_POOL_SIZE: 10 + +#TMF QUEUES +PM_MEASUREMENT_COLLECTION_GET_JOB_BY_ID: "jms:queue:PM.MEASUREMENTCOLLECTIONJOB.GET_BY_ID" +PM_MEASUREMENT_COLLECTION_JOBS_GET: "jms:queue:PM.MEASUREMENTCOLLECTIONJOBS.GET" +PM_MEASUREMENT_COLLECTION_JOB_ADD: "jms:queue:PM.MEASUREMENTCOLLECTIONJOB.ADD" +PM_MEASUREMENT_COLLECTION_JOB_UPDATE: "jms:queue:PM.MEASUREMENTCOLLECTIONJOB.UPDATE" + +EVENT_MEASUREMENT_COLLECTION_JOB_CREATE: "jms:topic:EVENT.MEASUREMENTCOLLECTIONJOB.CREATE" +EVENT_MEASUREMENT_COLLECTION_JOB_EXECUTION_STATE_CHANGED: "jms:topic:EVENT.MEASUREMENTCOLLECTIONJOB.STATECHANGED" +EVENT_MEASUREMENT_COLLECTION_JOB_DELETE: "jms:topic:EVENT.MEASUREMENTCOLLECTIONJOB.DELETE" +EVENT_MEASUREMENT_COLLECTION_JOB_ATTRIBUTE_VALUE_CHANGED: "jms:topic:EVENT.MEASUREMENTCOLLECTIONJOB.ATTRCHANGED" + +CATALOG_UPDADD_RESOURCESPEC: "jms:queue:CATALOG.UPDADD.RESOURCESPEC" +CATALOG_GET_SERVICE_BY_ID: "jms:queue:CATALOG.GET.SERVICE" +CATALOG_GET_RESOURCE_BY_ID: "jms:queue:CATALOG.GET.RESOURCE" +CATALOG_UPD_RESOURCE: "jms:queue:CATALOG.UPD.RESOURCE" +CATALOG_UPD_SERVICE: "jms:queue:CATALOG.UPD.SERVICE" diff --git a/src/test/java/org/etsi/osl/metrico/mapper/JobMapperTest.java b/src/test/java/org/etsi/osl/metrico/mapper/JobMapperTest.java new file mode 100644 index 0000000000000000000000000000000000000000..40da5a53eae9cea07c5c8c27f32b19910e38f7f5 --- /dev/null +++ b/src/test/java/org/etsi/osl/metrico/mapper/JobMapperTest.java @@ -0,0 +1,44 @@ +package org.etsi.osl.metrico.mapper; + +import org.etsi.osl.tmf.pm628.model.DataAccessEndpoint; +import org.etsi.osl.tmf.pm628.model.DataFilterMap; +import org.etsi.osl.tmf.pm628.model.DataFilterMapItem; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJob; +import org.jetbrains.annotations.NotNull; + +import java.net.URI; +import java.util.*; + +public class JobMapperTest { + + public MeasurementCollectionJob measurementCollectionJobCreate() { + MeasurementCollectionJob measurementCollectionJob = new MeasurementCollectionJob(); + + List<DataAccessEndpoint> dataAccessEndpointList = new ArrayList<>(); + dataAccessEndpointList.add(dataAccessEndpointCreate()); + + measurementCollectionJob.setUuid("9f22dc98-f439-4fdd-98e3-f6471cf8ca67"); + measurementCollectionJob.setDataAccessEndpoint(dataAccessEndpointList); + + + return measurementCollectionJob; + } + + public DataAccessEndpoint dataAccessEndpointCreate(){ + DataAccessEndpoint dataAccessEndpoint = new DataAccessEndpoint(); + dataAccessEndpoint.setUuid("123e4567-e89b-12d3-a456-426614174000"); + dataAccessEndpoint.setUri(URI.create("example.com")); + dataAccessEndpoint.setApiType("Prometheus"); + return dataAccessEndpoint; + + } + + public DataFilterMap dataFilterMapCreate(){ + DataFilterMap dataFilterMap = new DataFilterMap(); + // dataFilterMap.setMappings(); + + return dataFilterMap; + } + + +} diff --git a/src/test/java/org/etsi/osl/metrico/model/JobTest.java b/src/test/java/org/etsi/osl/metrico/model/JobTest.java new file mode 100644 index 0000000000000000000000000000000000000000..31a6c295dcf2918437526b8723b6ce5d79489f10 --- /dev/null +++ b/src/test/java/org/etsi/osl/metrico/model/JobTest.java @@ -0,0 +1,72 @@ +package org.etsi.osl.metrico.model; + +import org.etsi.osl.tmf.pm628.model.ExecutionStateType; +import org.junit.jupiter.api.Test; + +import java.time.OffsetDateTime; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +class JobTest { + + @Test + void testDefaultConstructor() { + Job job = new Job(); + assertEquals(ExecutionStateType.PENDING, job.getState()); + assertEquals(10, job.getExecutionInterval()); + assertNotNull(job.getStartDateTime()); + assertTrue(ChronoUnit.SECONDS.between(OffsetDateTime.now(), job.getStartDateTime()) <= 1); + } + + @Test + void testConstructorWithStopDateTime() { + OffsetDateTime stopDateTime = OffsetDateTime.now().plusDays(1); + Job job = new Job(stopDateTime); + assertEquals(stopDateTime, job.getEndDateTime()); + assertEquals(ExecutionStateType.PENDING, job.getState()); + assertEquals(10, job.getExecutionInterval()); + } + + @Test + void testConstructorWithStartAndStopDateTime() { + OffsetDateTime startDateTime = OffsetDateTime.now(); + OffsetDateTime stopDateTime = startDateTime.plusDays(1); + Job job = new Job(startDateTime, stopDateTime); + assertEquals(startDateTime, job.getStartDateTime()); + assertEquals(stopDateTime, job.getEndDateTime()); + assertEquals(ExecutionStateType.PENDING, job.getState()); + assertEquals(10, job.getExecutionInterval()); + } + + @Test + void testConstructorWithAllParams() { + OffsetDateTime startDateTime = OffsetDateTime.now(); + OffsetDateTime stopDateTime = startDateTime.plusDays(1); + Integer executionInterval = 15; + Job job = new Job(startDateTime, stopDateTime, executionInterval); + assertEquals(startDateTime, job.getStartDateTime()); + assertEquals(stopDateTime, job.getEndDateTime()); + assertEquals(executionInterval, job.getExecutionInterval()); + assertEquals(ExecutionStateType.PENDING, job.getState()); + } + + @Test + void testToString() { + Job job = new Job(); + job.setUuid(UUID.fromString("123e4567-e89b-12d3-a456-426614174000")); + job.setState(ExecutionStateType.PENDING); + job.setStartDateTime(OffsetDateTime.parse("2023-01-01T10:15:30+01:00")); + job.setEndDateTime(OffsetDateTime.parse("2023-01-02T10:15:30+01:00")); + job.setExecutionInterval(10); + job.setDataAccessEndPointRef(UUID.fromString("123e4567-e89b-12d3-a456-426614174001")); + job.setScheduleDefinitionRef(UUID.fromString("123e4567-e89b-12d3-a456-426614174002")); + job.setMeasurementCollectionJobRef(UUID.fromString("123e4567-e89b-12d3-a456-426614174003")); + job.setDeleted(false); + + String expected = "Job{uuid=123e4567-e89b-12d3-a456-426614174000, state=pending, startDateTime=2023-01-01T10:15:30+01:00, endDateTime=2023-01-02T10:15:30+01:00, executionInterval=10, dataAccessEndPointRef=123e4567-e89b-12d3-a456-426614174001, scheduleDefinitionRef=123e4567-e89b-12d3-a456-426614174002, measurementCollectionJobRef=123e4567-e89b-12d3-a456-426614174003, deleted=false}"; + assertEquals(expected, job.toString()); + } + +} \ No newline at end of file diff --git a/src/test/java/org/etsi/osl/metrico/services/JobServiceTest.java b/src/test/java/org/etsi/osl/metrico/services/JobServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ed1f285bb862d39c96741b340bc3df42676afa93 --- /dev/null +++ b/src/test/java/org/etsi/osl/metrico/services/JobServiceTest.java @@ -0,0 +1,106 @@ +package org.etsi.osl.metrico.services; + +import org.etsi.osl.metrico.model.Job; +import org.etsi.osl.metrico.reposervices.JobRepoService; +import org.etsi.osl.tmf.pm628.model.ExecutionStateType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.slf4j.Logger; + +import java.time.OffsetDateTime; +import java.util.UUID; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class JobServiceTest { + + @Mock + private JobRepoService jobRepoService; + + @Mock + private ScheduledExecutorService scheduler; + + @Mock + private Logger logger; + + private JobService jobService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + jobService = new JobService(jobRepoService); + } + + @Test + void testStartJob_Success() { + // Initialize the job with specific parameters + OffsetDateTime startDateTime = OffsetDateTime.now().plusSeconds(5); + OffsetDateTime endDateTime = startDateTime.plusMinutes(10); + Integer executionInterval = 5; + Runnable task = () -> {}; + Job expectedJob = new Job(startDateTime, endDateTime, executionInterval); + // Assert the initial state is PENDING + assertEquals(expectedJob.getState(), ExecutionStateType.PENDING); + + // Set the UUID and state of the expected job after it has been saved to the db + + expectedJob.setState(ExecutionStateType.INPROGRESS); + + // Mock jobRepoService.createAndSaveJob() to return the expected Job + when(jobRepoService.createAndSaveJob(expectedJob)).thenReturn(expectedJob); + +// // Mock scheduler.scheduleAtFixedRate() to not throw an exception +// ScheduledFuture<?> mockFuture = mock(ScheduledFuture.class); +// when(scheduler.scheduleAtFixedRate(any(Runnable.class), eq(5L), eq(5L), eq(TimeUnit.SECONDS))) +// .thenReturn(mockFuture); + +// // Call jobService.startJob() with valid parameters +// Job resultJob = jobService.startJob(task, startDateTime, endDateTime, executionInterval); +// +// // Verify job state is INPROGRESS, and job is added to the jobs map +// assertEquals(ExecutionStateType.INPROGRESS, resultJob.getState()); +// assertNotNull(JobService.getJobs().get(resultJob.getUuid())); +// assertEquals(expectedJob, JobService.getJobs().get(resultJob.getUuid())); + } + @Test + void testStartJob_NullPointerException() { + // Mock jobRepoService.createAndSaveJob() to throw NullPointerException + // Call jobService.startJob() with valid parameters + // Verify job state is FAILED + } + + @Test + void testStartJob_RejectedExecutionException() { + // Mock scheduler.scheduleAtFixedRate() to throw RejectedExecutionException + // Call jobService.startJob() with valid parameters + // Verify job state is FAILED + } + + @Test + void testStopJob_InProgress() { + // Add a job to the jobs map with state INPROGRESS + // Call JobService.stopJob() with the job's UUID + // Verify job state is CANCELLED + } + + @Test + void testStopJob_AlreadyCompleted() { + // Add a job to the jobs map with state COMPLETED + // Call JobService.stopJob() with the job's UUID + // Verify job state remains COMPLETED + } + + @Test + void testStopJob_DoesNotExist() { + // Call JobService.stopJob() with a non-existent job UUID + // Verify appropriate warning is logged + } +} \ No newline at end of file diff --git a/src/test/java/org/etsi/osl/metrico/services/MetricoServiceTest.java b/src/test/java/org/etsi/osl/metrico/services/MetricoServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..23940b6c1256d01c0580dd8c6ec8ad2a35fb4e11 --- /dev/null +++ b/src/test/java/org/etsi/osl/metrico/services/MetricoServiceTest.java @@ -0,0 +1,60 @@ +package org.etsi.osl.metrico.services; + +import org.etsi.osl.tmf.pm628.model.DataAccessEndpoint; +import org.etsi.osl.tmf.pm628.model.Granularity; +import org.etsi.osl.tmf.pm628.model.MeasurementCollectionJob; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.*; + +import java.net.URI; +import java.net.URISyntaxException; + + +@SpringBootTest +@ExtendWith(SpringExtension.class) +public class MetricoServiceTest { + + @Autowired + private MetricoService metricoService; + + private MeasurementCollectionJob mcj; + + @BeforeEach + public void setUp() throws URISyntaxException { + mcj = new MeasurementCollectionJob(); + mcj.setUuid("123e4567-e89b-12d3-a456-426614174000"); + + mcj.granularity(Granularity.G_10SEC); + + DataAccessEndpoint dae = new DataAccessEndpoint(); + dae.setApiType("PROMETHEUS"); + dae.setUri(new URI("http://")); + dae.setUuid("123e4567-e89b-12d3-a456-426614174011"); + List<DataAccessEndpoint> daeList = new ArrayList<>(); + daeList.add(dae); + mcj.setDataAccessEndpoint(daeList); + + //job.setDataAccessEndPointUri(new URI("http://")); + + } + +// @Test +// public void testQueryToPrometheus() { +// String[] result = metricoService.queryToPrometheus(mcj); +// System.out.println(Arrays.toString(result)); +// +// //assertEquals("OK", result); +// } +// +// @Test +// public void testStartPeriodicQueryToPrometheus() throws InterruptedException { +// metricoService.startPeriodicQueryToPrometheus(mcj); +// Thread.sleep(60000); +// } +} \ No newline at end of file diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..e8714e1d756e5e9a9305c36d685bb909cfca8668 --- /dev/null +++ b/src/test/resources/application.yml @@ -0,0 +1,17 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb + driverClassName: org.h2.Driver + username: sa + password: password + jpa: + database-platform: org.hibernate.dialect.H2Dialect + + +#NUMBER OF THREADS FOR THE METRICO THREAD POOL +METRICO_THREAD_POOL_SIZE: 10 + +CATALOG_GET_SERVICE_BY_ID: "jms:queue:CATALOG.GET.SERVICE" +CATALOG_GET_RESOURCE_BY_ID: "jms:queue:CATALOG.GET.RESOURCE" +CATALOG_UPD_RESOURCE: "jms:queue:CATALOG.UPD.RESOURCE" +CATALOG_UPD_SERVICE: "jms:queue:CATALOG.UPD.SERVICE" \ No newline at end of file