Update babel dependency in model-loader 16/137716/1 master
authorFiete Ostkamp <Fiete.Ostkamp@telekom.de>
Thu, 18 Apr 2024 15:05:19 +0000 (17:05 +0200)
committerFiete Ostkamp <Fiete.Ostkamp@telekom.de>
Thu, 18 Apr 2024 15:05:52 +0000 (17:05 +0200)
Issue-ID: AAI-3832
Change-Id: I1cd1588dac16401c7f5064398ff7b8de71bffe30
Signed-off-by: Fiete Ostkamp <Fiete.Ostkamp@telekom.de>
72 files changed:
.gitignore
INFO.yaml
README.md [moved from Readme.md with 100% similarity]
pom.xml
releases/1.13.5-container-release.yaml [new file with mode: 0644]
releases/1.13.5-maven-release.yaml [new file with mode: 0644]
releases/1.13.6-container-release.yaml [new file with mode: 0644]
src/main/java/org/onap/aai/modelloader/babel/BabelArtifact.java [moved from src/test/java/org/onap/aai/modelloader/TestModelLoaderApplication.java with 60% similarity]
src/main/java/org/onap/aai/modelloader/babel/BabelArtifactService.java [new file with mode: 0644]
src/main/java/org/onap/aai/modelloader/config/BeanConfig.java [new file with mode: 0644]
src/main/java/org/onap/aai/modelloader/config/DistributionClientStartupConfig.java [new file with mode: 0644]
src/main/java/org/onap/aai/modelloader/config/ModelLoaderConfig.java
src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandler.java
src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactHandler.java
src/main/java/org/onap/aai/modelloader/extraction/VnfCatalogExtractor.java
src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java
src/main/java/org/onap/aai/modelloader/notification/BabelArtifactConverter.java
src/main/java/org/onap/aai/modelloader/notification/EventCallback.java
src/main/java/org/onap/aai/modelloader/notification/NotificationDataImpl.java
src/main/java/org/onap/aai/modelloader/notification/NotificationPublisher.java
src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java
src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java
src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java [new file with mode: 0644]
src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java [deleted file]
src/main/java/org/onap/aai/modelloader/service/ArtifactDeploymentManager.java
src/main/java/org/onap/aai/modelloader/service/ArtifactInfoImpl.java
src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java [deleted file]
src/main/java/org/onap/aai/modelloader/service/ModelController.java [moved from src/main/java/org/onap/aai/modelloader/service/ModelLoaderService.java with 56% similarity]
src/main/java/org/onap/aai/modelloader/service/SdcConnectionJob.java
src/main/resources/application.properties
src/test/java/org/onap/aai/modelloader/BabelClientTestConfiguration.java [new file with mode: 0644]
src/test/java/org/onap/aai/modelloader/DistributionClientTestConfiguration.java [new file with mode: 0644]
src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java
src/test/java/org/onap/aai/modelloader/csar/extractor/VnfCatalogExtractorTest.java
src/test/java/org/onap/aai/modelloader/distribution/EventCallbackAspect.java [new file with mode: 0644]
src/test/java/org/onap/aai/modelloader/distribution/NotificationIntegrationTest.java [new file with mode: 0644]
src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java
src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java
src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java
src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java
src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactParser.java
src/test/java/org/onap/aai/modelloader/entity/model/TestNamedQueryArtifactParser.java
src/test/java/org/onap/aai/modelloader/extraction/TestArtifactInfoExtractor.java
src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java [new file with mode: 0644]
src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerVnfcTest.java
src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java [new file with mode: 0644]
src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java
src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java
src/test/java/org/onap/aai/modelloader/notification/TestBabelArtifactConverter.java
src/test/java/org/onap/aai/modelloader/notification/TestEventCallback.java
src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java [deleted file]
src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java
src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java
src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java
src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java
src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java
src/test/java/org/onap/aai/modelloader/restclient/TracingTest.java [new file with mode: 0644]
src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java [deleted file]
src/test/java/org/onap/aai/modelloader/service/TestModelController.java [moved from src/test/java/org/onap/aai/modelloader/service/TestModelLoaderService.java with 50% similarity]
src/test/java/org/onap/aai/modelloader/service/TestModelLoaderServiceWithSdc.java
src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java
src/test/java/org/onap/aai/modelloader/util/TestGizmoTranslator.java
src/test/java/org/onap/aai/modelloader/util/TestJsonXmlConverter.java
src/test/resources/__files/artifactTypes.json [new file with mode: 0644]
src/test/resources/__files/kafkaBootstrap.json [new file with mode: 0644]
src/test/resources/__files/modelResponse.xml [new file with mode: 0644]
src/test/resources/__files/service-TestSvc-csar-babel-response.json [new file with mode: 0644]
src/test/resources/__files/service-TestSvc-csar.csar [new file with mode: 0644]
src/test/resources/application.properties [new file with mode: 0644]
src/test/resources/logback-test.xml
src/test/resources/model-loader.properties
version.properties

index 56f75e2..e4b4035 100644 (file)
@@ -7,3 +7,4 @@ debug-logs/
 .checkstyle
 .idea/
 *.iml
+.vscode
\ No newline at end of file
index fb42332..3cd8e0a 100644 (file)
--- a/INFO.yaml
+++ b/INFO.yaml
@@ -41,6 +41,16 @@ committers:
       id: 'jimmydot'
       company: 'ATT'
       timezone: 'America/Detroit'
+    - name: 'Fiete Ostkamp'
+      email: 'fiete.ostkamp@telekom.de'
+      id: 'fostkamp'
+      company: 'Deutsche Telekom'
+      timezone: 'Europe/Berlin'
+    - name: 'Nandkishor Patke'
+      email: 'nandkishor-laxman.patke@t-systems.com'
+      id: 'nandkishorpatke'
+      company: 'T-Systems'
+      timezone: 'Asia/Kolkata'
 tsc:
     approval: 'https://lists.onap.org/g/onap-tsc'
     changes:
@@ -65,3 +75,9 @@ tsc:
         - type: 'removal'
           name: 'Harish Kajur'
           link: 'https://lists.onap.org/g/onap-tsc/message/8850'
+        - type: 'Addition'
+          name: 'Fiete Ostkamp'
+          link: 'https://lists.onap.org/g/onap-tsc/message/9499'
+        - type: 'Addition'
+          name: 'Nandkishor Patke'
+          link: 'https://lists.onap.org/g/onap-tsc/message/9499'
similarity index 100%
rename from Readme.md
rename to README.md
diff --git a/pom.xml b/pom.xml
index abf60e2..1a3028c 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -33,7 +33,7 @@
        <groupId>org.onap.aai.model-loader</groupId>
        <artifactId>model-loader</artifactId>
        <name>aai-model-loader</name>
-       <version>1.12.0-SNAPSHOT</version>
+       <version>1.14.0-SNAPSHOT</version>
 
        <dependencyManagement>
                <dependencies>
                                <type>pom</type>
                                <scope>import</scope>
                        </dependency>
+                       <dependency>
+                               <groupId>org.springframework.cloud</groupId>
+                               <artifactId>spring-cloud-dependencies</artifactId>
+                               <version>${spring-cloud.version}</version>
+                               <type>pom</type>
+                               <scope>import</scope>
+                       </dependency>
                </dependencies>
        </dependencyManagement>
 
                <start-class>org.onap.aai.modelloader.service.ModelLoaderApplication</start-class>
                <nexusproxy>https://nexus.onap.org</nexusproxy>
                <docker.location>${basedir}/target</docker.location>
-               <spring-boot.version>2.3.12.RELEASE</spring-boot.version>
+               <spring-boot.version>2.4.13</spring-boot.version>
+               <spring-cloud.version>2020.0.2</spring-cloud.version>
                <apache.commons-text.version>1.10.0</apache.commons-text.version>
                <commons-compress.version>1.22</commons-compress.version>
+               <gson.version>2.10.1</gson.version>
                <hamcrest-all.version>1.3</hamcrest-all.version>
-               <babel.version>1.9.5</babel.version>
+               <babel.version>1.13.0</babel.version>
                <aai.rest.client.version>1.2.1</aai.rest.client.version>
-               <sdc-distribution-client.version>2.0.0</sdc-distribution-client.version>
+               <sdc-distribution-client.version>2.1.1</sdc-distribution-client.version>
                <logback.version>1.2.11</logback.version>
                <!-- docker related properties -->
                <docker.fabric.version>0.39.0</docker.fabric.version>
@@ -65,7 +74,7 @@
                <aai.build.directory>${project.build.directory}/${project.artifactId}-${project.version}-build/</aai.build.directory>
                <aai.docker.namespace>onap</aai.docker.namespace>
                <aai.base.image>alpine</aai.base.image>
-               <aai.base.image.version>1.8.1</aai.base.image.version>
+               <aai.base.image.version>1.13.2</aai.base.image.version>
                <!-- This will be used for the docker images as the default format of maven build has issues -->
                <maven.build.timestamp.format>yyyyMMdd'T'HHmmss'Z'</maven.build.timestamp.format>
 
                        </build>
                </profile>
        </profiles>
+
        <dependencies>
                <dependency>
                        <groupId>org.springframework.boot</groupId>
                                </exclusion>
                        </exclusions>
                </dependency>
+               <dependency>
+                       <groupId>org.springframework.boot</groupId>
+                       <artifactId>spring-boot-starter-aop</artifactId>
+                       <scope>test</scope>
+               </dependency>
                <dependency>
                        <groupId>org.apache.kafka</groupId>
                        <artifactId>kafka-clients</artifactId>
-                       <version>3.3.1</version>
+                       <!-- <version>3.3.1</version> -->
+               </dependency>
+               <dependency>
+                       <groupId>org.springframework.kafka</groupId>
+                       <artifactId>spring-kafka</artifactId>
+                       <!-- <version>3.1.2</version> -->
+               </dependency>
+               <dependency>
+                       <groupId>org.springframework.kafka</groupId>
+                       <artifactId>spring-kafka-test</artifactId>
+                       <!-- <version>3.1.1</version> -->
+                       <scope>test</scope>
                </dependency>
                <dependency>
                        <groupId>org.onap.aai</groupId>
                <dependency>
                        <groupId>com.google.code.gson</groupId>
                        <artifactId>gson</artifactId>
+                       <version>${gson.version}</version>
                </dependency>
 
                <!-- Test dependencies -->
                <dependency>
                        <groupId>com.mikesamuel</groupId>
                        <artifactId>json-sanitizer</artifactId>
-                       <version>1.2.0</version>
+                       <version>1.2.3</version>
                </dependency>
 
                <!-- Common logging framework -->
                <dependency>
                        <groupId>ch.qos.logback</groupId>
                        <artifactId>logback-classic</artifactId>
-                       <version>${logback.version}</version><!--$NO-MVN-MAN-VER$ -->
+                       <version>${logback.version}</version>
+                       <!--$NO-MVN-MAN-VER$ -->
                </dependency>
                <dependency>
                        <groupId>ch.qos.logback</groupId>
                        <artifactId>logback-core</artifactId>
-                       <version>${logback.version}</version><!--$NO-MVN-MAN-VER$ -->
+                       <version>${logback.version}</version>
+                       <!--$NO-MVN-MAN-VER$ -->
                </dependency>
                <dependency>
                        <groupId>org.onap.sdc.sdc-distribution-client</groupId>
                <dependency>
                        <groupId>org.json</groupId>
                        <artifactId>json</artifactId>
-                       <version>20131018</version><!--$NO-MVN-MAN-VER$ -->
+                       <version>20131018</version>
+                       <!--$NO-MVN-MAN-VER$ -->
                </dependency>
                <dependency>
                        <groupId>org.eclipse.jetty</groupId>
                        <artifactId>commons-text</artifactId>
                        <version>${apache.commons-text.version}</version>
                </dependency>
-
-               <!-- Test dependencies -->
                <dependency>
-                       <groupId>junit</groupId>
-                       <artifactId>junit</artifactId>
-                       <scope>test</scope>
+                       <groupId>org.springframework.cloud</groupId>
+                       <artifactId>spring-cloud-starter-sleuth</artifactId>
                </dependency>
+               <dependency>
+                               <groupId>org.springframework.cloud</groupId>
+                               <artifactId>spring-cloud-sleuth-zipkin</artifactId>
+               </dependency>
+
+               <!-- Test dependencies -->
                <dependency>
                        <groupId>org.hamcrest</groupId>
                        <artifactId>hamcrest-all</artifactId>
                        <version>${hamcrest-all.version}</version>
                        <scope>test</scope>
                </dependency>
+               <dependency>
+                       <groupId>org.junit.jupiter</groupId>
+                       <artifactId>junit-jupiter</artifactId>
+                       <scope>test</scope>
+               </dependency>
+               <dependency>
+                       <groupId>org.junit.jupiter</groupId>
+                       <artifactId>junit-jupiter-api</artifactId>
+                       <scope>test</scope>
+               </dependency>
                <dependency>
                        <groupId>org.mockito</groupId>
                        <artifactId>mockito-core</artifactId>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-test</artifactId>
                        <scope>test</scope>
+                       <exclusions>
+                               <exclusion>
+                                       <groupId>com.vaadin.external.google</groupId>
+                                       <artifactId>android-json</artifactId>
+                               </exclusion>
+                       </exclusions>
+               </dependency>
+               <dependency>
+                       <groupId>org.springframework.cloud</groupId>
+                       <artifactId>spring-cloud-contract-wiremock</artifactId>
+                       <scope>test</scope>
                </dependency>
        </dependencies>
 
diff --git a/releases/1.13.5-container-release.yaml b/releases/1.13.5-container-release.yaml
new file mode 100644 (file)
index 0000000..0177137
--- /dev/null
@@ -0,0 +1,7 @@
+distribution_type: container
+container_release_tag: 1.13.5
+project: model-loader
+ref: ba282826d84f17e3156de99c39e6b1d50813f8ba
+containers:
+    - name: model-loader
+      version: 1.13-STAGING-20240326T082727Z
diff --git a/releases/1.13.5-maven-release.yaml b/releases/1.13.5-maven-release.yaml
new file mode 100644 (file)
index 0000000..71cc585
--- /dev/null
@@ -0,0 +1,4 @@
+distribution_type: maven
+log_dir: aai-model-loader-maven-stage-master/1396/
+project: model-loader
+version: 1.13.5
diff --git a/releases/1.13.6-container-release.yaml b/releases/1.13.6-container-release.yaml
new file mode 100644 (file)
index 0000000..873cd80
--- /dev/null
@@ -0,0 +1,7 @@
+distribution_type: container
+container_release_tag: 1.13.6
+project: model-loader
+ref: df2ad94ee9b641a4c2c19969816a6275f6d056e3
+containers:
+    - name: model-loader
+      version: 1.13-STAGING-20240417T124725Z
@@ -2,8 +2,7 @@
  * ============LICENSE_START=======================================================
  * org.onap.aai
  * ================================================================================
- * Copyright Â© 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Copyright Â© 2017-2018 European Software Marketing Ltd.
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-package org.onap.aai.modelloader;
+package org.onap.aai.modelloader.babel;
 
-import static org.junit.Assert.assertTrue;
+import org.onap.aai.modelloader.entity.ArtifactType;
 
-import org.junit.Test;
-
-/**
- * Tests for ModelLoaderApplication class.
- *
- */
-public class TestModelLoaderApplication {
-
-    static {
-        System.setProperty("CONFIG_HOME", "src/test/resources");
-    }
-
-    @Test
-    public void testServiceStarts() {
-        // The SDC Distribution Client is disabled.
-        ModelLoaderApplication.main(new String[0]);
-        assertTrue(true);
-    }
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
 
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class BabelArtifact {
+  String name;
+  public ArtifactType type;
+  String payload;
 }
diff --git a/src/main/java/org/onap/aai/modelloader/babel/BabelArtifactService.java b/src/main/java/org/onap/aai/modelloader/babel/BabelArtifactService.java
new file mode 100644 (file)
index 0000000..1221861
--- /dev/null
@@ -0,0 +1,100 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader.babel;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.onap.aai.babel.service.data.BabelArtifact;
+import org.onap.aai.babel.service.data.BabelRequest;
+import org.onap.aai.babel.service.data.BabelArtifact.ArtifactType;
+import org.onap.aai.cl.api.Logger;
+import org.onap.aai.cl.eelf.LoggerFactory;
+import org.onap.aai.modelloader.entity.Artifact;
+import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException;
+import org.onap.aai.modelloader.notification.BabelArtifactConverter;
+import org.onap.aai.modelloader.notification.ProcessToscaArtifactsException;
+import org.onap.aai.modelloader.restclient.BabelServiceClient;
+import org.onap.aai.modelloader.service.ModelLoaderMsgs;
+import org.springframework.stereotype.Service;
+
+@Service
+public class BabelArtifactService {
+
+  private static Logger logger = LoggerFactory.getInstance().getLogger(BabelArtifactService.class);
+
+  private final BabelServiceClient babelServiceClient;
+  private final BabelArtifactConverter babelArtifactConverter;
+
+  public BabelArtifactService(BabelServiceClient babelServiceClient, BabelArtifactConverter babelArtifactConverter) {
+    this.babelServiceClient = babelServiceClient;
+    this.babelArtifactConverter = babelArtifactConverter;
+  }
+
+  public void invokeBabelService(List<Artifact> modelArtifacts, List<Artifact> catalogArtifacts, BabelRequest babelRequest, String distributionId)
+          throws ProcessToscaArtifactsException {
+      try {
+          logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
+                  "Posting artifact: " + babelRequest.getArtifactName() + ", service version: " + babelRequest.getArtifactVersion()
+                          + ", artifact version: " + babelRequest.getArtifactVersion());
+  
+          List<BabelArtifact> babelArtifacts =
+                babelServiceClient.postArtifact(babelRequest, distributionId);
+  
+          // Sort Babel artifacts based on type
+          Map<ArtifactType, List<BabelArtifact>> artifactMap =
+                  babelArtifacts.stream().collect(Collectors.groupingBy(BabelArtifact::getType));
+  
+          if (artifactMap.containsKey(BabelArtifact.ArtifactType.MODEL)) {
+              modelArtifacts.addAll(
+                      babelArtifactConverter.convertToModel(artifactMap.get(BabelArtifact.ArtifactType.MODEL)));
+              artifactMap.remove(BabelArtifact.ArtifactType.MODEL);
+          }
+  
+          if (artifactMap.containsKey(BabelArtifact.ArtifactType.VNFCATALOG)) {
+              catalogArtifacts.addAll(babelArtifactConverter
+                      .convertToCatalog(artifactMap.get(BabelArtifact.ArtifactType.VNFCATALOG)));
+              artifactMap.remove(BabelArtifact.ArtifactType.VNFCATALOG);
+          }
+  
+          // Log unexpected artifact types
+          if (!artifactMap.isEmpty()) {
+              logger.warn(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR,
+                      babelRequest.getArtifactName() + " " + babelRequest.getArtifactVersion()
+                              + ". Unexpected artifact types returned by the babel service: "
+                              + artifactMap.keySet().toString());
+          }
+  
+      } catch (BabelArtifactParsingException e) {
+          logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR,
+                  "Error for artifact " + babelRequest.getArtifactName() + " " + babelRequest.getArtifactVersion() + " " + e);
+          throw new ProcessToscaArtifactsException(
+                  "An error occurred while trying to parse the Babel artifacts: " + e.getLocalizedMessage());
+      } catch (Exception e) {
+          logger.error(ModelLoaderMsgs.BABEL_REST_REQUEST_ERROR, e, "POST",
+                  "Error posting artifact " + babelRequest.getArtifactName() + " " + babelRequest.getArtifactVersion() + " to Babel: "
+                          + e.getLocalizedMessage());
+          throw new ProcessToscaArtifactsException(
+                  "An error occurred while calling the Babel service: " + e.getLocalizedMessage());
+      }
+  }
+  
+}
diff --git a/src/main/java/org/onap/aai/modelloader/config/BeanConfig.java b/src/main/java/org/onap/aai/modelloader/config/BeanConfig.java
new file mode 100644 (file)
index 0000000..cc6702b
--- /dev/null
@@ -0,0 +1,72 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader.config;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+
+import org.onap.aai.cl.api.Logger;
+import org.onap.aai.cl.eelf.LoggerFactory;
+import org.onap.aai.modelloader.service.ModelLoaderMsgs;
+import org.onap.sdc.api.IDistributionClient;
+import org.onap.sdc.impl.DistributionClientFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.client.RestTemplate;
+
+@Configuration
+public class BeanConfig {
+
+    private static final Logger logger = LoggerFactory.getInstance().getLogger(BeanConfig.class);
+
+
+    @Value("${CONFIG_HOME}")
+    private String configDir;
+
+    @Bean
+    public Properties configProperties() throws IOException {
+        // Load model loader system configuration
+        logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
+        InputStream configInputStream = Files.newInputStream(Paths.get(configDir, "model-loader.properties"));
+        Properties configProperties = new Properties();
+        configProperties.load(configInputStream);
+        return configProperties;
+    }
+
+    @Bean
+    public ModelLoaderConfig modelLoaderConfig(Properties configProperties) {
+        ModelLoaderConfig.setConfigHome(configDir);
+        return new ModelLoaderConfig(configProperties);
+    }
+    
+    @Bean
+    public IDistributionClient iDistributionClient() {
+        return DistributionClientFactory.createDistributionClient();
+    }
+
+    @Bean
+    public RestTemplate restTemplate() {
+        return new RestTemplate();
+    }
+}
diff --git a/src/main/java/org/onap/aai/modelloader/config/DistributionClientStartupConfig.java b/src/main/java/org/onap/aai/modelloader/config/DistributionClientStartupConfig.java
new file mode 100644 (file)
index 0000000..cd9d919
--- /dev/null
@@ -0,0 +1,88 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader.config;
+
+import java.util.Date;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import org.onap.aai.cl.api.Logger;
+import org.onap.aai.cl.eelf.LoggerFactory;
+import org.onap.aai.modelloader.notification.EventCallback;
+import org.onap.aai.modelloader.service.ModelLoaderMsgs;
+import org.onap.aai.modelloader.service.SdcConnectionJob;
+import org.onap.sdc.api.IDistributionClient;
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.utils.DistributionActionResultEnum;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.boot.context.event.ApplicationReadyEvent;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.event.EventListener;
+
+@Configuration
+@ConditionalOnProperty(value = "ml.distribution.connection.enabled", havingValue = "true", matchIfMissing = true)
+public class DistributionClientStartupConfig {
+
+    private static final Logger logger = LoggerFactory.getInstance().getLogger(DistributionClientStartupConfig.class);
+
+    private final IDistributionClient client;
+    private final ModelLoaderConfig config;
+    private final EventCallback eventCallback;
+
+    public DistributionClientStartupConfig(IDistributionClient client, ModelLoaderConfig config,
+            EventCallback eventCallback) {
+        this.client = client;
+        this.config = config;
+        this.eventCallback = eventCallback;
+    }
+
+    @EventListener(ApplicationReadyEvent.class)
+    protected void initSdcClient() {
+        // Initialize distribution client
+        logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
+        IDistributionClientResult initResult = null;
+        initResult = client.init(config, eventCallback);
+
+        if (initResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
+            // Start distribution client
+            logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
+            IDistributionClientResult startResult = client.start();
+            if (startResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
+                logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
+            } else {
+                String errorMsg = "Failed to start distribution client: " + startResult.getDistributionMessageResult();
+                logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
+
+                // Kick off a timer to retry the SDC connection
+                Timer timer = new Timer();
+                TimerTask task = new SdcConnectionJob(client, config, eventCallback, timer);
+                timer.schedule(task, new Date(), 60000);
+            }
+        } else {
+            String errorMsg = "Failed to initialize distribution client: " + initResult.getDistributionMessageResult();
+            logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
+
+            // Kick off a timer to retry the SDC connection
+            Timer timer = new Timer();
+            TimerTask task = new SdcConnectionJob(client, config, eventCallback, timer);
+            timer.schedule(task, new Date(), 60000);
+        }
+    }
+}
index 77693bc..6723e75 100644 (file)
@@ -27,12 +27,12 @@ import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Optional;
 import java.util.Properties;
+
 import org.apache.commons.lang3.StringUtils;
 import org.eclipse.jetty.util.security.Password;
 import org.onap.sdc.api.consumer.IConfiguration;
-import org.springframework.core.env.Environment;
-
 /**
  * Properties for the Model Loader
  *
@@ -77,6 +77,9 @@ public class ModelLoaderConfig implements IConfiguration {
     protected static final String PROP_ML_DISTRIBUTION_HTTP_PROXY_PORT = PREFIX_DISTRIBUTION_CLIENT + "HTTP_PROXY_PORT";
     protected static final String PROP_ML_DISTRIBUTION_HTTPS_PROXY_HOST = PREFIX_DISTRIBUTION_CLIENT + "HTTPS_PROXY_HOST";
     protected static final String PROP_ML_DISTRIBUTION_HTTPS_PROXY_PORT = PREFIX_DISTRIBUTION_CLIENT + "HTTPS_PROXY_PORT";
+    protected static final String PROP_ML_DISTRIBUTION_SASL_JAAS_CONFIG = PREFIX_DISTRIBUTION_CLIENT + "SASL_JAAS_CONFIG";
+    protected static final String PROP_ML_DISTRIBUTION_SASL_MECHANISM = PREFIX_DISTRIBUTION_CLIENT + "SASL_MECHANISM";
+    protected static final String PROP_ML_DISTRIBUTION_SECURITY_PROTOCOL = PREFIX_DISTRIBUTION_CLIENT + "SECURITY_PROTOCOL";
     protected static final String PROP_AAI_BASE_URL = PREFIX_AAI + "BASE_URL";
     protected static final String PROP_AAI_KEYSTORE_FILE = PREFIX_AAI + SUFFIX_KEYSTORE_FILE;
     protected static final String PROP_AAI_KEYSTORE_PASSWORD = PREFIX_AAI + SUFFIX_KEYSTORE_PASS;
@@ -97,6 +100,8 @@ public class ModelLoaderConfig implements IConfiguration {
     protected static final String PROP_DEBUG_INGEST_SIMULATOR = PREFIX_DEBUG + "INGEST_SIMULATOR";
     protected static final String FILESEP =
             (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
+    protected static final String PROP_AAI_CLIENT_CONNECT_TIMEOUT_MS = PREFIX_AAI + "RESTCLIENT_CONNECT_TIMEOUT";
+    protected static final String PROP_AAI_CLIENT_READ_TIMEOUT_MS = PREFIX_AAI + "RESTCLIENT_READ_TIMEOUT";
 
     private static String configHome;
     private Properties modelLoaderProperties = null;
@@ -401,4 +406,45 @@ public class ModelLoaderConfig implements IConfiguration {
         }
     }
 
+    public int getClientConnectTimeoutMs() {
+        String connectTimeout = Optional.ofNullable(get(PROP_AAI_CLIENT_CONNECT_TIMEOUT_MS)).orElse("120000");
+        return Integer.parseInt(connectTimeout);
+    }
+
+    public int getClientReadTimeoutMs() {
+        String connectTimeout = Optional.ofNullable(get(PROP_AAI_CLIENT_READ_TIMEOUT_MS)).orElse("120000");
+        return Integer.parseInt(connectTimeout);
+    }
+
+    @Override
+    public String getKafkaSaslJaasConfig() {
+        String saslJaasConfFromEnv = System.getenv("SASL_JAAS_CONFIG");
+        if(saslJaasConfFromEnv != null) {
+            return saslJaasConfFromEnv;
+        }
+        if(get(PROP_ML_DISTRIBUTION_SASL_JAAS_CONFIG) != null) {
+            return get(PROP_ML_DISTRIBUTION_SASL_JAAS_CONFIG);
+        }
+        return null;
+    }
+
+    @Override
+    public String getKafkaSaslMechanism() {
+        if(get(PROP_ML_DISTRIBUTION_SASL_MECHANISM) != null) {
+            return get(PROP_ML_DISTRIBUTION_SASL_MECHANISM);
+        }
+        return System.getenv().getOrDefault("SASL_MECHANISM", "SCRAM-SHA-512");
+    }
+
+    /**
+     * One of PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL
+     */
+    @Override
+    public String getKafkaSecurityProtocolConfig() {
+        if(get(PROP_ML_DISTRIBUTION_SECURITY_PROTOCOL) != null) {
+            return get(PROP_ML_DISTRIBUTION_SECURITY_PROTOCOL);
+        }
+        return System.getenv().getOrDefault("SECURITY_PROTOCOL", "SASL_PLAINTEXT");
+    }
+
 }
index c54d7b2..c1f6e9b 100644 (file)
@@ -44,6 +44,7 @@ import org.onap.aai.modelloader.entity.ArtifactHandler;
 import org.onap.aai.modelloader.restclient.AaiRestClient;\r
 import org.onap.aai.modelloader.service.ModelLoaderMsgs;\r
 import org.onap.aai.restclient.client.OperationResult;\r
+import org.springframework.stereotype.Component;\r
 import org.w3c.dom.Document;\r
 import org.w3c.dom.Element;\r
 import org.w3c.dom.Node;\r
@@ -53,6 +54,7 @@ import org.xml.sax.InputSource;
 /**\r
  * VNF Catalog specific handling\r
  */\r
+@Component\r
 public class VnfCatalogArtifactHandler extends ArtifactHandler {\r
 \r
     private static Logger logger = LoggerFactory.getInstance().getLogger(VnfCatalogArtifactHandler.class.getName());\r
index 626ca49..7aa2191 100644 (file)
@@ -28,7 +28,9 @@ import org.onap.aai.modelloader.entity.Artifact;
 import org.onap.aai.modelloader.entity.ArtifactHandler;
 import org.onap.aai.modelloader.restclient.AaiRestClient;
 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
+import org.springframework.stereotype.Service;
 
+@Service
 public class ModelArtifactHandler extends ArtifactHandler {
 
     private static Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifactHandler.class.getName());
index 0e27d57..64ecf8a 100644 (file)
 package org.onap.aai.modelloader.extraction;
 
 import java.io.IOException;
+import java.nio.charset.Charset;
 import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.List;
 import java.util.regex.Pattern;
+
 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
 import org.apache.commons.compress.archivers.zip.ZipFile;
 import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
@@ -36,6 +38,7 @@ import org.onap.aai.modelloader.entity.Artifact;
 import org.onap.aai.modelloader.entity.ArtifactType;
 import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifact;
 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
+import org.springframework.stereotype.Component;
 
 
 /**
@@ -45,6 +48,7 @@ import org.onap.aai.modelloader.service.ModelLoaderMsgs;
  * A .csar file is a compressed archive like a zip file and this class will treat the byte array as it if were a zip
  * file.
  */
+@Component
 public class VnfCatalogExtractor {
     private static final Logger logger = LoggerFactory.getInstance().getLogger(VnfCatalogExtractor.class.getName());
 
@@ -75,7 +79,7 @@ public class VnfCatalogExtractor {
                 ZipArchiveEntry entry = enumeration.nextElement();
                 if (fileShouldBeExtracted(entry)) {
                     vnfcFiles.add(new VnfCatalogArtifact(ArtifactType.VNF_CATALOG_XML,
-                            IOUtils.toString(zipFile.getInputStream(entry))));
+                            IOUtils.toString(zipFile.getInputStream(entry), Charset.defaultCharset())));
                 }
             }
         } catch (IOException e) {
index 58bb074..f0c96bd 100644 (file)
@@ -24,24 +24,18 @@ import java.time.ZonedDateTime;
 import java.time.format.DateTimeFormatter;
 import java.util.Base64;
 import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import org.onap.aai.babel.service.data.BabelArtifact;
-import org.onap.aai.babel.service.data.BabelArtifact.ArtifactType;
+import org.onap.aai.babel.service.data.BabelRequest;
 import org.onap.aai.cl.api.Logger;
 import org.onap.aai.cl.eelf.LoggerFactory;
 import org.onap.aai.cl.mdc.MdcContext;
 import org.onap.aai.cl.mdc.MdcOverride;
-import org.onap.aai.modelloader.config.ModelLoaderConfig;
+import org.onap.aai.modelloader.babel.BabelArtifactService;
 import org.onap.aai.modelloader.entity.Artifact;
 import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException;
 import org.onap.aai.modelloader.entity.model.IModelParser;
 import org.onap.aai.modelloader.entity.model.NamedQueryArtifactParser;
 import org.onap.aai.modelloader.extraction.InvalidArchiveException;
 import org.onap.aai.modelloader.extraction.VnfCatalogExtractor;
-import org.onap.aai.modelloader.restclient.BabelServiceClient;
-import org.onap.aai.modelloader.restclient.BabelServiceClientException;
-import org.onap.aai.modelloader.service.BabelServiceClientFactory;
 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
 import org.onap.sdc.api.IDistributionClient;
 import org.onap.sdc.api.notification.IArtifactInfo;
@@ -49,6 +43,7 @@ import org.onap.sdc.api.notification.INotificationData;
 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
 import org.onap.sdc.utils.ArtifactTypeEnum;
 import org.onap.sdc.utils.DistributionActionResultEnum;
+import org.springframework.stereotype.Component;
 
 /**
  * This class is responsible for downloading the artifacts from the ASDC.
@@ -60,22 +55,22 @@ import org.onap.sdc.utils.DistributionActionResultEnum;
  *
  * TOSCA_CSAR file artifacts will be converted into XML and returned as model artifacts.
  */
+@Component
 public class ArtifactDownloadManager {
 
     private static Logger logger = LoggerFactory.getInstance().getLogger(ArtifactDownloadManager.class);
 
-    private IDistributionClient client;
-    private NotificationPublisher notificationPublisher;
-    private BabelArtifactConverter babelArtifactConverter;
-    private ModelLoaderConfig config;
-    private BabelServiceClientFactory clientFactory;
-    private VnfCatalogExtractor vnfCatalogExtractor;
+    private final IDistributionClient client;
+    private final NotificationPublisher notificationPublisher;
+    private final VnfCatalogExtractor vnfCatalogExtractor;
+    private final BabelArtifactService babelArtifactService;
 
-    public ArtifactDownloadManager(IDistributionClient client, ModelLoaderConfig config,
-            BabelServiceClientFactory clientFactory) {
+    public ArtifactDownloadManager(IDistributionClient client,
+            NotificationPublisher notificationPublisher, VnfCatalogExtractor vnfCatalogExtractor, BabelArtifactService babelArtifactService) {
         this.client = client;
-        this.config = config;
-        this.clientFactory = clientFactory;
+        this.notificationPublisher = notificationPublisher;
+        this.vnfCatalogExtractor = vnfCatalogExtractor;
+        this.babelArtifactService = babelArtifactService;
     }
 
     /**
@@ -96,10 +91,10 @@ public class ArtifactDownloadManager {
                 IDistributionClientDownloadResult downloadResult = downloadIndividualArtifacts(data, artifact);
                 processDownloadedArtifacts(modelArtifacts, catalogArtifacts, artifact, downloadResult, data);
             } catch (DownloadFailureException e) {
-                getNotificationPublisher().publishDownloadFailure(client, data, artifact, e.getMessage());
+                notificationPublisher.publishDownloadFailure(client, data, artifact, e.getMessage());
                 success = false;
             } catch (Exception e) {
-                getNotificationPublisher().publishDeployFailure(client, data, artifact);
+                notificationPublisher.publishDeployFailure(client, data, artifact);
                 success = false;
             }
 
@@ -126,7 +121,7 @@ public class ArtifactDownloadManager {
 
         if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) {
             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Downloaded artifact: " + artifact.getArtifactName());
-            getNotificationPublisher().publishDownloadSuccess(client, data, artifact);
+            notificationPublisher.publishDownloadSuccess(client, data, artifact);
         } else {
             throw new DownloadFailureException(downloadResult.getDistributionMessageResult());
         }
@@ -153,10 +148,14 @@ public class ArtifactDownloadManager {
             IArtifactInfo artifactInfo, String distributionId, String serviceVersion)
             throws ProcessToscaArtifactsException, InvalidArchiveException {
         // Get translated artifacts from Babel Service
-        invokeBabelService(modelArtifacts, catalogArtifacts, payload, artifactInfo, distributionId, serviceVersion);
+        BabelRequest babelRequest = new BabelRequest();
+        babelRequest.setArtifactName(artifactInfo.getArtifactName());
+        babelRequest.setCsar(Base64.getEncoder().encodeToString(payload));
+        babelRequest.setArtifactVersion(serviceVersion);
+        babelArtifactService.invokeBabelService(modelArtifacts, catalogArtifacts, babelRequest, distributionId);
 
         // Get VNF Catalog artifacts directly from CSAR
-        List<Artifact> csarCatalogArtifacts = getVnfCatalogExtractor().extract(payload, artifactInfo.getArtifactName());
+        List<Artifact> csarCatalogArtifacts = vnfCatalogExtractor.extract(payload, artifactInfo.getArtifactName());
 
         // Throw an error if VNF Catalog data is present in the Babel payload and directly in the CSAR
         if (!catalogArtifacts.isEmpty() && !csarCatalogArtifacts.isEmpty()) {
@@ -168,75 +167,6 @@ public class ArtifactDownloadManager {
         }
     }
 
-    public void invokeBabelService(List<Artifact> modelArtifacts, List<Artifact> catalogArtifacts, byte[] payload,
-            IArtifactInfo artifactInfo, String distributionId, String serviceVersion)
-            throws ProcessToscaArtifactsException {
-        try {
-            BabelServiceClient babelClient = createBabelServiceClient(artifactInfo, serviceVersion);
-
-            logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
-                    "Posting artifact: " + artifactInfo.getArtifactName() + ", service version: " + serviceVersion
-                            + ", artifact version: " + artifactInfo.getArtifactVersion());
-
-            List<BabelArtifact> babelArtifacts =
-                    babelClient.postArtifact(payload, artifactInfo.getArtifactName(), serviceVersion, distributionId);
-
-            // Sort Babel artifacts based on type
-            Map<ArtifactType, List<BabelArtifact>> artifactMap =
-                    babelArtifacts.stream().collect(Collectors.groupingBy(BabelArtifact::getType));
-
-            if (artifactMap.containsKey(BabelArtifact.ArtifactType.MODEL)) {
-                modelArtifacts.addAll(
-                        getBabelArtifactConverter().convertToModel(artifactMap.get(BabelArtifact.ArtifactType.MODEL)));
-                artifactMap.remove(BabelArtifact.ArtifactType.MODEL);
-            }
-
-            if (artifactMap.containsKey(BabelArtifact.ArtifactType.VNFCATALOG)) {
-                catalogArtifacts.addAll(getBabelArtifactConverter()
-                        .convertToCatalog(artifactMap.get(BabelArtifact.ArtifactType.VNFCATALOG)));
-                artifactMap.remove(BabelArtifact.ArtifactType.VNFCATALOG);
-            }
-
-            // Log unexpected artifact types
-            if (!artifactMap.isEmpty()) {
-                logger.warn(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR,
-                        artifactInfo.getArtifactName() + " " + serviceVersion
-                                + ". Unexpected artifact types returned by the babel service: "
-                                + artifactMap.keySet().toString());
-            }
-
-        } catch (BabelArtifactParsingException e) {
-            logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR,
-                    "Error for artifact " + artifactInfo.getArtifactName() + " " + serviceVersion + e);
-            throw new ProcessToscaArtifactsException(
-                    "An error occurred while trying to parse the Babel artifacts: " + e.getLocalizedMessage());
-        } catch (Exception e) {
-            logger.error(ModelLoaderMsgs.BABEL_REST_REQUEST_ERROR, e, "POST", config.getBabelBaseUrl(),
-                    "Error posting artifact " + artifactInfo.getArtifactName() + " " + serviceVersion + " to Babel: "
-                            + e.getLocalizedMessage());
-            throw new ProcessToscaArtifactsException(
-                    "An error occurred while calling the Babel service: " + e.getLocalizedMessage());
-        }
-    }
-
-    BabelServiceClient createBabelServiceClient(IArtifactInfo artifact, String serviceVersion)
-            throws ProcessToscaArtifactsException {
-        BabelServiceClient babelClient;
-        try {
-            logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel client");
-            babelClient = clientFactory.create(config);
-        } catch (BabelServiceClientException e) {
-            logger.error(ModelLoaderMsgs.BABEL_REST_REQUEST_ERROR, e, "POST", config.getBabelBaseUrl(),
-                    "Error posting artifact " + artifact.getArtifactName() + " " + serviceVersion + " to Babel: "
-                            + e.getLocalizedMessage());
-            throw new ProcessToscaArtifactsException(
-                    "An error occurred tyring to convert the tosca artifacts to xml artifacts: "
-                            + e.getLocalizedMessage());
-        }
-
-        return babelClient;
-    }
-
     private void processModelQuerySpecArtifact(List<Artifact> modelArtifacts,
             IDistributionClientDownloadResult downloadResult) throws BabelArtifactParsingException {
         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Processing named query artifact.");
@@ -257,28 +187,4 @@ public class ArtifactDownloadManager {
     private boolean parsedArtifactsExist(List<Artifact> parsedArtifacts) {
         return parsedArtifacts != null && !parsedArtifacts.isEmpty();
     }
-
-    private NotificationPublisher getNotificationPublisher() {
-        if (notificationPublisher == null) {
-            notificationPublisher = new NotificationPublisher();
-        }
-
-        return notificationPublisher;
-    }
-
-    private BabelArtifactConverter getBabelArtifactConverter() {
-        if (babelArtifactConverter == null) {
-            babelArtifactConverter = new BabelArtifactConverter();
-        }
-
-        return babelArtifactConverter;
-    }
-
-    private VnfCatalogExtractor getVnfCatalogExtractor() {
-        if (vnfCatalogExtractor == null) {
-            vnfCatalogExtractor = new VnfCatalogExtractor();
-        }
-
-        return vnfCatalogExtractor;
-    }
 }
index ad4eb7d..5118652 100644 (file)
@@ -29,12 +29,14 @@ import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifact;
 import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException;
 import org.onap.aai.modelloader.entity.model.ModelArtifact;
 import org.onap.aai.modelloader.entity.model.ModelArtifactParser;
+import org.springframework.stereotype.Component;
 
 /**
  * This class is responsible for converting TOSCA artifacts into instances of {@link ModelArtifact} ready for pushing
  * the converted artifacts .
  */
-class BabelArtifactConverter {
+@Component
+public class BabelArtifactConverter {
 
     /**
      * This method converts BabelArtifacts into instances of {@link ModelArtifact}.
@@ -44,7 +46,7 @@ class BabelArtifactConverter {
      * @throws BabelArtifactParsingException if an error occurs trying to parse the generated XML files that were
      *         converted from tosca artifacts
      */
-    List<Artifact> convertToModel(List<BabelArtifact> xmlArtifacts) throws BabelArtifactParsingException {
+    public List<Artifact> convertToModel(List<BabelArtifact> xmlArtifacts) throws BabelArtifactParsingException {
         Objects.requireNonNull(xmlArtifacts);
         List<Artifact> modelArtifacts = new ArrayList<>();
         ModelArtifactParser modelArtParser = new ModelArtifactParser();
@@ -70,7 +72,7 @@ class BabelArtifactConverter {
      * @param xmlArtifacts xml artifacts to be parsed
      * @return List<org.openecomp.modelloader.entity.Artifact> list of converted catalog artifacts
      */
-    List<Artifact> convertToCatalog(List<BabelArtifact> xmlArtifacts) {
+    public List<Artifact> convertToCatalog(List<BabelArtifact> xmlArtifacts) {
         Objects.requireNonNull(xmlArtifacts);
         List<Artifact> catalogArtifacts = new ArrayList<>();
 
index d7bccba..754eaff 100644 (file)
@@ -26,33 +26,32 @@ import java.util.List;
 import org.onap.aai.cl.api.Logger;
 import org.onap.aai.cl.eelf.LoggerFactory;
 import org.onap.aai.cl.mdc.MdcContext;
-import org.onap.aai.modelloader.config.ModelLoaderConfig;
 import org.onap.aai.modelloader.entity.Artifact;
 import org.onap.aai.modelloader.extraction.ArtifactInfoExtractor;
 import org.onap.aai.modelloader.service.ArtifactDeploymentManager;
-import org.onap.aai.modelloader.service.BabelServiceClientFactory;
 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
 import org.onap.sdc.api.IDistributionClient;
 import org.onap.sdc.api.consumer.INotificationCallback;
 import org.onap.sdc.api.notification.IArtifactInfo;
 import org.onap.sdc.api.notification.INotificationData;
 import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
 
+@Component
 public class EventCallback implements INotificationCallback {
     private static Logger logger = LoggerFactory.getInstance().getLogger(EventCallback.class.getName());
     private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(EventCallback.class.getName());
 
-    private ArtifactDeploymentManager artifactDeploymentManager;
-    private ArtifactDownloadManager artifactDownloadManager;
-    private NotificationPublisher notificationPublisher;
-    private IDistributionClient client;
-    private ModelLoaderConfig config;
-    private BabelServiceClientFactory babelServiceClientFactory;
+    private final ArtifactDeploymentManager artifactDeploymentManager;
+    private final ArtifactDownloadManager artifactDownloadManager;
+    private final NotificationPublisher notificationPublisher;
+    private final IDistributionClient client;
 
-    public EventCallback(IDistributionClient client, ModelLoaderConfig config, BabelServiceClientFactory babelServiceClientFactory) {
+    public EventCallback(IDistributionClient client, ArtifactDeploymentManager artifactDeploymentManager, ArtifactDownloadManager artifactDownloadManager, NotificationPublisher notificationPublisher) {
+        this.artifactDeploymentManager = artifactDeploymentManager;
+        this.artifactDownloadManager = artifactDownloadManager;
+        this.notificationPublisher = notificationPublisher;
         this.client = client;
-        this.config = config;
-        this.babelServiceClientFactory = babelServiceClientFactory;
     }
 
     @Override
@@ -65,10 +64,10 @@ public class EventCallback implements INotificationCallback {
         List<Artifact> modelArtifacts = new ArrayList<>();
 
         boolean success =
-                getArtifactDownloadManager().downloadArtifacts(data, artifacts, modelArtifacts, catalogArtifacts);
+                artifactDownloadManager.downloadArtifacts(data, artifacts, modelArtifacts, catalogArtifacts);
 
         if (success) {
-            success = getArtifactDeploymentManager().deploy(data, modelArtifacts, catalogArtifacts);
+            success = artifactDeploymentManager.deploy(data, modelArtifacts, catalogArtifacts);
         }
 
         String statusString = success ? "SUCCESS" : "FAILURE";
@@ -85,37 +84,12 @@ public class EventCallback implements INotificationCallback {
             boolean deploymentSuccess) {
         if (deploymentSuccess) {
             artifacts.stream().filter(a -> filterType.equalsIgnoreCase(a.getArtifactType()))
-                    .forEach(a -> getNotificationPublisher().publishDeploySuccess(client, data, a));
-            getNotificationPublisher().publishComponentSuccess(client, data);
+                    .forEach(a -> notificationPublisher.publishDeploySuccess(client, data, a));
+            notificationPublisher.publishComponentSuccess(client, data);
         } else {
             artifacts.stream().filter(a -> filterType.equalsIgnoreCase(a.getArtifactType()))
-                    .forEach(a -> getNotificationPublisher().publishDeployFailure(client, data, a));
-            getNotificationPublisher().publishComponentFailure(client, data, "deploy failure");
+                    .forEach(a -> notificationPublisher.publishDeployFailure(client, data, a));
+            notificationPublisher.publishComponentFailure(client, data, "deploy failure");
         }
     }
-
-    private ArtifactDeploymentManager getArtifactDeploymentManager() {
-        if (artifactDeploymentManager == null) {
-            artifactDeploymentManager = new ArtifactDeploymentManager(config);
-        }
-
-        return artifactDeploymentManager;
-    }
-
-    private ArtifactDownloadManager getArtifactDownloadManager() {
-        if (artifactDownloadManager == null) {
-            artifactDownloadManager = new ArtifactDownloadManager(client, config, babelServiceClientFactory);
-        }
-
-        return artifactDownloadManager;
-    }
-
-
-    private NotificationPublisher getNotificationPublisher() {
-        if (notificationPublisher == null) {
-            notificationPublisher = new NotificationPublisher();
-        }
-
-        return notificationPublisher;
-    }
 }
index 566415e..3eb07f3 100644 (file)
  */
 package org.onap.aai.modelloader.notification;
 
-import java.util.Collections;
 import java.util.List;
 import org.onap.sdc.api.notification.IArtifactInfo;
 import org.onap.sdc.api.notification.INotificationData;
 import org.onap.sdc.api.notification.IResourceInstance;
 
+import lombok.Data;
+
+@Data
 public class NotificationDataImpl implements INotificationData {
 
     private String distributionID;
+    private String serviceName;
+    private String serviceVersion;
+    private String serviceUUID;
+    private String serviceDescription;
+    private List<IResourceInstance> resources;
+    private List<IArtifactInfo> serviceArtifacts;
+    private String serviceInvariantUUID;
+    private String workloadContext;
 
     @Override
-    public IArtifactInfo getArtifactMetadataByUUID(String arg0) {
-        return null;
-    }
-
-    @Override
-    public String getDistributionID() {
-        return distributionID;
-    }
-
-    public void setDistributionID(String distributionID) {
-        this.distributionID = distributionID;
-    }
-
-    @Override
-    public List<IResourceInstance> getResources() {
-        return Collections.emptyList();
-    }
-
-    @Override
-    public List<IArtifactInfo> getServiceArtifacts() {
-        return Collections.emptyList();
-    }
-
-    @Override
-    public String getServiceDescription() {
-        return null;
-    }
-
-    @Override
-    public String getServiceInvariantUUID() {
-        return null;
-    }
-
-    @Override
-    public String getServiceName() {
-        return null;
-    }
-
-    @Override
-    public String getServiceUUID() {
-        return null;
-    }
-
-    @Override
-    public String getServiceVersion() {
+    public IArtifactInfo getArtifactMetadataByUUID(String uuid) {
         return null;
     }
-
-    @Override
-    public String getWorkloadContext() {
-        return null;
-    }
-
-    @Override
-    public void setWorkloadContext(String arg0) {
-        // Unsupported method - not expected to be called
-    }
-
-    @Override
-    public int hashCode() {
-        final int prime = 31;
-        int result = 1;
-        result = prime * result + ((distributionID == null) ? 0 : distributionID.hashCode());
-        return result;
-    }
-
-    @Override
-    public boolean equals(Object obj) {
-        if (this == obj)
-            return true;
-        if (obj == null)
-            return false;
-        if (getClass() != obj.getClass())
-            return false;
-        NotificationDataImpl other = (NotificationDataImpl) obj;
-        if (distributionID == null) {
-            if (other.distributionID != null)
-                return false;
-        } else if (!distributionID.equals(other.distributionID))
-            return false;
-        return true;
-    }
-
 }
index 6e6ff13..7d5b1cc 100644 (file)
@@ -38,10 +38,12 @@ import org.onap.sdc.api.notification.INotificationData;
 import org.onap.sdc.api.results.IDistributionClientResult;
 import org.onap.sdc.utils.DistributionActionResultEnum;
 import org.onap.sdc.utils.DistributionStatusEnum;
+import org.springframework.stereotype.Component;
 
 /**
  * This class is responsible for publishing the status of actions performed working with artifacts.
  */
+@Component
 public class NotificationPublisher {
 
     private static Logger logger = LoggerFactory.getInstance().getLogger(NotificationPublisher.class);
index 29c0c70..45f84d6 100644 (file)
@@ -42,6 +42,7 @@ import org.onap.aai.modelloader.service.ModelLoaderMsgs;
 import org.onap.aai.restclient.client.OperationResult;
 import org.onap.aai.restclient.client.RestClient;
 import org.onap.aai.restclient.enums.RestAuthenticationMode;
+import org.springframework.stereotype.Component;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
@@ -52,6 +53,7 @@ import org.xml.sax.SAXException;
  * Wrapper around the standard A&AI Rest Client interface. This currently uses Jersey client 1.x
  *
  */
+@Component
 public class AaiRestClient {
 
     public static final String HEADER_TRANS_ID = "X-TransactionId";
@@ -156,24 +158,19 @@ public class AaiRestClient {
 
     private RestClient setupClient() {
         RestClient restClient = new RestClient();
+        restClient.validateServerHostname(false)
+                .validateServerCertChain(false)
+                .connectTimeoutMs(config.getClientConnectTimeoutMs())
+                .readTimeoutMs(config.getClientReadTimeoutMs());
 
         //Use certs only if SSL is enabled
         if (config.useHttpsWithAAI())
         {// @formatter:off
-            restClient.validateServerHostname(false)
-                    .validateServerCertChain(false)
-                    .clientCertFile(config.getAaiKeyStorePath())
-                    .clientCertPassword(config.getAaiKeyStorePassword())
-                    .connectTimeoutMs(120000)
-                    .readTimeoutMs(120000);
+            restClient
+                .clientCertFile(config.getAaiKeyStorePath())
+                .clientCertPassword(config.getAaiKeyStorePassword());
             // @formatter:on
         }
-        else {
-            restClient.validateServerHostname(false)
-                    .validateServerCertChain(false)
-                    .connectTimeoutMs(120000)
-                    .readTimeoutMs(120000);
-        }
 
         if (useBasicAuth()) {
             restClient.authenticationMode(RestAuthenticationMode.SSL_BASIC);
index f69752b..8328c42 100644 (file)
@@ -23,10 +23,10 @@ package org.onap.aai.modelloader.restclient;
 
 import java.util.List;
 import org.onap.aai.babel.service.data.BabelArtifact;
+import org.onap.aai.babel.service.data.BabelRequest;
 
 public interface BabelServiceClient {
 
-    List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
-            String transactionId) throws BabelServiceClientException;
+    List<BabelArtifact> postArtifact(BabelRequest babelRequest, String transactionId) throws BabelServiceClientException;
 
 }
diff --git a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java
new file mode 100644 (file)
index 0000000..53ce917
--- /dev/null
@@ -0,0 +1,85 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright Â© 2017-2019 European Software Marketing Ltd.
+ * ================================================================================
+ * 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.onap.aai.modelloader.restclient;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import org.onap.aai.babel.service.data.BabelArtifact;
+import org.onap.aai.babel.service.data.BabelRequest;
+import org.onap.aai.babel.service.data.BabelArtifact.ArtifactType;
+import org.onap.aai.cl.api.Logger;
+import org.onap.aai.cl.eelf.LoggerFactory;
+import org.onap.aai.modelloader.config.ModelLoaderConfig;
+import org.onap.aai.modelloader.service.ModelLoaderMsgs;
+import org.springframework.core.ParameterizedTypeReference;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
+
+/**
+ * HTTPS Client for interfacing with Babel.
+ *
+ */
+@Component
+public class BabelServiceClientImpl implements BabelServiceClient {
+
+    private static final Logger logger = LoggerFactory.getInstance().getLogger(BabelServiceClientImpl.class);
+    private final ModelLoaderConfig config;
+    private final RestTemplate restTemplate;
+
+    public BabelServiceClientImpl(ModelLoaderConfig config, RestTemplate restTemplate) {
+        this.config = config;
+        this.restTemplate = restTemplate;
+    }
+
+    @Override
+    public List<BabelArtifact> postArtifact(BabelRequest babelRequest, String transactionId) throws BabelServiceClientException {
+        if (logger.isInfoEnabled()) {
+            logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + babelRequest.getArtifactName()
+                    + " Artifact version: " + babelRequest.getArtifactVersion() + " Artifact payload: " + babelRequest.getCsar());
+        }
+
+        String resourceUrl = config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl();
+
+        HttpHeaders headers = new HttpHeaders();
+        headers.set(AaiRestClient.HEADER_TRANS_ID, transactionId);
+        headers.set(AaiRestClient.HEADER_FROM_APP_ID, AaiRestClient.ML_APP_NAME);
+        HttpEntity<BabelRequest> entity = new HttpEntity<>(babelRequest, headers);
+
+        ResponseEntity<List<BabelArtifact>> artifactResponse = restTemplate.exchange(resourceUrl, HttpMethod.POST, entity, new ParameterizedTypeReference<List<BabelArtifact>>() {});
+
+        if (logger.isDebugEnabled()) {
+            logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
+                    "Babel response " + artifactResponse.getStatusCode() + " " + artifactResponse.getBody().toString());
+        }
+
+        if (!artifactResponse.getStatusCode().equals(HttpStatus.OK)) {
+            throw new BabelServiceClientException(artifactResponse.getBody().toString());
+        }
+
+        return artifactResponse.getBody();
+    }
+}
diff --git a/src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java b/src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java
deleted file mode 100644 (file)
index 289015c..0000000
+++ /dev/null
@@ -1,254 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright Â© 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Copyright Â© 2017-2019 European Software Marketing Ltd.
- * ================================================================================
- * 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.onap.aai.modelloader.restclient;
-
-import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
-import com.google.json.JsonSanitizer;
-import com.sun.jersey.api.client.Client; // NOSONAR
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.time.ZonedDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.Base64;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.X509TrustManager;
-import javax.ws.rs.core.Response;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.onap.aai.babel.service.data.BabelArtifact;
-import org.onap.aai.cl.api.LogFields;
-import org.onap.aai.cl.api.LogLine;
-import org.onap.aai.cl.api.Logger;
-import org.onap.aai.cl.eelf.LoggerFactory;
-import org.onap.aai.cl.mdc.MdcContext;
-import org.onap.aai.cl.mdc.MdcOverride;
-import org.onap.aai.modelloader.config.ModelLoaderConfig;
-import org.onap.aai.modelloader.service.ModelLoaderMsgs;
-
-/**
- * HTTPS Client for interfacing with Babel.
- *
- */
-public class HttpsBabelServiceClient implements BabelServiceClient {
-
-    private static final Logger logger = LoggerFactory.getInstance().getLogger(HttpsBabelServiceClient.class);
-    private static final Logger metricsLogger =
-            LoggerFactory.getInstance().getMetricsLogger(HttpsBabelServiceClient.class);
-    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
-
-    private static final String SSL_PROTOCOL = "TLS";
-    private static final String KEYSTORE_ALGORITHM = "SunX509";
-    private static final String KEYSTORE_TYPE = "PKCS12";
-
-    private final ModelLoaderConfig config;
-    private final Client client;
-
-    /**
-     * @param config
-     * @throws NoSuchAlgorithmException
-     * @throws KeyStoreException
-     * @throws CertificateException
-     * @throws IOException
-     * @throws UnrecoverableKeyException
-     * @throws KeyManagementException
-     * @throws BabelServiceClientException
-     */
-    public HttpsBabelServiceClient(ModelLoaderConfig config)
-            throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
-            UnrecoverableKeyException, KeyManagementException, BabelServiceClientException {
-        this.config = config;
-
-        logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel Service client");
-        //Initialize SSL Context only if SSL is enabled
-        if (config.useHttpsWithBabel()) {
-            SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
-            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
-            KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
-
-            String clientCertPassword = config.getBabelKeyStorePassword();
-
-            char[] pwd = null;
-            if (clientCertPassword != null) {
-                pwd = clientCertPassword.toCharArray();
-            }
-
-            TrustManager[] trustManagers = getTrustManagers();
-
-            String clientCertFileName = config.getBabelKeyStorePath();
-            if (clientCertFileName == null) {
-                ctx.init(null, trustManagers, null);
-            } else {
-                InputStream fin = Files.newInputStream(Paths.get(clientCertFileName));
-                keyStore.load(fin, pwd);
-                kmf.init(keyStore, pwd);
-                ctx.init(kmf.getKeyManagers(), trustManagers, null);
-            }
-
-            logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context");
-
-            HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
-            HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);
-        }
-
-        client = Client.create(new DefaultClientConfig());
-
-        logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created");
-    }
-
-    private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
-            IOException, BabelServiceClientException {
-        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
-        // Using null here initializes the TMF with the default trust store.
-        tmf.init((KeyStore) null);
-
-        // Create a new Trust Manager from the local trust store.
-        String trustStoreFile = config.getBabelTrustStorePath();
-        if (trustStoreFile == null) {
-            throw new BabelServiceClientException("No Babel trust store defined");
-        }
-        try (InputStream myKeys = Files.newInputStream(Paths.get(trustStoreFile))) {
-            KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
-            myTrustStore.load(myKeys, config.getBabelTrustStorePassword().toCharArray());
-            tmf.init(myTrustStore);
-        }
-        X509TrustManager localTm = findX509TrustManager(tmf);
-
-        // Create a custom trust manager that wraps both our trust store and the default.
-        final X509TrustManager finalLocalTm = localTm;
-
-        // Find the default trust manager.
-        final X509TrustManager defaultTrustManager = findX509TrustManager(tmf);
-
-        return new TrustManager[] {new X509TrustManager() {
-            @Override
-            public X509Certificate[] getAcceptedIssuers() {
-                return defaultTrustManager.getAcceptedIssuers();
-            }
-
-            @Override
-            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
-                try {
-                    finalLocalTm.checkServerTrusted(chain, authType);
-                } catch (CertificateException e) { // NOSONAR
-                    defaultTrustManager.checkServerTrusted(chain, authType);
-                }
-            }
-
-            @Override
-            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
-                defaultTrustManager.checkClientTrusted(chain, authType);
-            }
-        }};
-    }
-
-    private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
-        X509TrustManager trustManager = null;
-        for (TrustManager tm : tmf.getTrustManagers()) {
-            if (tm instanceof X509TrustManager) {
-                trustManager = (X509TrustManager) tm;
-                break;
-            }
-        }
-        return trustManager;
-    }
-
-    /**
-     * @param artifactPayload
-     * @param artifactName
-     * @param artifactVersion
-     * @param transactionId
-     * @return
-     * @throws BabelServiceClientException
-     * @throws JSONException
-     */
-    @Override
-    public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
-            String transactionId) throws BabelServiceClientException {
-        Objects.requireNonNull(artifactPayload);
-
-        String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
-
-        JSONObject obj = new JSONObject();
-        try {
-            obj.put("csar", encodedPayload);
-            obj.put("artifactVersion", artifactVersion);
-            obj.put("artifactName", artifactName);
-        } catch (JSONException ex) {
-            throw new BabelServiceClientException(ex);
-        }
-
-        if (logger.isInfoEnabled()) {
-            logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
-                    + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
-        }
-
-        MdcOverride override = new MdcOverride();
-        override.addAttribute(MdcContext.MDC_START_TIME, ZonedDateTime.now().format(formatter));
-
-        WebResource webResource = client.resource(config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl());
-        ClientResponse response = webResource.type("application/json")
-                .header(AaiRestClient.HEADER_TRANS_ID, Collections.singletonList(transactionId))
-                .header(AaiRestClient.HEADER_FROM_APP_ID, Collections.singletonList(AaiRestClient.ML_APP_NAME))
-                .post(ClientResponse.class, obj.toString());
-        String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class));
-
-        if (logger.isDebugEnabled()) {
-            logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
-                    "Babel response " + response.getStatus() + " " + sanitizedJson);
-        }
-
-        metricsLogger.info(ModelLoaderMsgs.BABEL_REST_REQUEST, new LogFields() //
-                .setField(LogLine.DefinedFields.TARGET_ENTITY, "Babel")
-                .setField(LogLine.DefinedFields.STATUS_CODE,
-                        Response.Status.fromStatusCode(response.getStatus()).getFamily()
-                                .equals(Response.Status.Family.SUCCESSFUL) ? "COMPLETE" : "ERROR")
-                .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
-                .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusInfo().toString()), //
-                override, response.toString());
-
-        if (response.getStatus() != Response.Status.OK.getStatusCode()) {
-            throw new BabelServiceClientException(sanitizedJson);
-        }
-
-        return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());
-    }
-}
index af006f5..9f09703 100644 (file)
@@ -28,18 +28,22 @@ import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifactHandler;
 import org.onap.aai.modelloader.entity.model.ModelArtifactHandler;
 import org.onap.aai.modelloader.restclient.AaiRestClient;
 import org.onap.sdc.api.notification.INotificationData;
+import org.springframework.stereotype.Component;
 
 /**
  * This class is responsible for deploying model and catalog artifacts.
  */
+@Component
 public class ArtifactDeploymentManager {
 
-    private ModelLoaderConfig config;
-    private ModelArtifactHandler modelArtifactHandler;
-    private VnfCatalogArtifactHandler vnfCatalogArtifactHandler;
+    private final ModelLoaderConfig config;
+    private final ModelArtifactHandler modelArtifactHandler;
+    private final VnfCatalogArtifactHandler vnfCatalogArtifactHandler;
 
-    public ArtifactDeploymentManager(ModelLoaderConfig config) {
+    public ArtifactDeploymentManager(ModelLoaderConfig config, ModelArtifactHandler modelArtifactHandler, VnfCatalogArtifactHandler vnfCatalogArtifactHandler) {
         this.config = config;
+        this.modelArtifactHandler = modelArtifactHandler;
+        this.vnfCatalogArtifactHandler = vnfCatalogArtifactHandler;
     }
 
     /**
@@ -59,36 +63,20 @@ public class ArtifactDeploymentManager {
 
         List<Artifact> completedArtifacts = new ArrayList<>();
         boolean deploySuccess =
-                getModelArtifactHandler().pushArtifacts(modelArtifacts, distributionId, completedArtifacts, aaiClient);
+                modelArtifactHandler.pushArtifacts(modelArtifacts, distributionId, completedArtifacts, aaiClient);
 
         if (!deploySuccess) {
-            getModelArtifactHandler().rollback(completedArtifacts, distributionId, aaiClient);
+            modelArtifactHandler.rollback(completedArtifacts, distributionId, aaiClient);
         } else {
             List<Artifact> completedImageData = new ArrayList<>();
-            deploySuccess = getVnfCatalogArtifactHandler().pushArtifacts(catalogArtifacts, distributionId,
+            deploySuccess = vnfCatalogArtifactHandler.pushArtifacts(catalogArtifacts, distributionId,
                     completedImageData, aaiClient);
             if (!deploySuccess) {
-                getModelArtifactHandler().rollback(completedArtifacts, distributionId, aaiClient);
-                getVnfCatalogArtifactHandler().rollback(completedImageData, distributionId, aaiClient);
+                modelArtifactHandler.rollback(completedArtifacts, distributionId, aaiClient);
+                vnfCatalogArtifactHandler.rollback(completedImageData, distributionId, aaiClient);
             }
         }
 
         return deploySuccess;
     }
-
-    private ModelArtifactHandler getModelArtifactHandler() {
-        if (modelArtifactHandler == null) {
-            modelArtifactHandler = new ModelArtifactHandler(config);
-        }
-
-        return modelArtifactHandler;
-    }
-
-    private VnfCatalogArtifactHandler getVnfCatalogArtifactHandler() {
-        if (vnfCatalogArtifactHandler == null) {
-            this.vnfCatalogArtifactHandler = new VnfCatalogArtifactHandler(config);
-        }
-
-        return vnfCatalogArtifactHandler;
-    }
 }
index 9af92be..f83e44d 100644 (file)
  */
 package org.onap.aai.modelloader.service;
 
-import java.util.Collections;
 import java.util.List;
 import org.onap.sdc.api.notification.IArtifactInfo;
 
+import lombok.Data;
+
 /**
  * This class is an implementation of IArtifactInfo for test purposes.
  */
+@Data
 public class ArtifactInfoImpl implements IArtifactInfo {
 
     private String artifactName;
     private String artifactType;
     private String artifactDescription;
     private String artifactVersion;
-
-    @Override
-    public String getArtifactName() {
-        return artifactName;
-    }
-
-    public void setArtifactName(String artifactName) {
-        this.artifactName = artifactName;
-    }
-
-    @Override
-    public String getArtifactType() {
-        return artifactType;
-    }
-
-    public void setArtifactType(String artifactType) {
-        this.artifactType = artifactType;
-    }
-
-    @Override
-    public String getArtifactURL() {
-        return null;
-    }
-
-    @Override
-    public String getArtifactChecksum() {
-        return null;
-    }
-
-    @Override
-    public String getArtifactDescription() {
-        return artifactDescription;
-    }
-
-    public void setArtifactDescription(String artifactDescription) {
-        this.artifactDescription = artifactDescription;
-    }
-
-    @Override
-    public Integer getArtifactTimeout() {
-        return null;
-    }
-
-    @Override
-    public String getArtifactVersion() {
-        return artifactVersion;
-    }
-
-    public void setArtifactVersion(String artifactVersion) {
-        this.artifactVersion = artifactVersion;
-    }
-
-    @Override
-    public String getArtifactUUID() {
-        return null;
-    }
-
-    @Override
-    public IArtifactInfo getGeneratedArtifact() {
-        return null;
-    }
-
-    @Override
-    public List<IArtifactInfo> getRelatedArtifacts() {
-        return Collections.emptyList();
-    }
-
-    @Override
-    public boolean equals(Object o) {
-        if (this == o) {
-            return true;
-        }
-        if (o == null || getClass() != o.getClass()) {
-            return false;
-        }
-
-        ArtifactInfoImpl that = (ArtifactInfoImpl) o;
-
-        if (artifactName != null ? !artifactName.equals(that.artifactName) : that.artifactName != null) {
-            return false;
-        }
-        if (artifactType != null ? !artifactType.equals(that.artifactType) : that.artifactType != null) {
-            return false;
-        }
-        if (artifactDescription != null ? !artifactDescription.equals(that.artifactDescription)
-                : that.artifactDescription != null) {
-            return false;
-        }
-        return artifactVersion != null ? artifactVersion.equals(that.artifactVersion) : that.artifactVersion == null;
-    }
-
-    @Override
-    public int hashCode() {
-        int result = artifactName != null ? artifactName.hashCode() : 0;
-        result = 31 * result + (artifactType != null ? artifactType.hashCode() : 0);
-        result = 31 * result + (artifactDescription != null ? artifactDescription.hashCode() : 0);
-        result = 31 * result + (artifactVersion != null ? artifactVersion.hashCode() : 0);
-        return result;
-    }
+    private String artifactURL;
+    private String artifactChecksum;
+    private Integer artifactTimeout;
+    private String artifactUUID;
+    private IArtifactInfo generatedArtifact;
+    private List<IArtifactInfo> relatedArtifacts;
 }
diff --git a/src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java b/src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java
deleted file mode 100644 (file)
index 2414991..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright Â© 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Copyright Â© 2017-2018 European Software Marketing Ltd.
- * ================================================================================
- * 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.onap.aai.modelloader.service;
-
-import java.io.IOException;
-import java.security.KeyManagementException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import org.onap.aai.modelloader.config.ModelLoaderConfig;
-import org.onap.aai.modelloader.restclient.BabelServiceClient;
-import org.onap.aai.modelloader.restclient.BabelServiceClientException;
-import org.onap.aai.modelloader.restclient.HttpsBabelServiceClient;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Service;
-
-@Service
-@Primary
-public class HttpsBabelServiceClientFactory implements BabelServiceClientFactory {
-
-    /*
-     * (non-Javadoc)
-     * 
-     * @see org.onap.aai.modelloader.service.BabelServiceClientFactory#create(org.onap.aai.modelloader.config.
-     * ModelLoaderConfig)
-     */
-    @Override
-    public BabelServiceClient create(ModelLoaderConfig config) throws BabelServiceClientException {
-        try {
-            return new HttpsBabelServiceClient(config);
-        } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
-                | CertificateException | IOException ex) {
-            throw new BabelServiceClientException(ex);
-        }
-    }
-
-}
 package org.onap.aai.modelloader.service;
 
 import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Base64;
-import java.util.Date;
 import java.util.List;
-import java.util.Properties;
-import java.util.Timer;
-import java.util.TimerTask;
 
-import javax.annotation.PostConstruct;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 
@@ -41,16 +33,10 @@ import org.onap.aai.cl.eelf.LoggerFactory;
 import org.onap.aai.modelloader.config.ModelLoaderConfig;
 import org.onap.aai.modelloader.entity.Artifact;
 import org.onap.aai.modelloader.notification.ArtifactDownloadManager;
-import org.onap.aai.modelloader.notification.EventCallback;
 import org.onap.aai.modelloader.notification.NotificationDataImpl;
 import org.onap.aai.modelloader.notification.NotificationPublisher;
 import org.onap.sdc.api.IDistributionClient;
 import org.onap.sdc.api.notification.IArtifactInfo;
-import org.onap.sdc.api.results.IDistributionClientResult;
-import org.onap.sdc.impl.DistributionClientFactory;
-import org.onap.sdc.utils.DistributionActionResultEnum;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -61,85 +47,20 @@ import org.springframework.web.bind.annotation.RestController;
  */
 @RestController
 @RequestMapping("/services/model-loader/v1/model-service")
-public class ModelLoaderService implements ModelLoaderInterface {
+public class ModelController implements ModelLoaderInterface {
 
-    private static final Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
+    private static final Logger logger = LoggerFactory.getInstance().getLogger(ModelController.class);
 
-    @Value("${CONFIG_HOME}")
-    private String configDir;
-    private IDistributionClient client;
-    private ModelLoaderConfig config;
-    @Autowired
-    private BabelServiceClientFactory babelClientFactory;
+    private final IDistributionClient client;
+    private final ModelLoaderConfig config;
+    private final ArtifactDeploymentManager artifactDeploymentManager;
+    private final ArtifactDownloadManager artifactDownloadManager;
 
-    /**
-     * Responsible for loading configuration files and calling initialization.
-     */
-    @PostConstruct
-    protected void start() {
-        // Load model loader system configuration
-        logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
-        ModelLoaderConfig.setConfigHome(configDir);
-        Properties configProperties = new Properties();
-        try (InputStream configInputStream = Files.newInputStream(Paths.get(configDir, "model-loader.properties"))) {
-            configProperties.load(configInputStream);
-            config = new ModelLoaderConfig(configProperties);
-            if (!config.getASDCConnectionDisabled()) {
-                initSdcClient();
-            }
-        } catch (IOException e) {
-            String errorMsg = "Failed to load configuration: " + e.getMessage();
-            logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
-        }
-    }
-
-    /**
-     * Responsible for stopping the connection to the distribution client before the resource is destroyed.
-     */
-    public void preShutdownOperations() {
-        logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
-        if (client != null) {
-            client.stop();
-        }
-    }
-
-    /**
-     * Responsible for loading configuration files, initializing model distribution clients, and starting them.
-     */
-    protected void initSdcClient() {
-        // Initialize distribution client
-        logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
-        client = DistributionClientFactory.createDistributionClient();
-        EventCallback callback = new EventCallback(client, config, babelClientFactory);
-
-        IDistributionClientResult initResult = client.init(config, callback);
-
-        if (initResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
-            // Start distribution client
-            logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
-            IDistributionClientResult startResult = client.start();
-            if (startResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
-                logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
-            } else {
-                String errorMsg = "Failed to start distribution client: " + startResult.getDistributionMessageResult();
-                logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
-
-                // Kick off a timer to retry the SDC connection
-                Timer timer = new Timer();
-                TimerTask task = new SdcConnectionJob(client, config, callback, timer);
-                timer.schedule(task, new Date(), 60000);
-            }
-        } else {
-            String errorMsg = "Failed to initialize distribution client: " + initResult.getDistributionMessageResult();
-            logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
-
-            // Kick off a timer to retry the SDC connection
-            Timer timer = new Timer();
-            TimerTask task = new SdcConnectionJob(client, config, callback, timer);
-            timer.schedule(task, new Date(), 60000);
-        }
-
-        Runtime.getRuntime().addShutdownHook(new Thread(this::preShutdownOperations));
+    public ModelController(IDistributionClient client, ModelLoaderConfig config, ArtifactDeploymentManager artifactDeploymentManager, ArtifactDownloadManager artifactDownloadManager) {
+        this.client = client;
+        this.config = config;
+        this.artifactDeploymentManager = artifactDeploymentManager;
+        this.artifactDownloadManager = artifactDownloadManager;
     }
 
     /**
@@ -193,7 +114,7 @@ public class ModelLoaderService implements ModelLoaderInterface {
             List<Artifact> modelArtifacts = new ArrayList<>();
             List<Artifact> catalogArtifacts = new ArrayList<>();
 
-            new ArtifactDownloadManager(client, config, babelClientFactory).processToscaArtifacts(modelArtifacts,
+            artifactDownloadManager.processToscaArtifacts(modelArtifacts,
                     catalogArtifacts, csarFile, artifactInfo, "test-transaction-id", modelVersion);
 
             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Loading xml models from test artifacts: "
@@ -202,7 +123,7 @@ public class ModelLoaderService implements ModelLoaderInterface {
             NotificationDataImpl notificationData = new NotificationDataImpl();
             notificationData.setDistributionID("TestDistributionID");
             boolean success =
-                    new ArtifactDeploymentManager(config).deploy(notificationData, modelArtifacts, catalogArtifacts);
+                    artifactDeploymentManager.deploy(notificationData, modelArtifacts, catalogArtifacts);
             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Deployment success was " + success);
             response = success ? Response.ok().build() : Response.serverError().build();
         } catch (Exception e) {
index 9a6c6e9..79cf538 100644 (file)
@@ -34,12 +34,11 @@ public class SdcConnectionJob extends TimerTask {
     private static final Logger logger = LoggerFactory.getInstance().getLogger(SdcConnectionJob.class.getName());
 
     private final IDistributionClient client;
-    private ModelLoaderConfig config;
-    private EventCallback callback;
-    private Timer timer;
+    private final ModelLoaderConfig config;
+    private final EventCallback callback;
+    private final Timer timer;
 
     public SdcConnectionJob(IDistributionClient client, ModelLoaderConfig config, EventCallback callback, Timer timer) {
-        super();
         this.client = client;
         this.timer = timer;
         this.callback = callback;
index 4ea6f0a..d3b4f45 100644 (file)
@@ -12,9 +12,20 @@ server.port=9500
 #server.ssl.keyStoreType=
 #server.ssl.keyAlias=
 
-server.tomcat.max-threads=200
+spring.application.name=model-loader
+
+spring.sleuth.enabled=false
+spring.zipkin.baseUrl=http://jaeger-collector.istio-system:9411
+spring.sleuth.messaging.jms.enabled=false
+spring.sleuth.trace-id128=true
+spring.sleuth.sampler.probability=1.0
+spring.sleuth.propagation.type=w3c,b3
+spring.sleuth.supports-join=false
+spring.sleuth.web.skip-pattern=/aai/util.*
+
+server.tomcat.threads.max=200
 # The minimum number of threads always kept alive
-server.tomcat.min-spare-threads=25
+server.tomcat.threads.min-spare=25
 
 # Spring Boot logging
 logging.config=${logback.configurationFile}
diff --git a/src/test/java/org/onap/aai/modelloader/BabelClientTestConfiguration.java b/src/test/java/org/onap/aai/modelloader/BabelClientTestConfiguration.java
new file mode 100644 (file)
index 0000000..9df74fa
--- /dev/null
@@ -0,0 +1,57 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Primary;
+
+@TestConfiguration
+public class BabelClientTestConfiguration {
+  @Value("${CONFIG_HOME}")
+  private String configDir;
+
+  @Value("${wiremock.server.port}")
+  private int wiremockPort;
+
+  @Primary
+  @Bean(name = "testProperties")
+  public Properties configProperties() throws IOException {
+    // Load model loader system configuration
+    InputStream configInputStream = Files.newInputStream(Paths.get(configDir, "model-loader.properties"));
+    Properties configProperties = new Properties();
+    configProperties.load(configInputStream);
+
+    setOverrides(configProperties);
+
+    return configProperties;
+  }
+
+  private void setOverrides(Properties configProperties) {
+    configProperties.setProperty("ml.babel.BASE_URL", "http://localhost:" + wiremockPort);
+  }
+}
diff --git a/src/test/java/org/onap/aai/modelloader/DistributionClientTestConfiguration.java b/src/test/java/org/onap/aai/modelloader/DistributionClientTestConfiguration.java
new file mode 100644 (file)
index 0000000..1eed62f
--- /dev/null
@@ -0,0 +1,81 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.matching;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.context.event.ApplicationStartedEvent;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Primary;
+import org.springframework.context.event.EventListener;
+
+@TestConfiguration
+public class DistributionClientTestConfiguration {
+
+  @Value("${CONFIG_HOME}")
+  private String configDir;
+
+  @Value("${wiremock.server.port}")
+  private int wiremockPort;
+
+  @Primary
+  @Bean(name = "testProperties")
+  public Properties configProperties() throws IOException {
+    // Load model loader system configuration
+    InputStream configInputStream = Files.newInputStream(Paths.get(configDir, "model-loader.properties"));
+    Properties configProperties = new Properties();
+    configProperties.load(configInputStream);
+
+    setOverrides(configProperties);
+
+    return configProperties;
+  }
+
+  private void setOverrides(Properties configProperties) {
+    configProperties.setProperty("ml.distribution.ASDC_ADDRESS", "localhost:" + wiremockPort);
+    configProperties.setProperty("ml.babel.BASE_URL", "http://localhost:" + wiremockPort);
+  }
+
+  @EventListener(ApplicationStartedEvent.class)
+  public void mockSdcInit() {
+    stubFor(get(urlEqualTo("/sdc/v1/artifactTypes"))
+        .withHeader("X-ECOMP-RequestID", matching(".+"))
+        .withHeader("X-ECOMP-InstanceID", equalTo("aai-ml-id-test"))
+        .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("artifactTypes.json")));
+
+    stubFor(get(urlEqualTo("/sdc/v1/distributionKafkaData"))
+        .withHeader("X-ECOMP-RequestID", matching(".+"))
+        .withHeader("X-ECOMP-InstanceID", equalTo("aai-ml-id-test"))
+        .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("kafkaBootstrap.json")));
+  }
+}
\ No newline at end of file
index e19b1e2..87fbd6a 100644 (file)
@@ -20,8 +20,8 @@
  */
 package org.onap.aai.modelloader.config;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
 
 import java.io.File;
 import java.io.FileInputStream;
@@ -29,7 +29,7 @@ import java.io.IOException;
 import java.util.List;
 import java.util.Properties;
 import org.eclipse.jetty.util.security.Password;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.onap.aai.modelloader.restclient.AaiRestClient;
 import org.onap.sdc.utils.ArtifactTypeEnum;
 
@@ -157,13 +157,13 @@ public class TestModelLoaderConfig {
         ModelLoaderConfig config = new ModelLoaderConfig(props, null);
         AaiRestClient aaiClient = new AaiRestClient(config);
 
-        assertFalse("Empty AAI Password should result in no basic authentication", aaiClient.useBasicAuth());
+        assertFalse(aaiClient.useBasicAuth(), "Empty AAI Password should result in no basic authentication");
 
         props.load(new FileInputStream("src/test/resources/model-loader-no-auth-password.properties"));
         config = new ModelLoaderConfig(props, null);
         aaiClient = new AaiRestClient(config);
 
-        assertFalse("No AAI Password should result in no basic authentication", aaiClient.useBasicAuth());
+        assertFalse(aaiClient.useBasicAuth(), "No AAI Password should result in no basic authentication");
     }
 
     @Test
index bd8c33f..b3335fc 100644 (file)
 package org.onap.aai.modelloader.csar.extractor;
 
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
 import java.util.stream.Collectors;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
 import org.onap.aai.modelloader.entity.Artifact;
 import org.onap.aai.modelloader.entity.ArtifactType;
 import org.onap.aai.modelloader.extraction.InvalidArchiveException;
@@ -85,8 +86,8 @@ public class VnfCatalogExtractorTest {
         List<Artifact> vnfcArtifacts = new VnfCatalogExtractor().extract(
                 new ArtifactTestUtils().loadResource("compressedArtifacts/noVnfcFilesArchive.csar"),
                 "noVnfcFilesArchive.csar");
-        assertTrue("No VNFC files should have been extracted, but " + vnfcArtifacts.size() + " were found.",
-                vnfcArtifacts.isEmpty());
+        assertTrue(vnfcArtifacts.isEmpty(),
+                "No VNFC files should have been extracted, but " + vnfcArtifacts.size() + " were found.");
     }
 
     @Test
diff --git a/src/test/java/org/onap/aai/modelloader/distribution/EventCallbackAspect.java b/src/test/java/org/onap/aai/modelloader/distribution/EventCallbackAspect.java
new file mode 100644 (file)
index 0000000..16f311b
--- /dev/null
@@ -0,0 +1,49 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader.distribution;
+
+import java.util.concurrent.CountDownLatch;
+
+import org.aspectj.lang.annotation.After;
+import org.aspectj.lang.annotation.Aspect;
+import org.springframework.stereotype.Component;
+
+import lombok.Getter;
+import lombok.Setter;
+
+@Aspect
+@Getter
+@Setter
+@Component
+/**
+ * Aspect to asynchronously wait for the EventCallback being called after a distribution event from sdc was published
+ */
+public class EventCallbackAspect {
+
+  private CountDownLatch countDownLatch;
+
+  @After(
+      "execution(* org.onap.aai.modelloader.notification.EventCallback.activateCallback(..))")
+  private void afterEventCallbackCalled() {
+    if (countDownLatch != null) {
+      countDownLatch.countDown();
+    }
+  }
+}
\ No newline at end of file
diff --git a/src/test/java/org/onap/aai/modelloader/distribution/NotificationIntegrationTest.java b/src/test/java/org/onap/aai/modelloader/distribution/NotificationIntegrationTest.java
new file mode 100644 (file)
index 0000000..abdefd4
--- /dev/null
@@ -0,0 +1,68 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader.distribution;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.onap.aai.modelloader.notification.NotificationDataImpl;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.kafka.core.KafkaTemplate;
+import org.springframework.kafka.test.context.EmbeddedKafka;
+import org.springframework.test.annotation.DirtiesContext;
+
+@DirtiesContext
+@SpringBootTest(properties = { "model-loader.sdc.connection.enabled=true"})
+@EmbeddedKafka(partitions = 1, ports = 9092, topics = {"${topics.distribution.notification}"})
+public class NotificationIntegrationTest {
+
+    @Autowired EventCallbackAspect eventCallbackAspect;
+
+    @Autowired
+    private KafkaTemplate<String, NotificationDataImpl> kafkaTemplate;
+
+    @Value("${topics.distribution.notification}")
+    private String topic;
+
+    @Test
+    @Disabled("This test is not yet implemented")
+    public void thatActivateCallbackIsCalled()
+      throws Exception {
+        NotificationDataImpl notificationData = new NotificationDataImpl();
+        notificationData.setDistributionID("distributionID");
+    
+        // TODO: send distribution event here
+        kafkaTemplate.send(topic, notificationData);
+
+        // TODO: mock distribution client requests to /sdc/v1/artifactTypes
+        // TODO: mock distribution client requests to /sdc/v1/distributionKafkaData
+
+        // aspect will wait for EventCallback.activateCallback to be called
+        eventCallbackAspect.setCountDownLatch(new CountDownLatch(1));
+        boolean callbackCalled = eventCallbackAspect.getCountDownLatch().await(10, TimeUnit.SECONDS);
+        assertTrue(callbackCalled);
+    }
+}
index cead699..8145599 100644 (file)
@@ -22,8 +22,8 @@ package org.onap.aai.modelloader.entity.catalog;
 
 import static org.hamcrest.CoreMatchers.containsString;
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -34,9 +34,11 @@ import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
+
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
 import org.onap.aai.modelloader.config.ModelLoaderConfig;
index c8b14f7..793ed9a 100644 (file)
@@ -22,9 +22,9 @@ package org.onap.aai.modelloader.entity.catalog;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * Tests for NotificationDataImpl class.
index 8f4bf8d..0c79dc5 100644 (file)
@@ -24,14 +24,16 @@ import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.not;
 import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.isEmptyString;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
 import org.onap.aai.modelloader.entity.Artifact;
 
 public class ModelSorterTest {
@@ -128,12 +130,14 @@ public class ModelSorterTest {
         assertThat(new ModelSorter().sort(Arrays.asList(nq1, nq2, artifact)), is(expected));
     }
 
-    @Test(expected = BabelArtifactParsingException.class)
+    @Test
     public void circularDependency() throws BabelArtifactParsingException {
-        List<Artifact> modelList = new ArrayList<Artifact>();
-        modelList.add(buildTestModel("aaaa", "1111", "bbbb|1111"));
-        modelList.add(buildTestModel("bbbb", "1111", "aaaa|1111"));
-        new ModelSorter().sort(modelList);
+        assertThrows(BabelArtifactParsingException.class, () -> {
+            List<Artifact> modelList = new ArrayList<Artifact>();
+            modelList.add(buildTestModel("aaaa", "1111", "bbbb|1111"));
+            modelList.add(buildTestModel("bbbb", "1111", "aaaa|1111"));
+            new ModelSorter().sort(modelList);
+        });
     }
 
     private ModelArtifact buildTestModel() {
index 5ccd1d2..177a8d2 100644 (file)
 package org.onap.aai.modelloader.entity.model;
 
 import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.hasSize;
-import static org.hamcrest.Matchers.isEmptyString;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+
 import javax.ws.rs.core.Response;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.onap.aai.modelloader.config.ModelLoaderConfig;
@@ -55,9 +55,9 @@ public class TestModelArtifactHandler {
     @Mock
     private AaiRestClient aaiClient;
 
-    @Before
+    @BeforeEach
     public void setupMocks() {
-        MockitoAnnotations.initMocks(this);
+        MockitoAnnotations.openMocks(this);
     }
 
     @Test
index aef0acc..fc0556f 100644 (file)
@@ -23,13 +23,14 @@ package org.onap.aai.modelloader.entity.model;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.not;
 import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase;
-import static org.junit.Assert.assertThat;
 
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.util.List;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
 import org.onap.aai.modelloader.entity.Artifact;
 import org.springframework.util.CollectionUtils;
 
index 1d2d385..9ea900f 100644 (file)
 package org.onap.aai.modelloader.entity.model;
 
 import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.isEmptyString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.util.List;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
 import org.onap.aai.modelloader.entity.Artifact;
 
 public class TestNamedQueryArtifactParser {
index 3bfb2a5..142b3c0 100644 (file)
@@ -20,8 +20,8 @@
  */
 package org.onap.aai.modelloader.extraction;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getEmptyNotificationData;
 import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneResource;
 import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneService;
@@ -29,9 +29,9 @@ import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.ge
 
 import java.util.ArrayList;
 import java.util.List;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.onap.aai.modelloader.fixture.ArtifactInfoBuilder;
 import org.onap.aai.modelloader.fixture.MockNotificationDataImpl;
 import org.onap.sdc.api.notification.IArtifactInfo;
@@ -44,12 +44,12 @@ public class TestArtifactInfoExtractor {
 
     private ArtifactInfoExtractor extractor;
 
-    @Before
+    @BeforeEach
     public void setup() {
         extractor = new ArtifactInfoExtractor();
     }
 
-    @After
+    @AfterEach
     public void tearDown() {
         extractor = null;
     }
@@ -60,7 +60,7 @@ public class TestArtifactInfoExtractor {
     }
 
     private void doEmptyArtifactsTest(INotificationData notificationData) {
-        assertTrue("The list returned should have been empty", extractor.extract(notificationData).isEmpty());
+        assertTrue(extractor.extract(notificationData).isEmpty(), "The list returned should have been empty");
     }
 
     @Test
@@ -79,8 +79,8 @@ public class TestArtifactInfoExtractor {
 
         List<IArtifactInfo> artifacts = extractor.extract(getNotificationDataWithOneService());
 
-        assertEquals("One artifact should have been returned", 1, artifacts.size());
-        assertEquals("The actual artifact did not match the expected one", expected, artifacts.get(0));
+        assertEquals(1, artifacts.size(), "One artifact should have been returned");
+        assertEquals(expected, artifacts.get(0), "The actual artifact did not match the expected one");
     }
 
     @Test
@@ -90,8 +90,8 @@ public class TestArtifactInfoExtractor {
 
         List<IArtifactInfo> artifacts = extractor.extract(getNotificationDataWithOneResource());
 
-        assertEquals("One artifact should have been returned", 1, artifacts.size());
-        assertEquals("The actual artifact did not match the expected one", expectedArtifacts, artifacts);
+        assertEquals(1, artifacts.size(), "One artifact should have been returned");
+        assertEquals(expectedArtifacts, artifacts, "The actual artifact did not match the expected one");
     }
 
     @Test
@@ -102,7 +102,7 @@ public class TestArtifactInfoExtractor {
 
         List<IArtifactInfo> artifacts = extractor.extract(getNotificationDataWithOneServiceAndResources());
 
-        assertEquals("Two artifact should have been returned", 2, artifacts.size());
-        assertEquals("The actual artifact did not match the expected one", expectedArtifacts, artifacts);
+        assertEquals(2, artifacts.size(), "Two artifact should have been returned");
+        assertEquals(expectedArtifacts, artifacts, "The actual artifact did not match the expected one");
     }
 }
diff --git a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java b/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java
new file mode 100644 (file)
index 0000000..0985790
--- /dev/null
@@ -0,0 +1,107 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader.notification;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.matching;
+import static com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath;
+import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.http.entity.ContentType;
+import org.junit.jupiter.api.Test;
+import org.onap.aai.modelloader.DistributionClientTestConfiguration;
+import org.onap.aai.modelloader.entity.Artifact;
+import org.onap.aai.modelloader.entity.ArtifactType;
+import org.onap.aai.modelloader.service.ArtifactInfoImpl;
+import org.onap.sdc.api.notification.IArtifactInfo;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
+import org.springframework.context.annotation.Import;
+import org.springframework.http.MediaType;
+import org.springframework.kafka.test.context.EmbeddedKafka;
+import org.springframework.test.annotation.DirtiesContext;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+
+@DirtiesContext
+@AutoConfigureWireMock(port = 0)
+@EmbeddedKafka(partitions = 1, ports = 9092, topics = {"${topics.distribution.notification}"})
+@SpringBootTest(properties = { "ml.distribution.connection.enabled=true" })
+@Import(DistributionClientTestConfiguration.class)
+public class ArtifactDownloadManagerTest {
+
+  @Autowired ArtifactDownloadManager artifactDownloadManager;
+
+  @Test
+  public void downloadArtifacts() throws JsonProcessingException {
+    NotificationDataImpl notificationData = new NotificationDataImpl();
+    notificationData.setDistributionID("distributionID");
+    notificationData.setServiceVersion("2.0");
+
+    stubFor(get(urlEqualTo("/sdc/v1/catalog/services/DemovlbCds/1.0/artifacts/service-TestSvc-csar.csar"))
+        .withHeader("Accept", equalTo(ContentType.APPLICATION_OCTET_STREAM.toString()))
+        .withHeader("X-ECOMP-RequestID", matching(".+"))
+        .withHeader("X-ECOMP-InstanceID", equalTo("aai-ml-id-test"))
+        .willReturn(aResponse()
+          .withHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM.toString())
+          .withBodyFile("service-TestSvc-csar.csar")));
+    
+    stubFor(
+        post(urlEqualTo("/services/babel-service/v1/app/generateArtifacts"))
+            .withHeader("X-TransactionId", equalTo("distributionID"))
+            .withHeader("X-FromAppId", equalTo("ModelLoader"))
+            .withHeader("Content-Type", equalTo(MediaType.APPLICATION_JSON_VALUE))
+            .withRequestBody(matchingJsonPath("$.artifactName", equalTo("service-TestSvc-csar.csar")))
+            .withRequestBody(matchingJsonPath("$.artifactVersion", equalTo("2.0")))
+            .withRequestBody(matchingJsonPath("$.csar", matching(".*")))
+            .willReturn(
+                aResponse()
+                    .withHeader("Content-Type", "application/json")
+                    .withBodyFile("service-TestSvc-csar-babel-response.json")));
+
+    ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl();
+    artifactInfo.setArtifactName("service-TestSvc-csar.csar");
+    artifactInfo.setArtifactVersion("1.0");
+    artifactInfo.setArtifactURL("/sdc/v1/catalog/services/DemovlbCds/1.0/artifacts/service-TestSvc-csar.csar");
+    artifactInfo.setArtifactType("TOSCA_CSAR");
+    artifactInfo.setArtifactChecksum("ZmI5NzQ1MWViZGFkMjRjZWEwNTQzY2U0OWQwYjlmYjQ=");
+    artifactInfo.setArtifactUUID("f6f907f1-3f45-4fb4-8cbe-15a4c6ee16db");
+    List<IArtifactInfo> artifacts = new ArrayList<>();
+    artifacts.add(artifactInfo);
+    List<Artifact> modelArtifacts = new ArrayList<>(); // processed artifacts will be written to this list
+    List<Artifact> catalogArtifacts = new ArrayList<>(); // processed artifacts will be written to this list
+    boolean result = artifactDownloadManager.downloadArtifacts(notificationData, artifacts, modelArtifacts, catalogArtifacts);
+    
+    assertEquals(1, modelArtifacts.size());
+    assertEquals(ArtifactType.MODEL, modelArtifacts.get(0).getType());
+    assertTrue(result);
+  }
+
+}
index c0de0ee..a64c00c 100644 (file)
 package org.onap.aai.modelloader.notification;
 
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile;
 
@@ -33,11 +32,15 @@ import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
 import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
 import org.onap.aai.babel.service.data.BabelArtifact;
-import org.onap.aai.modelloader.config.ModelLoaderConfig;
+import org.onap.aai.modelloader.babel.BabelArtifactService;
 import org.onap.aai.modelloader.entity.Artifact;
 import org.onap.aai.modelloader.entity.ArtifactType;
 import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifact;
@@ -55,40 +58,30 @@ import org.onap.sdc.api.notification.INotificationData;
 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
 import org.onap.sdc.impl.DistributionClientDownloadResultImpl;
 import org.onap.sdc.utils.DistributionActionResultEnum;
-import org.springframework.test.util.ReflectionTestUtils;
 
 /**
  * Tests {@link ArtifactDownloadManager} with VNF Catalog Artifacts.
  */
 public class ArtifactDownloadManagerVnfcTest {
 
-    private ArtifactDownloadManager downloadManager;
-    private BabelServiceClient mockBabelClient;
-    private IDistributionClient mockDistributionClient;
-    private NotificationPublisher mockNotificationPublisher;
-    private BabelArtifactConverter mockBabelArtifactConverter;
-    private BabelServiceClientFactory mockClientFactory;
-    private VnfCatalogExtractor mockVnfCatalogExtractor;
+    @Mock private ArtifactDownloadManager downloadManager;
+    @Mock private BabelServiceClient mockBabelClient;
+    @Mock private IDistributionClient mockDistributionClient;
+    @Mock private NotificationPublisher mockNotificationPublisher;
+    @Mock private BabelArtifactConverter mockBabelArtifactConverter;
+    @Mock private BabelServiceClientFactory mockClientFactory;
+    @Mock private VnfCatalogExtractor mockVnfCatalogExtractor;
+    @InjectMocks private BabelArtifactService babelArtifactService;
 
-    @Before
+    @BeforeEach
     public void setup() throws Exception {
-        mockBabelClient = mock(BabelServiceClient.class);
-        mockDistributionClient = mock(IDistributionClient.class);
-        mockNotificationPublisher = mock(NotificationPublisher.class);
-        mockBabelArtifactConverter = mock(BabelArtifactConverter.class);
-        mockClientFactory = mock(BabelServiceClientFactory.class);
+        MockitoAnnotations.openMocks(this);
         when(mockClientFactory.create(Mockito.any())).thenReturn(mockBabelClient);
-        mockVnfCatalogExtractor = mock(VnfCatalogExtractor.class);
 
         Properties configProperties = new Properties();
         configProperties.load(this.getClass().getClassLoader().getResourceAsStream("model-loader.properties"));
         downloadManager = new ArtifactDownloadManager(mockDistributionClient,
-                new ModelLoaderConfig(configProperties, "."), mockClientFactory);
-
-
-        ReflectionTestUtils.setField(downloadManager, "notificationPublisher", mockNotificationPublisher);
-        ReflectionTestUtils.setField(downloadManager, "babelArtifactConverter", mockBabelArtifactConverter);
-        ReflectionTestUtils.setField(downloadManager, "vnfCatalogExtractor", mockVnfCatalogExtractor);
+                mockNotificationPublisher, mockVnfCatalogExtractor, babelArtifactService);
     }
 
     @Test
@@ -98,7 +91,7 @@ public class ArtifactDownloadManagerVnfcTest {
         IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0);
 
         setupValidDownloadCsarMocks(data, artifactInfo);
-        when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifacts());
+        when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifacts());
         when(mockVnfCatalogExtractor.extract(any(), any())).thenReturn(new ArrayList<>());
 
         List<Artifact> modelArtifacts = new ArrayList<>();
@@ -106,7 +99,7 @@ public class ArtifactDownloadManagerVnfcTest {
         assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles),
                 is(true));
 
-        assertEquals("There should have been some catalog files", 2, catalogFiles.size());
+        assertEquals(2, catalogFiles.size(), "There should have been some catalog files");
     }
 
     @Test
@@ -116,7 +109,7 @@ public class ArtifactDownloadManagerVnfcTest {
         IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0);
 
         setupValidDownloadCsarMocks(data, artifactInfo);
-        when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifactsNoVnfc());
+        when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifactsNoVnfc());
         when(mockVnfCatalogExtractor.extract(any(), any())).thenReturn(createXmlVnfcArtifacts());
 
         List<Artifact> modelArtifacts = new ArrayList<>();
@@ -124,7 +117,7 @@ public class ArtifactDownloadManagerVnfcTest {
         assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles),
                 is(true));
 
-        assertEquals("There should have been some catalog files", 3, catalogFiles.size());
+        assertEquals(3, catalogFiles.size(), "There should have been some catalog files");
     }
 
     @Test
@@ -134,7 +127,7 @@ public class ArtifactDownloadManagerVnfcTest {
         IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0);
 
         setupValidDownloadCsarMocks(data, artifactInfo);
-        when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifactsNoVnfc());
+        when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifactsNoVnfc());
         when(mockVnfCatalogExtractor.extract(any(), any())).thenReturn(new ArrayList<>());
 
         List<Artifact> modelArtifacts = new ArrayList<>();
@@ -142,7 +135,7 @@ public class ArtifactDownloadManagerVnfcTest {
         assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles),
                 is(true));
 
-        assertEquals("There should not have been any catalog files", 0, catalogFiles.size());
+        assertEquals(0, catalogFiles.size(), "There should not have been any catalog files");
     }
 
     @Test
@@ -152,7 +145,7 @@ public class ArtifactDownloadManagerVnfcTest {
         IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0);
 
         setupValidDownloadCsarMocks(data, artifactInfo);
-        when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifacts());
+        when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifacts());
         when(mockVnfCatalogExtractor.extract(any(), any())).thenReturn(createXmlVnfcArtifacts());
         doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo);
 
diff --git a/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java b/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java
new file mode 100644 (file)
index 0000000..4d7b53e
--- /dev/null
@@ -0,0 +1,224 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader.notification;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.verify;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
+
+import java.util.List;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aai.modelloader.config.ModelLoaderConfig;
+import org.onap.aai.modelloader.entity.Artifact;
+import org.onap.aai.modelloader.entity.model.ModelArtifact;
+import org.onap.aai.modelloader.entity.model.ModelArtifactHandler;
+import org.onap.aai.modelloader.restclient.AaiRestClient;
+import org.onap.aai.restclient.client.OperationResult;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
+import org.springframework.http.HttpStatus;
+import org.w3c.dom.Node;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.tomakehurst.wiremock.client.WireMock;
+
+import java.util.ArrayList;
+
+@SpringBootTest
+@AutoConfigureWireMock(port = 0)
+public class ModelArtifactHandlerTest {
+
+  @Value("${wiremock.server.port}")
+  private int wiremockPort;
+
+  final ObjectMapper objectMapper = new ObjectMapper();
+  @Mock
+  ModelLoaderConfig config;
+  @InjectMocks
+  ModelArtifactHandler modelArtifactHandler;
+
+  @Autowired
+  AaiRestClient restClient;
+
+  @BeforeEach
+  public void setUp() {
+    when(config.getAaiBaseUrl()).thenReturn("http://localhost:" + wiremockPort);
+    when(config.getAaiModelUrl(any())).thenReturn("/aai/v28/service-design-and-creation/models/model/");
+  }
+
+  @Test
+  public void thatArtifactsCanBeCreated() {
+    WireMock.stubFor(
+        WireMock.get(urlEqualTo("/aai/v28/service-design-and-creation/models/model/modelInvariantId"))
+            .withHeader("Accept", equalTo("application/xml"))
+            .withHeader("X-TransactionId", equalTo("someId"))
+            .withHeader("X-FromAppId", equalTo("ModelLoader"))
+            .willReturn(
+                WireMock.aResponse()
+                    .withStatus(HttpStatus.NOT_FOUND.value())));
+
+    WireMock.stubFor(
+        WireMock.put(urlEqualTo("/aai/v28/service-design-and-creation/models/model/modelInvariantId"))
+            .withHeader("Content-Type", equalTo("application/xml"))
+            .withHeader("X-TransactionId", equalTo("someId"))
+            .withHeader("X-FromAppId", equalTo("ModelLoader"))
+            .willReturn(
+                WireMock.aResponse()
+                    .withStatus(HttpStatus.CREATED.value())));
+
+    ModelArtifact modelArtifact = new ModelArtifact();
+    modelArtifact.setModelInvariantId("modelInvariantId");
+    List<Artifact> artifacts = List.of(modelArtifact);
+    List<Artifact> completedArtifacts = new ArrayList<>();
+
+    boolean result = modelArtifactHandler.pushArtifacts(artifacts,
+        "someId", completedArtifacts, restClient);
+    assertTrue(result);
+    WireMock.verify(
+        WireMock.putRequestedFor(urlEqualTo("/aai/v28/service-design-and-creation/models/model/modelInvariantId")));
+  }
+
+  @Test
+  public void thatArtifactsCanBeUpdated() {
+    // Checks if model exists in resources service
+    WireMock.stubFor(
+        WireMock.get(urlEqualTo("/aai/v28/service-design-and-creation/models/model/modelInvariantId"))
+            .withHeader("Accept", equalTo("application/xml"))
+            .withHeader("X-TransactionId", equalTo("distributionId"))
+            .withHeader("X-FromAppId", equalTo("ModelLoader"))
+            .willReturn(
+                WireMock.aResponse()
+                    .withStatus(HttpStatus.OK.value())));
+
+    // Checks if specific version of model exists in aai-resources
+    WireMock.stubFor(
+        WireMock.get(urlEqualTo(
+            "/aai/v28/service-design-and-creation/models/model/modelInvariantId/model-vers/model-ver/modelVersionId"))
+            .withHeader("Accept", equalTo("application/xml"))
+            .withHeader("X-TransactionId", equalTo("distributionId"))
+            .withHeader("X-FromAppId", equalTo("ModelLoader"))
+            .willReturn(
+                WireMock.aResponse()
+                    .withStatus(HttpStatus.NOT_FOUND.value())));
+
+    WireMock.stubFor(
+        WireMock.put(urlEqualTo(
+            "/aai/v28/service-design-and-creation/models/model/modelInvariantId/model-vers/model-ver/modelVersionId"))
+            .withHeader("Content-Type", equalTo("application/xml"))
+            .withHeader("X-TransactionId", equalTo("distributionId"))
+            .withHeader("X-FromAppId", equalTo("ModelLoader"))
+            .willReturn(
+                WireMock.aResponse()
+                    .withStatus(HttpStatus.CREATED.value())));
+
+    ModelArtifact modelArtifact = new ModelArtifact();
+    modelArtifact.setModelInvariantId("modelInvariantId");
+    modelArtifact.setModelVerId("modelVersionId");
+    Node node = Mockito.mock(Node.class);
+    modelArtifact.setModelVer(node);
+    List<Artifact> artifacts = List.of(modelArtifact);
+    List<Artifact> completedArtifacts = new ArrayList<>();
+
+    boolean result = modelArtifactHandler.pushArtifacts(artifacts,
+        "distributionId", completedArtifacts, restClient);
+    verify(WireMock.putRequestedFor(urlEqualTo(
+        "/aai/v28/service-design-and-creation/models/model/modelInvariantId/model-vers/model-ver/modelVersionId")));
+    assertTrue(result);
+  }
+
+  @Test
+  public void thatModelCanBeRolledBack() {
+    stubFor(WireMock.get(urlEqualTo("/aai/v28/service-design-and-creation/models/model/3a40ab73-6694-4e75-bb6d-9a4a86ce35b3"))
+        .withHeader("X-FromAppId", equalTo("ModelLoader"))
+        .withHeader("X-TransactionId", equalTo("distributionId"))
+        .willReturn(aResponse()
+            .withBodyFile("modelResponse.xml")));
+
+    stubFor(WireMock.delete(urlEqualTo("/aai/v28/service-design-and-creation/models/model/3a40ab73-6694-4e75-bb6d-9a4a86ce35b3?resource-version=1710523260974"))
+        .withHeader("X-FromAppId", equalTo("ModelLoader"))
+        .withHeader("X-TransactionId", equalTo("distributionId"))
+        .willReturn(aResponse().withStatus(HttpStatus.OK.value())));
+
+    ModelArtifact modelArtifact = new ModelArtifact();
+    modelArtifact.setModelInvariantId("3a40ab73-6694-4e75-bb6d-9a4a86ce35b3");
+    modelArtifact.setModelVerId("modelVersionId");
+    Node node = Mockito.mock(Node.class);
+    modelArtifact.setModelVer(node);
+    List<Artifact> completedArtifacts = new ArrayList<>();
+    completedArtifacts.add(modelArtifact);
+
+    mockModelCreation(modelArtifact);
+
+    modelArtifactHandler.rollback(completedArtifacts, "distributionId", restClient);
+
+    verify(
+        deleteRequestedFor(
+            urlEqualTo("/aai/v28/service-design-and-creation/models/model/3a40ab73-6694-4e75-bb6d-9a4a86ce35b3?resource-version=1710523260974")));
+  }
+
+  /**
+   * To test the rollback of the full model, the ModelArtifact must have the
+   * firstVersionOfModel = true state.
+   * This flag is set during the model creation and thus needs to run before
+   * testing this particular aspect.
+   *
+   * @param modelArtifact
+   */
+  private void mockModelCreation(ModelArtifact modelArtifact) {
+    OperationResult createdResult = Mockito.mock(OperationResult.class);
+    when(createdResult.getResultCode()).thenReturn(HttpStatus.CREATED.value());
+    OperationResult notFoundResult = Mockito.mock(OperationResult.class);
+    when(notFoundResult.getResultCode()).thenReturn(HttpStatus.NOT_FOUND.value());
+    AaiRestClient aaiClient = Mockito.mock(AaiRestClient.class);
+    when(aaiClient.putResource(any(), any(), any(), any())).thenReturn(createdResult);
+    when(aaiClient.getResource(any(), any(), any())).thenReturn(notFoundResult);
+    modelArtifact.push(aaiClient, config, null, new ArrayList<>());
+  }
+
+  @Test
+  public void thatModelVersionCanBeRolledBack() {
+
+    // "http://localhost:10594/aai/v28/service-design-and-creation/models/model/modelInvariantId/model-vers/model-ver/modelVersionId"
+
+    ModelArtifact modelArtifact = new ModelArtifact();
+    modelArtifact.setModelInvariantId("modelInvariantId");
+    modelArtifact.setModelVerId("modelVersionId");
+    Node node = Mockito.mock(Node.class);
+    modelArtifact.setModelVer(node);
+    List<Artifact> completedArtifacts = new ArrayList<>();
+    completedArtifacts.add(modelArtifact);
+
+    modelArtifactHandler.rollback(completedArtifacts, "distributionId", restClient);
+
+  }
+}
\ No newline at end of file
index b50bd0d..dfced1a 100644 (file)
 package org.onap.aai.modelloader.notification;
 
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithCatalogFile;
 import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithOneOfEach;
@@ -33,10 +32,13 @@ import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
 import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
 import org.onap.aai.babel.service.data.BabelArtifact;
 import org.onap.aai.modelloader.config.ModelLoaderConfig;
 import org.onap.aai.modelloader.entity.Artifact;
@@ -49,7 +51,6 @@ import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder;
 import org.onap.aai.modelloader.service.ArtifactDeploymentManager;
 import org.onap.aai.modelloader.util.ArtifactTestUtils;
 import org.onap.sdc.api.notification.INotificationData;
-import org.springframework.test.util.ReflectionTestUtils;
 
 /**
  * Tests {@link ArtifactDeploymentManager}.
@@ -62,28 +63,24 @@ public class TestArtifactDeploymentManager {
     private Properties configProperties;
     private ArtifactDeploymentManager manager;
 
-    private ModelArtifactHandler mockModelArtifactHandler;
-    private VnfCatalogArtifactHandler mockVnfCatalogArtifactHandler;
+    @Mock private ModelArtifactHandler modelArtifactHandlerMock;
+    @Mock private VnfCatalogArtifactHandler vnfCatalogArtifactHandlerMock;
 
-    @Before
+    @BeforeEach
     public void setup() throws IOException {
+        MockitoAnnotations.openMocks(this);
         configProperties = new Properties();
         configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE));
 
-        mockModelArtifactHandler = mock(ModelArtifactHandler.class);
-        mockVnfCatalogArtifactHandler = mock(VnfCatalogArtifactHandler.class);
-
-        manager = new ArtifactDeploymentManager(new ModelLoaderConfig(configProperties, null));
-
-        ReflectionTestUtils.setField(manager, "modelArtifactHandler", mockModelArtifactHandler);
-        ReflectionTestUtils.setField(manager, "vnfCatalogArtifactHandler", mockVnfCatalogArtifactHandler);
+        ModelLoaderConfig modelLoaderConfig = new ModelLoaderConfig(configProperties, null);
+        manager = new ArtifactDeploymentManager(modelLoaderConfig, modelArtifactHandlerMock, vnfCatalogArtifactHandlerMock);
     }
 
-    @After
+    @AfterEach
     public void tearDown() {
         configProperties = null;
-        mockModelArtifactHandler = null;
-        mockVnfCatalogArtifactHandler = null;
+        modelArtifactHandlerMock = null;
+        vnfCatalogArtifactHandlerMock = null;
         manager = null;
     }
 
@@ -94,18 +91,18 @@ public class TestArtifactDeploymentManager {
         List<BabelArtifact> toscaArtifacts = setupTest(xml, data);
         List<Artifact> modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts);
 
-        when(mockModelArtifactHandler.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any()))
+        when(modelArtifactHandlerMock.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any()))
                 .thenReturn(false);
 
         assertThat(SHOULD_HAVE_RETURNED_FALSE, manager.deploy(data, modelArtifacts, new ArrayList<>()), is(false));
 
-        Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(),
+        Mockito.verify(modelArtifactHandlerMock).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(),
                 any());
-        Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).pushArtifacts(eq(modelArtifacts),
+        Mockito.verify(vnfCatalogArtifactHandlerMock, Mockito.never()).pushArtifacts(eq(modelArtifacts),
                 eq(data.getDistributionID()), any(), any());
-        Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList<Artifact>()), eq(data.getDistributionID()),
+        Mockito.verify(modelArtifactHandlerMock).rollback(eq(new ArrayList<Artifact>()), eq(data.getDistributionID()),
                 any());
-        Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(eq(new ArrayList<Artifact>()),
+        Mockito.verify(vnfCatalogArtifactHandlerMock, Mockito.never()).rollback(eq(new ArrayList<Artifact>()),
                 eq(data.getDistributionID()), any());
     }
 
@@ -128,19 +125,19 @@ public class TestArtifactDeploymentManager {
         List<org.onap.aai.modelloader.entity.Artifact> catalogFiles = new ArrayList<>();
         catalogFiles.add(new VnfCatalogArtifact("Some catalog content"));
 
-        when(mockModelArtifactHandler.pushArtifacts(any(), any(), any(), any())).thenReturn(true);
-        when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any()))
+        when(modelArtifactHandlerMock.pushArtifacts(any(), any(), any(), any())).thenReturn(true);
+        when(vnfCatalogArtifactHandlerMock.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any()))
                 .thenReturn(false);
 
         assertThat(SHOULD_HAVE_RETURNED_FALSE, manager.deploy(data, new ArrayList<>(), catalogFiles), is(false));
 
-        Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(new ArrayList<Artifact>()),
+        Mockito.verify(modelArtifactHandlerMock).pushArtifacts(eq(new ArrayList<Artifact>()),
                 eq(data.getDistributionID()), any(), any());
-        Mockito.verify(mockVnfCatalogArtifactHandler).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()),
+        Mockito.verify(vnfCatalogArtifactHandlerMock).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()),
                 any(), any());
-        Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList<Artifact>()), eq(data.getDistributionID()),
+        Mockito.verify(modelArtifactHandlerMock).rollback(eq(new ArrayList<Artifact>()), eq(data.getDistributionID()),
                 any());
-        Mockito.verify(mockVnfCatalogArtifactHandler).rollback(eq(new ArrayList<Artifact>()),
+        Mockito.verify(vnfCatalogArtifactHandlerMock).rollback(eq(new ArrayList<Artifact>()),
                 eq(data.getDistributionID()), any());
     }
 
@@ -169,34 +166,34 @@ public class TestArtifactDeploymentManager {
         List<org.onap.aai.modelloader.entity.Artifact> catalogFiles = new ArrayList<>();
         catalogFiles.add(new VnfCatalogArtifact("Some catalog content"));
 
-        when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any()))
+        when(vnfCatalogArtifactHandlerMock.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any()))
                 .thenReturn(catalogsDeployed);
-        when(mockModelArtifactHandler.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any()))
+        when(modelArtifactHandlerMock.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any()))
                 .thenReturn(modelsDeployed);
 
         assertThat(SHOULD_HAVE_RETURNED_FALSE, manager.deploy(data, modelArtifacts, catalogFiles), is(false));
 
         // Catalog artifacts are only pushed if models are successful.
-        Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(),
+        Mockito.verify(modelArtifactHandlerMock).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(),
                 any());
         if (modelsDeployed) {
-            Mockito.verify(mockVnfCatalogArtifactHandler).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()),
+            Mockito.verify(vnfCatalogArtifactHandlerMock).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()),
                     any(), any());
         }
 
         if (modelsDeployed && catalogsDeployed) {
-            Mockito.verify(mockModelArtifactHandler, Mockito.never()).rollback(any(), any(), any());
-            Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(any(), any(), any());
+            Mockito.verify(modelArtifactHandlerMock, Mockito.never()).rollback(any(), any(), any());
+            Mockito.verify(vnfCatalogArtifactHandlerMock, Mockito.never()).rollback(any(), any(), any());
         } else {
             if (modelsDeployed) {
-                Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList<Artifact>()),
+                Mockito.verify(modelArtifactHandlerMock).rollback(eq(new ArrayList<Artifact>()),
                         eq(data.getDistributionID()), any());
-                Mockito.verify(mockVnfCatalogArtifactHandler).rollback(eq(new ArrayList<Artifact>()),
+                Mockito.verify(vnfCatalogArtifactHandlerMock).rollback(eq(new ArrayList<Artifact>()),
                         eq(data.getDistributionID()), any());
             } else {
-                Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList<Artifact>()),
+                Mockito.verify(modelArtifactHandlerMock).rollback(eq(new ArrayList<Artifact>()),
                         eq(data.getDistributionID()), any());
-                Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(any(), any(), any());
+                Mockito.verify(vnfCatalogArtifactHandlerMock, Mockito.never()).rollback(any(), any(), any());
             }
         }
     }
@@ -218,18 +215,18 @@ public class TestArtifactDeploymentManager {
         List<org.onap.aai.modelloader.entity.Artifact> catalogFiles = new ArrayList<>();
         catalogFiles.add(new VnfCatalogArtifact("Some catalog content"));
 
-        when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any()))
+        when(vnfCatalogArtifactHandlerMock.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any()))
                 .thenReturn(true);
-        when(mockModelArtifactHandler.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any()))
+        when(modelArtifactHandlerMock.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any()))
                 .thenReturn(true);
 
         assertThat(manager.deploy(data, modelArtifacts, catalogFiles), is(true));
 
-        Mockito.verify(mockVnfCatalogArtifactHandler).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()),
+        Mockito.verify(vnfCatalogArtifactHandlerMock).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()),
                 any(), any());
-        Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(),
+        Mockito.verify(modelArtifactHandlerMock).pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(),
                 any());
-        Mockito.verify(mockModelArtifactHandler, Mockito.never()).rollback(any(), any(), any());
-        Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(any(), any(), any());
+        Mockito.verify(modelArtifactHandlerMock, Mockito.never()).rollback(any(), any(), any());
+        Mockito.verify(vnfCatalogArtifactHandlerMock, Mockito.never()).rollback(any(), any(), any());
     }
 }
index f8b3de9..27d0aa9 100644 (file)
@@ -22,12 +22,11 @@ package org.onap.aai.modelloader.notification;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.collection.IsEmptyCollection.empty;
-import static org.junit.Assert.assertThat;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyList;
 import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithInvalidType;
 import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithModelQuerySpec;
@@ -39,19 +38,23 @@ import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
+
 import org.hamcrest.collection.IsEmptyCollection;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
 import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
 import org.onap.aai.babel.service.data.BabelArtifact;
-import org.onap.aai.modelloader.config.ModelLoaderConfig;
+import org.onap.aai.modelloader.babel.BabelArtifactService;
 import org.onap.aai.modelloader.entity.Artifact;
 import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException;
+import org.onap.aai.modelloader.extraction.VnfCatalogExtractor;
 import org.onap.aai.modelloader.restclient.BabelServiceClient;
 import org.onap.aai.modelloader.restclient.BabelServiceClientException;
 import org.onap.aai.modelloader.service.BabelServiceClientFactory;
-import org.onap.aai.modelloader.service.HttpsBabelServiceClientFactory;
 import org.onap.aai.modelloader.util.ArtifactTestUtils;
 import org.onap.sdc.api.IDistributionClient;
 import org.onap.sdc.api.notification.IArtifactInfo;
@@ -59,7 +62,6 @@ import org.onap.sdc.api.notification.INotificationData;
 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
 import org.onap.sdc.impl.DistributionClientDownloadResultImpl;
 import org.onap.sdc.utils.DistributionActionResultEnum;
-import org.springframework.test.util.ReflectionTestUtils;
 
 /**
  * Tests {@link ArtifactDownloadManager}.
@@ -67,31 +69,27 @@ import org.springframework.test.util.ReflectionTestUtils;
 public class TestArtifactDownloadManager {
 
     private ArtifactDownloadManager downloadManager;
-    private BabelServiceClient mockBabelClient;
-    private IDistributionClient mockDistributionClient;
-    private NotificationPublisher mockNotificationPublisher;
-    private BabelArtifactConverter mockBabelArtifactConverter;
-    private BabelServiceClientFactory mockClientFactory;
-
-    @Before
+    @Mock private BabelServiceClient mockBabelClient;
+    @Mock private IDistributionClient mockDistributionClient;
+    @Mock private NotificationPublisher mockNotificationPublisher;
+    @Mock private BabelArtifactConverter mockBabelArtifactConverter;
+    @Mock private BabelServiceClientFactory mockClientFactory;
+    @InjectMocks BabelArtifactService babelArtifactService;
+    private VnfCatalogExtractor vnfCatalogExtractor;
+
+    @BeforeEach
     public void setup() throws Exception {
-        mockBabelClient = mock(BabelServiceClient.class);
-        mockDistributionClient = mock(IDistributionClient.class);
-        mockNotificationPublisher = mock(NotificationPublisher.class);
-        mockBabelArtifactConverter = mock(BabelArtifactConverter.class);
-        mockClientFactory = mock(HttpsBabelServiceClientFactory.class);
+        MockitoAnnotations.openMocks(this);
+        vnfCatalogExtractor = new VnfCatalogExtractor();
         when(mockClientFactory.create(any())).thenReturn(mockBabelClient);
 
         Properties configProperties = new Properties();
         configProperties.load(this.getClass().getClassLoader().getResourceAsStream("model-loader.properties"));
         downloadManager = new ArtifactDownloadManager(mockDistributionClient,
-                new ModelLoaderConfig(configProperties, "."), mockClientFactory);
-
-        ReflectionTestUtils.setField(downloadManager, "notificationPublisher", mockNotificationPublisher);
-        ReflectionTestUtils.setField(downloadManager, "babelArtifactConverter", mockBabelArtifactConverter);
+                mockNotificationPublisher, vnfCatalogExtractor, babelArtifactService);
     }
 
-    @After
+    @AfterEach
     public void tearDown() {
         downloadManager = null;
         mockDistributionClient = null;
@@ -109,7 +107,7 @@ public class TestArtifactDownloadManager {
                 catalogFiles), is(true));
         assertThat(modelFiles, is(empty()));
         assertThat(catalogFiles, is(empty()));
-        Mockito.verifyZeroInteractions(mockBabelClient, mockDistributionClient, mockNotificationPublisher,
+        Mockito.verifyNoInteractions(mockBabelClient, mockDistributionClient, mockNotificationPublisher,
                 mockBabelArtifactConverter);
     }
 
@@ -129,7 +127,7 @@ public class TestArtifactDownloadManager {
         Mockito.verify(mockNotificationPublisher).publishDownloadFailure(mockDistributionClient, data, artifact,
                 errorMessage);
 
-        Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter);
+        Mockito.verifyNoInteractions(mockBabelClient, mockBabelArtifactConverter);
     }
 
     @Test
@@ -146,8 +144,6 @@ public class TestArtifactDownloadManager {
         Mockito.verify(mockDistributionClient).download(artifactInfo);
         Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo);
         Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo);
-
-        Mockito.verifyZeroInteractions(mockBabelArtifactConverter);
     }
 
     @Test
@@ -157,17 +153,17 @@ public class TestArtifactDownloadManager {
         when(mockDistributionClient.download(artifact)).thenReturn(createDistributionClientDownloadResult(
                 DistributionActionResultEnum.SUCCESS, null, "This is not a valid Tosca CSAR File".getBytes()));
         doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
-        when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenThrow(new BabelServiceClientException(""));
+        when(mockBabelClient.postArtifact(any(), any())).thenThrow(new BabelServiceClientException(""));
         doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact);
 
         assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null), is(false));
 
         Mockito.verify(mockDistributionClient).download(artifact);
         Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
-        Mockito.verify(mockBabelClient).postArtifact(any(), any(), any(), any());
+        Mockito.verify(mockBabelClient).postArtifact(any(), any());
         Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact);
 
-        Mockito.verifyZeroInteractions(mockBabelArtifactConverter);
+        Mockito.verifyNoInteractions(mockBabelArtifactConverter);
 
     }
 
@@ -189,7 +185,7 @@ public class TestArtifactDownloadManager {
         Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
         Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact);
 
-        Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter);
+        Mockito.verifyNoInteractions(mockBabelClient, mockBabelArtifactConverter);
     }
 
     @Test
@@ -208,7 +204,7 @@ public class TestArtifactDownloadManager {
 
         Mockito.verify(mockDistributionClient).download(artifactInfo);
         Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo);
-        Mockito.verify(mockBabelClient).postArtifact(any(), any(), any(), any());
+        Mockito.verify(mockBabelClient).postArtifact(any(), any());
         Mockito.verify(mockBabelArtifactConverter).convertToModel(any());
         Mockito.verify(mockBabelArtifactConverter).convertToCatalog(any());
     }
@@ -218,7 +214,7 @@ public class TestArtifactDownloadManager {
         when(mockDistributionClient.download(artifactInfo))
                 .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.SUCCESS, null,
                         artifactTestUtils.loadResource("compressedArtifacts/service-VscpaasTest-csar.csar")));
-        when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifacts());
+        when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifacts());
     }
 
     private List<BabelArtifact> createBabelArtifacts() {
@@ -246,7 +242,7 @@ public class TestArtifactDownloadManager {
         Mockito.verify(mockDistributionClient).download(artifact);
         Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
 
-        Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter);
+        Mockito.verifyNoInteractions(mockBabelClient, mockBabelArtifactConverter);
     }
 
     private void setupValidModelQuerySpecMocks(ArtifactTestUtils artifactTestUtils, INotificationData data,
@@ -279,7 +275,7 @@ public class TestArtifactDownloadManager {
 
         Mockito.verify(mockDistributionClient).download(serviceArtifact);
         Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, serviceArtifact);
-        Mockito.verify(mockBabelClient).postArtifact(any(), any(), any(), any());
+        Mockito.verify(mockBabelClient).postArtifact(any(), any());
         Mockito.verify(mockBabelArtifactConverter).convertToModel(any());
         Mockito.verify(mockBabelArtifactConverter).convertToCatalog(any());
 
@@ -302,7 +298,7 @@ public class TestArtifactDownloadManager {
         when(mockBabelArtifactConverter.convertToModel(anyList()))
                 .thenThrow(BabelArtifactParsingException.class);
         doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo);
-        when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifacts());
+        when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifacts());
 
         List<Artifact> modelArtifacts = new ArrayList<>();
         List<Artifact> catalogFiles = new ArrayList<>();
@@ -313,7 +309,7 @@ public class TestArtifactDownloadManager {
 
         Mockito.verify(mockDistributionClient).download(artifactInfo);
         Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo);
-        Mockito.verify(mockBabelClient).postArtifact(any(), any(), any(), any());
+        Mockito.verify(mockBabelClient).postArtifact(any(), any());
         Mockito.verify(mockBabelArtifactConverter).convertToModel(any());
     }
 
@@ -332,7 +328,7 @@ public class TestArtifactDownloadManager {
         Mockito.verify(mockDistributionClient).download(artifact);
         Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
         Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact);
-        Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter);
+        Mockito.verifyNoInteractions(mockBabelClient, mockBabelArtifactConverter);
     }
 
     private IDistributionClientDownloadResult createDistributionClientDownloadResult(
index 2a04ec5..1d81513 100644 (file)
  */
 package org.onap.aai.modelloader.notification;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
 import org.onap.aai.babel.service.data.BabelArtifact;
 import org.onap.aai.modelloader.entity.Artifact;
 import org.onap.aai.modelloader.entity.ArtifactType;
@@ -42,30 +44,34 @@ import org.onap.sdc.api.notification.INotificationData;
  */
 public class TestBabelArtifactConverter {
 
-    @Test(expected = NullPointerException.class)
+    @Test
     public void convert_nullToscaFiles() throws BabelArtifactParsingException {
-        new BabelArtifactConverter().convertToModel(null);
-        fail("An instance of ArtifactGenerationException should have been thrown");
+        assertThrows(NullPointerException.class, () -> {
+            new BabelArtifactConverter().convertToModel(null);
+            fail("An instance of ArtifactGenerationException should have been thrown");
+        });
     }
 
     @Test
     public void testEmptyToscaFiles() throws BabelArtifactParsingException {
-        assertTrue("Nothing should have been returned",
-                new BabelArtifactConverter().convertToModel(new ArrayList<>()).isEmpty());
+        assertTrue(new BabelArtifactConverter().convertToModel(new ArrayList<>()).isEmpty(),
+                "Nothing should have been returned");
     }
 
-    @Test(expected = BabelArtifactParsingException.class)
+    @Test
     public void testInvalidXml() throws IOException, BabelArtifactParsingException {
-        byte[] problemXml =
-                "<model xmlns=\"http://org.openecomp.aai.inventory/v10\"><rubbish>This is some xml that should cause the model artifact parser to throw an erorr</rubbish></model>"
-                        .getBytes();
+        assertThrows(BabelArtifactParsingException.class, () -> {
+            byte[] problemXml =
+                    "<model xmlns=\"http://org.openecomp.aai.inventory/v10\"><rubbish>This is some xml that should cause the model artifact parser to throw an erorr</rubbish></model>"
+                            .getBytes();
 
-        INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile();
+            INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile();
 
-        List<BabelArtifact> toscaArtifacts = setupTest(problemXml, data);
+            List<BabelArtifact> toscaArtifacts = setupTest(problemXml, data);
 
-        new BabelArtifactConverter().convertToModel(toscaArtifacts);
-        fail("An instance of ModelArtifactParsingException should have been thrown");
+            new BabelArtifactConverter().convertToModel(toscaArtifacts);
+            fail("An instance of ModelArtifactParsingException should have been thrown");
+        });
     }
 
     private List<BabelArtifact> setupTest(byte[] xml, INotificationData data) throws IOException {
@@ -88,7 +94,7 @@ public class TestBabelArtifactConverter {
 
         List<Artifact> modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts);
 
-        assertEquals("There should have been 1 artifact", 1, modelArtifacts.size());
+        assertEquals(1, modelArtifacts.size(), "There should have been 1 artifact");
         assertEquals(new String(xml), modelArtifacts.get(0).getPayload());
         assertEquals(ArtifactType.MODEL, modelArtifacts.get(0).getType());
     }
index 8276d90..1073a61 100644 (file)
 package org.onap.aai.modelloader.notification;
 
 import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import java.io.IOException;
 import java.util.List;
 import java.util.Properties;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
 import org.mockito.Mockito;
-import org.onap.aai.modelloader.config.ModelLoaderConfig;
+import org.mockito.MockitoAnnotations;
 import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException;
 import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder;
 import org.onap.aai.modelloader.service.ArtifactDeploymentManager;
 import org.onap.sdc.api.IDistributionClient;
 import org.onap.sdc.api.notification.INotificationData;
-import org.springframework.test.util.ReflectionTestUtils;
 
 /**
  * Tests {@link EventCallback}.
@@ -47,36 +47,25 @@ public class TestEventCallback {
 
     private static final String CONFIG_FILE = "model-loader.properties";
 
-    private ModelLoaderConfig config;
     private Properties configProperties;
     private EventCallback eventCallback;
 
-    private ArtifactDeploymentManager mockArtifactDeploymentManager;
-    private ArtifactDownloadManager mockArtifactDownloadManager;
-    private IDistributionClient mockDistributionClient;
-    private NotificationPublisher mockNotificationPublisher;
+    @Mock private ArtifactDeploymentManager mockArtifactDeploymentManager;
+    @Mock private ArtifactDownloadManager mockArtifactDownloadManager;
+    @Mock private IDistributionClient mockDistributionClient;
+    @Mock private NotificationPublisher mockNotificationPublisher;
 
-    @Before
+    @BeforeEach
     public void setup() throws IOException {
+        MockitoAnnotations.openMocks(this);
         configProperties = new Properties();
         configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE));
-        config = new ModelLoaderConfig(configProperties, null);
-
-        mockArtifactDeploymentManager = mock(ArtifactDeploymentManager.class);
-        mockArtifactDownloadManager = mock(ArtifactDownloadManager.class);
-        mockDistributionClient = mock(IDistributionClient.class);
-        mockNotificationPublisher = mock(NotificationPublisher.class);
-
-        eventCallback = new EventCallback(mockDistributionClient, config, null);
 
-        ReflectionTestUtils.setField(eventCallback, "artifactDeploymentManager", mockArtifactDeploymentManager);
-        ReflectionTestUtils.setField(eventCallback, "artifactDownloadManager", mockArtifactDownloadManager);
-        ReflectionTestUtils.setField(eventCallback, "notificationPublisher", mockNotificationPublisher);
+        eventCallback = new EventCallback(mockDistributionClient, mockArtifactDeploymentManager, mockArtifactDownloadManager, mockNotificationPublisher);
     }
 
-    @After
+    @AfterEach
     public void tearDown() {
-        config = null;
         configProperties = null;
         eventCallback = null;
         mockArtifactDeploymentManager = null;
@@ -96,7 +85,7 @@ public class TestEventCallback {
 
         verify(mockArtifactDownloadManager).downloadArtifacts(any(INotificationData.class), any(List.class),
                 any(List.class), any(List.class));
-        Mockito.verifyZeroInteractions(mockArtifactDeploymentManager);
+        Mockito.verifyNoInteractions(mockArtifactDeploymentManager);
     }
 
     @SuppressWarnings("unchecked")
diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java b/src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java
deleted file mode 100644 (file)
index c045910..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright Â© 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Copyright Â© 2017-2018 European Software Marketing Ltd.
- * ================================================================================
- * 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.onap.aai.modelloader.notification;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-
-/**
- * Tests for NotificationDataImpl class
- *
- */
-public class TestNotificationDataImpl {
-
-    @Test
-    public void testGettersAndSetters() {
-        NotificationDataImpl data = new NotificationDataImpl();
-        String distributionId = "testid";
-
-        data.setDistributionID(distributionId);
-        assertThat(data.getDistributionID(), is(equalTo(distributionId)));
-
-        // Getters return empty data
-        assertThat(data.getArtifactMetadataByUUID(null), is(equalTo(null)));
-        assertThat(data.getServiceDescription(), is(equalTo(null)));
-        assertThat(data.getServiceInvariantUUID(), is(equalTo(null)));
-        assertThat(data.getServiceName(), is(equalTo(null)));
-        assertThat(data.getServiceUUID(), is(equalTo(null)));
-        assertThat(data.getServiceVersion(), is(equalTo(null)));
-        assertThat(data.getResources().size(), is(0));
-        assertThat(data.getServiceArtifacts().size(), is(0));
-
-        // Unsupported method!
-        String context = "testcontext";
-        data.setWorkloadContext(context);
-        assertThat(data.getWorkloadContext(), is(equalTo(null)));
-    }
-
-
-    @Test
-    public void testEquality() {
-        NotificationDataImpl data = new NotificationDataImpl();
-        assertThat(data, is(not(equalTo(null))));
-        assertThat(data, is(not(equalTo("")))); // NOSONAR
-        assertThat(data, is(equalTo(data)));
-
-        NotificationDataImpl other = new NotificationDataImpl();
-        assertThat(data, is(equalTo(other)));
-        assertThat(data.hashCode(), is(equalTo(other.hashCode())));
-
-        other.setDistributionID("");
-        assertThat(data, is(not(equalTo(other))));
-
-        data.setDistributionID("1234");
-        assertThat(data, is(not(equalTo(other))));
-
-        other.setDistributionID("1234");
-        assertThat(data, is(equalTo(other)));
-        assertThat(data.hashCode(), is(equalTo(other.hashCode())));
-    }
-
-}
index 253fc17..c4aa932 100644 (file)
  */
 package org.onap.aai.modelloader.notification;
 
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.when;
 
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.onap.sdc.api.IDistributionClient;
@@ -61,9 +61,9 @@ public class TestNotificationPublisher {
         System.setProperty("CONFIG_HOME", "src/test/resources");
     }
 
-    @Before
+    @BeforeEach
     public void setupMocks() {
-        MockitoAnnotations.initMocks(this);
+        MockitoAnnotations.openMocks(this);
         when(client.getConfiguration()).thenReturn(config);
         when(client.sendDownloadStatus(any())).thenReturn(clientResult);
         when(client.sendComponentDoneStatus(any())).thenReturn(clientResult);
index 604aca7..783ad2e 100644 (file)
@@ -23,6 +23,7 @@ package org.onap.aai.modelloader.restclient;
 import java.util.Collections;
 import java.util.List;
 import org.onap.aai.babel.service.data.BabelArtifact;
+import org.onap.aai.babel.service.data.BabelRequest;
 import org.onap.aai.modelloader.config.ModelLoaderConfig;
 
 /**
@@ -34,8 +35,8 @@ public class MockBabelServiceClient implements BabelServiceClient {
     public MockBabelServiceClient(ModelLoaderConfig config) throws BabelServiceClientException {}
 
     @Override
-    public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
-            String transactionId) throws BabelServiceClientException {
+    public List<BabelArtifact> postArtifact(BabelRequest babelRequest, String transactionId)
+            throws BabelServiceClientException {
         return Collections.emptyList();
     }
 }
index 91aa182..37b7e12 100644 (file)
@@ -20,8 +20,7 @@
  */
 package org.onap.aai.modelloader.restclient;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 import java.io.File;
 import java.io.IOException;
@@ -30,9 +29,11 @@ import java.nio.file.Paths;
 import java.util.Properties;
 import java.util.stream.IntStream;
 import java.util.stream.Stream;
+
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.xml.parsers.DocumentBuilderFactory;
+
 import org.onap.aai.modelloader.config.ModelLoaderConfig;
 import org.onap.aai.modelloader.entity.ArtifactType;
 import org.onap.aai.modelloader.entity.model.ModelArtifact;
index 00bee09..18753b1 100644 (file)
@@ -22,21 +22,24 @@ package org.onap.aai.modelloader.restclient;
 
 import static javax.servlet.http.HttpServletResponse.SC_OK;
 import static org.apache.commons.io.IOUtils.write;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.IOException;
+import java.nio.charset.Charset;
 import java.util.Properties;
+
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.ws.rs.core.MediaType;
+
 import org.eclipse.jetty.server.Handler;
 import org.eclipse.jetty.server.Request;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.handler.AbstractHandler;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.onap.aai.modelloader.config.ModelLoaderConfig;
 
 /**
@@ -48,19 +51,21 @@ public class TestAaiServiceClient {
     private Server server;
     private AaiRestClient aaiClient;
 
-    @Before
+    @BeforeEach
     public void startJetty() throws Exception {
-        server = new Server(8080);
+        server = new Server(0);
         server.setHandler(getMockHandler());
         server.start();
 
         Properties props = new Properties();
         props.put("ml.aai.KEYSTORE_PASSWORD", "2244");
+        props.put("ml.aai.RESTCLIENT_CONNECT_TIMEOUT", "3000");
+        props.put("ml.aai.RESTCLIENT_READ_TIMEOUT", "3000");
         ModelLoaderConfig config = new ModelLoaderConfig(props, ".");
         aaiClient = new AaiRestClient(config);
     }
 
-    @After
+    @AfterEach
     public void stopJetty() throws Exception {
         server.stop();
     }
@@ -75,11 +80,11 @@ public class TestAaiServiceClient {
 
     @Test
     public void testOperations() {
-        String url = "http://localhost:8080";
+        String url = server.getURI().toString();
         String transId = "";
         MediaType mediaType = MediaType.APPLICATION_JSON_TYPE;
         aaiClient.getResource(url, "", mediaType);
-        aaiClient.deleteResource("http://localhost", transId, "");
+        aaiClient.deleteResource(url, "", transId);
         aaiClient.getAndDeleteResource(url, transId);
         aaiClient.postResource(url, "", transId, mediaType);
         aaiClient.putResource(url, "", transId, mediaType);
@@ -99,7 +104,7 @@ public class TestAaiServiceClient {
                     HttpServletResponse response) throws IOException, ServletException {
                 response.setStatus(SC_OK);
                 response.setContentType("text/json;charset=utf-8");
-                write("", response.getOutputStream());
+                write("", response.getOutputStream(), Charset.defaultCharset());
                 request.setHandled(true);
             }
         };
index 8da5f89..d82bff0 100644 (file)
  */
 package org.onap.aai.modelloader.restclient;
 
-import static javax.servlet.http.HttpServletResponse.SC_OK;
-import static org.apache.commons.io.IOUtils.write;
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
 
-import com.google.gson.Gson;
 import java.io.IOException;
 import java.net.URISyntaxException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
-import java.util.ArrayList;
+import java.util.Base64;
 import java.util.List;
-import java.util.Properties;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import org.eclipse.jetty.server.Handler;
-import org.eclipse.jetty.server.Request;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.handler.AbstractHandler;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 import org.onap.aai.babel.service.data.BabelArtifact;
-import org.onap.aai.modelloader.config.ModelLoaderConfig;
-import org.onap.aai.modelloader.service.HttpsBabelServiceClientFactory;
+import org.onap.aai.babel.service.data.BabelRequest;
+import org.onap.aai.modelloader.BabelClientTestConfiguration;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
+import org.springframework.context.annotation.Import;
+import org.springframework.test.annotation.DirtiesContext;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.tomakehurst.wiremock.client.WireMock;
 
 /**
  * Local testing of the Babel service client.
  *
  */
+@SpringBootTest
+@DirtiesContext
+@AutoConfigureWireMock(port = 0)
+@Import(BabelClientTestConfiguration.class)
 public class TestBabelServiceClient {
 
-    private Server server;
-    private String responseBody;
+    @Value("${wiremock.server.port}")
+    private int wiremockPort;
 
-    @Before
-    public void startJetty() throws Exception {
-        List<BabelArtifact> response = new ArrayList<>();
-        response.add(new BabelArtifact("", null, ""));
-        response.add(new BabelArtifact("", null, ""));
-        response.add(new BabelArtifact("", null, ""));
-        responseBody = new Gson().toJson(response);
+    @Autowired BabelServiceClient client;
 
-        server = new Server(8080);
-        server.setHandler(getMockHandler());
-        server.start();
-    }
-
-    @After
-    public void stopJetty() throws Exception {
-        server.stop();
+    @BeforeAll
+    public static void setup() throws JsonProcessingException {
+        ObjectMapper objectMapper = new ObjectMapper();
+        List<BabelArtifact> artifacts = List.of(
+            new BabelArtifact("art1", null, ""),
+            new BabelArtifact("art2", null, ""),
+            new BabelArtifact("art3", null, ""));
+        WireMock.stubFor(
+            WireMock.post(WireMock.urlEqualTo("/services/babel-service/v1/app/generateArtifacts"))
+                .withHeader("X-TransactionId", WireMock.equalTo("Test-Transaction-ID-BabelClient"))
+                .withHeader("X-FromAppId", WireMock.equalTo("ModelLoader"))
+                .withRequestBody(WireMock.matchingJsonPath("$.artifactName", WireMock.equalTo("service-Vscpass-Test")))
+                .withRequestBody(WireMock.matchingJsonPath("$.artifactVersion", WireMock.equalTo("1.0")))
+                .withRequestBody(WireMock.matchingJsonPath("$.csar", WireMock.matching(".*")))
+                .willReturn(
+                    WireMock.aResponse()
+                        .withHeader("Content-Type", "application/json")
+                        .withBody(objectMapper.writeValueAsString(artifacts))));
     }
 
     @Test
     public void testRestClient() throws BabelServiceClientException, IOException, URISyntaxException {
-        Properties configProperties = new Properties();
-        configProperties.put("ml.babel.KEYSTORE_PASSWORD", "OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0");
-        configProperties.put("ml.babel.KEYSTORE_FILE", "src/test/resources/auth/aai-client-dummy.p12");
-        configProperties.put("ml.babel.TRUSTSTORE_PASSWORD", "OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0");
-        // In a real deployment this would be a different file (to the client keystore)
-        configProperties.put("ml.babel.TRUSTSTORE_FILE", "src/test/resources/auth/aai-client-dummy.p12");
-        configProperties.put("ml.babel.BASE_URL", "http://localhost:8080/");
-        configProperties.put("ml.babel.GENERATE_ARTIFACTS_URL", "generate");
-        BabelServiceClient client =
-                new HttpsBabelServiceClientFactory().create(new ModelLoaderConfig(configProperties, "."));
-        List<BabelArtifact> result =
-                client.postArtifact(readBytesFromFile("compressedArtifacts/service-VscpaasTest-csar.csar"),
-                        "service-Vscpass-Test", "1.0", "Test-Transaction-ID-BabelClient");
-        assertThat(result.size(), is(equalTo(3)));
-    }
+        BabelRequest babelRequest = new BabelRequest();
+        babelRequest.setArtifactName("service-Vscpass-Test");
+        babelRequest.setCsar(Base64.getEncoder().encodeToString(readBytesFromFile("compressedArtifacts/service-VscpaasTest-csar.csar")));
+        babelRequest.setArtifactVersion("1.0");
 
-    @Test
-    public void testRestClientHttp() throws BabelServiceClientException, IOException, URISyntaxException {
-        Properties configProperties = new Properties();
-        configProperties.put("ml.babel.USE_HTTPS", "false");
-        configProperties.put("ml.babel.BASE_URL", "http://localhost:8080/");
-        configProperties.put("ml.babel.GENERATE_ARTIFACTS_URL", "generate");
-        BabelServiceClient client =
-                new HttpsBabelServiceClientFactory().create(new ModelLoaderConfig(configProperties, "."));
         List<BabelArtifact> result =
-                client.postArtifact(readBytesFromFile("compressedArtifacts/service-VscpaasTest-csar.csar"),
-                        "service-Vscpass-Test", "1.0", "Test-Transaction-ID-BabelClient");
+                client.postArtifact(babelRequest, "Test-Transaction-ID-BabelClient");
         assertThat(result.size(), is(equalTo(3)));
     }
 
@@ -111,23 +98,4 @@ public class TestBabelServiceClient {
     private byte[] readBytesFromFile(String resourceFile) throws IOException, URISyntaxException {
         return Files.readAllBytes(Paths.get(ClassLoader.getSystemResource(resourceFile).toURI()));
     }
-
-    /**
-     * Creates an {@link AbstractHandler handler} returning an arbitrary String as a response.
-     * 
-     * @return never <code>null</code>.
-     */
-    private Handler getMockHandler() {
-        Handler handler = new AbstractHandler() {
-            @Override
-            public void handle(String target, Request request, HttpServletRequest servletRequest,
-                    HttpServletResponse response) throws IOException, ServletException {
-                response.setStatus(SC_OK);
-                response.setContentType("text/xml;charset=utf-8");
-                write(responseBody, response.getOutputStream());
-                request.setHandled(true);
-            }
-        };
-        return handler;
-    }
 }
diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TracingTest.java b/src/test/java/org/onap/aai/modelloader/restclient/TracingTest.java
new file mode 100644 (file)
index 0000000..3bfceb5
--- /dev/null
@@ -0,0 +1,63 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright Â© 2024 Deutsche Telekom AG Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.onap.aai.modelloader.restclient;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.client.RestTemplate;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+
+@SpringBootTest(properties = {
+  "spring.sleuth.enabled=true",
+  "spring.zipkin.baseUrl=http://localhost:${wiremock.server.port}"
+})
+@AutoConfigureWireMock(port = 0)
+public class TracingTest {
+
+  @Value("${wiremock.server.port}")
+  private int wiremockPort;
+
+  @Autowired RestTemplate restTemplate;
+  
+  @Test
+  public void thatArtifactsCanBePushed() {
+    WireMock.stubFor(
+      WireMock.post(WireMock.urlEqualTo("/api/v2/spans"))
+          .willReturn(
+              WireMock.aResponse()
+                  .withStatus(HttpStatus.OK.value())));
+
+    WireMock.stubFor(
+      WireMock.get(WireMock.urlEqualTo("/"))
+          .withHeader("X-B3-TraceId", WireMock.matching(".*"))
+          .willReturn(
+              WireMock.aResponse()
+                  .withStatus(HttpStatus.OK.value())));
+
+
+    String response = restTemplate.getForObject("http://localhost:" + wiremockPort + "/", String.class);
+  }
+  
+}
diff --git a/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java b/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java
deleted file mode 100644 (file)
index ec55f15..0000000
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright Â© 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Copyright Â© 2017-2018 European Software Marketing Ltd.
- * ================================================================================
- * 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.onap.aai.modelloader.service;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.Matchers.empty;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-
-/**
- * Tests for NotificationDataImpl class
- *
- */
-public class TestArtifactInfoImpl {
-
-    @Test
-    public void testGettersAndSetters() {
-        ArtifactInfoImpl info = new ArtifactInfoImpl();
-        String artifactName = "testname";
-
-        info.setArtifactName(artifactName);
-        assertThat(info.getArtifactName(), is(equalTo(artifactName)));
-
-        String artifactType = "test-type";
-        info.setArtifactType(artifactType);
-        assertThat(info.getArtifactType(), is(equalTo(artifactType)));
-
-        String artifactVersion = "v1";
-        info.setArtifactVersion(artifactVersion);
-        assertThat(info.getArtifactVersion(), is(equalTo(artifactVersion)));
-
-        String artifactDescription = "test description";
-        info.setArtifactDescription(artifactDescription);
-        assertThat(info.getArtifactDescription(), is(equalTo(artifactDescription)));
-
-        assertThat(info.getArtifactChecksum(), is(nullValue()));
-        assertThat(info.getArtifactTimeout(), is(nullValue()));
-        assertThat(info.getArtifactURL(), is(nullValue()));
-        assertThat(info.getArtifactUUID(), is(nullValue()));
-        assertThat(info.getGeneratedArtifact(), is(nullValue()));
-        assertThat(info.getRelatedArtifacts(), is(empty()));
-    }
-
-
-    @Test
-    public void testEquality() {
-        ArtifactInfoImpl info = new ArtifactInfoImpl();
-        assertThat(info, is(not(equalTo(null))));
-        assertThat(info, is(not(equalTo("")))); // NOSONAR
-        assertThat(info, is(equalTo(info)));
-
-        ArtifactInfoImpl other = new ArtifactInfoImpl();
-        assertThat(info, is(equalTo(other)));
-        assertThat(info.hashCode(), is(equalTo(other.hashCode())));
-
-        // Artifact Name
-        other.setArtifactName("");
-        assertThat(info, is(not(equalTo(other))));
-
-        info.setArtifactName("1234");
-        assertThat(info, is(not(equalTo(other))));
-
-        other.setArtifactName("1234");
-        assertThat(info, is(equalTo(other)));
-        assertThat(info.hashCode(), is(equalTo(other.hashCode())));
-
-        // Artifact Type
-        other.setArtifactType("");
-        assertThat(info, is(not(equalTo(other))));
-
-        info.setArtifactType("type");
-        assertThat(info, is(not(equalTo(other))));
-
-        other.setArtifactType("type");
-        assertThat(info, is(equalTo(other)));
-        assertThat(info.hashCode(), is(equalTo(other.hashCode())));
-
-        // Artifact Description
-        other.setArtifactDescription("");
-        assertThat(info, is(not(equalTo(other))));
-
-        info.setArtifactDescription("type");
-        assertThat(info, is(not(equalTo(other))));
-
-        other.setArtifactDescription("type");
-        assertThat(info, is(equalTo(other)));
-        assertThat(info.hashCode(), is(equalTo(other.hashCode())));
-
-        // Artifact Version
-        other.setArtifactVersion("");
-        assertThat(info, is(not(equalTo(other))));
-
-        info.setArtifactVersion("v1");
-        assertThat(info, is(not(equalTo(other))));
-
-        other.setArtifactVersion("v1");
-        assertThat(info, is(equalTo(other)));
-        assertThat(info.hashCode(), is(equalTo(other.hashCode())));
-    }
-
-}
 package org.onap.aai.modelloader.service;
 
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
 
 import java.io.IOException;
 import java.util.Base64;
+import java.util.Collections;
+
 import javax.ws.rs.core.Response;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.onap.aai.modelloader.babel.BabelArtifactService;
+import org.onap.aai.modelloader.config.ModelLoaderConfig;
+import org.onap.aai.modelloader.extraction.VnfCatalogExtractor;
+import org.onap.aai.modelloader.notification.ArtifactDownloadManager;
+import org.onap.aai.modelloader.notification.BabelArtifactConverter;
+import org.onap.aai.modelloader.notification.NotificationPublisher;
+import org.onap.aai.modelloader.restclient.BabelServiceClient;
+import org.onap.aai.modelloader.restclient.BabelServiceClientException;
 import org.onap.aai.modelloader.util.ArtifactTestUtils;
+import org.onap.sdc.api.IDistributionClient;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
 
 /**
  * Tests for the ModelLoaderService class.
  *
  */
-@RunWith(SpringRunner.class)
-@SpringBootTest(classes = {ModelLoaderService.class, MockBabelServiceClientFactory.class})
+@SpringBootTest
 @TestPropertySource(properties = {"CONFIG_HOME=src/test/resources",})
-public class TestModelLoaderService {
+public class TestModelController {
 
-    @Autowired
-    private ModelLoaderService service;
+    @Autowired IDistributionClient iDistributionClient;
+    @Autowired ModelLoaderConfig modelLoaderConfig;
+    @Autowired ArtifactDeploymentManager artifactDeploymentManager;
+    @Autowired BabelArtifactConverter babelArtifactConverter;
+    @Autowired NotificationPublisher notificationPublisher;
+    @Autowired VnfCatalogExtractor vnfCatalogExtractor;
 
-    @After
-    public void shutdown() {
-        service.preShutdownOperations();
-    }
+    @Mock BabelServiceClientFactory clientFactory;
+    @Mock BabelServiceClient babelServiceClient;
+    @InjectMocks BabelArtifactService babelArtifactService;
+    
+    private ModelController modelController;
 
-    @Test
-    public void testMissingConfig() {
-        new ModelLoaderService().start();
-        assertTrue(true);
+    @BeforeEach
+    public void init() throws BabelServiceClientException {
+        when(clientFactory.create(any())).thenReturn(babelServiceClient);
+        when(babelServiceClient.postArtifact(any(), any())).thenReturn(Collections.emptyList());
+        ArtifactDownloadManager artifactDownloadManager = new ArtifactDownloadManager(iDistributionClient, notificationPublisher, vnfCatalogExtractor, babelArtifactService);
+        this.modelController = new ModelController(iDistributionClient, modelLoaderConfig, artifactDeploymentManager, artifactDownloadManager);
     }
 
     @Test
     public void testLoadModel() {
-        Response response = service.loadModel("");
+        Response response = modelController.loadModel("");
         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
     }
 
     @Test
     public void testSaveModel() {
-        Response response = service.saveModel("", "");
+        Response response = modelController.saveModel("", "");
         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
     }
 
     @Test
     public void testIngestModel() throws IOException {
         byte[] csarPayload = new ArtifactTestUtils().loadResource("compressedArtifacts/service-VscpaasTest-csar.csar");
-        Response response = service.ingestModel("model-name", "", Base64.getEncoder().encodeToString(csarPayload));
+        Response response = modelController.ingestModel("model-name", "", Base64.getEncoder().encodeToString(csarPayload));
         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
     }
 
     @Test
     public void testIngestModelMissingName() throws IOException {
         byte[] csarPayload = new ArtifactTestUtils().loadResource("compressedArtifacts/service-VscpaasTest-csar.csar");
-        Response response = service.ingestModel("", "", Base64.getEncoder().encodeToString(csarPayload));
+        Response response = modelController.ingestModel("", "", Base64.getEncoder().encodeToString(csarPayload));
         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
     }
 
index d23b3ef..6dc1b3d 100644 (file)
 package org.onap.aai.modelloader.service;
 
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
 
 import java.io.IOException;
 import java.util.Base64;
+
 import javax.ws.rs.core.Response;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+
+import org.junit.jupiter.api.Test;
 import org.onap.aai.modelloader.util.ArtifactTestUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
 
 /**
  * Tests for the ModelLoaderService class.
  *
  */
-@RunWith(SpringRunner.class)
-@SpringBootTest(classes = {ModelLoaderService.class, HttpsBabelServiceClientFactory.class})
+@SpringBootTest
 @TestPropertySource(properties = {"CONFIG_HOME=src/test/resources",})
 public class TestModelLoaderServiceWithSdc {
 
     @Autowired
-    private ModelLoaderService service;
-
-    @After
-    public void shutdown() {
-        service.preShutdownOperations();
-    }
+    private ModelController controller;
 
     @Test
     public void testIngestModel() throws IOException {
         byte[] csarPayload = new ArtifactTestUtils().loadResource("compressedArtifacts/service-VscpaasTest-csar.csar");
-        Response response = service.ingestModel("model-name", "", Base64.getEncoder().encodeToString(csarPayload));
+        Response response = controller.ingestModel("model-name", "", Base64.getEncoder().encodeToString(csarPayload));
         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
     }
 
index 50074f1..e5db2a5 100644 (file)
@@ -22,6 +22,8 @@ package org.onap.aai.modelloader.util;
 
 import java.io.IOException;
 import java.net.URL;
+import java.nio.charset.Charset;
+
 import org.apache.commons.io.IOUtils;
 import org.onap.aai.babel.service.data.BabelArtifact;
 
@@ -53,7 +55,7 @@ public class ArtifactTestUtils {
     }
 
     public static String loadResourceAsString(String resourceName) throws IOException {
-        return IOUtils.toString(getResource(resourceName));
+        return IOUtils.toString(getResource(resourceName), Charset.defaultCharset());
     }
 
     private static URL getResource(String resourceName) {
index 97d7a19..c1a862a 100644 (file)
 package org.onap.aai.modelloader.util;
 
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
 import org.onap.aai.modelloader.gizmo.GizmoBulkPayload;
 
 public class TestGizmoTranslator {
 
-    @Test(expected = IOException.class)
+    @Test
     public void translateInvalidXml() throws IOException {
-        GizmoTranslator.translate("not valid XML");
+        assertThrows(IOException.class, () -> {
+            GizmoTranslator.translate("not valid XML");
+        });
     }
 
     @Test
index 81a4833..ec66a59 100644 (file)
 package org.onap.aai.modelloader.util;
 
 import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
 
 import java.io.ByteArrayInputStream;
 import java.nio.file.Files;
 import java.nio.file.Paths;
+
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
diff --git a/src/test/resources/__files/artifactTypes.json b/src/test/resources/__files/artifactTypes.json
new file mode 100644 (file)
index 0000000..de3cfce
--- /dev/null
@@ -0,0 +1,63 @@
+[
+  "AAI_SERVICE_MODEL",
+  "AAI_VF_INSTANCE_MODEL",
+  "AAI_VF_MODEL",
+  "AAI_VF_MODULE_MODEL",
+  "ANSIBLE_PLAYBOOK",
+  "APPC_CONFIG",
+  "BPEL",
+  "CHEF",
+  "CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT",
+  "CONTROLLER_BLUEPRINT_ARCHIVE",
+  "DCAE_DOC",
+  "DCAE_EVENT",
+  "DCAE_INVENTORY_BLUEPRINT",
+  "DCAE_INVENTORY_DOC",
+  "DCAE_INVENTORY_EVENT",
+  "DCAE_INVENTORY_JSON",
+  "DCAE_INVENTORY_POLICY",
+  "DCAE_INVENTORY_TOSCA",
+  "DCAE_JSON",
+  "DCAE_POLICY",
+  "DCAE_TOSCA",
+  "DG_XML",
+  "ETSI_PACKAGE",
+  "ASD_PACKAGE",
+  "GUIDE",
+  "HEAT_ARTIFACT",
+  "HEAT_ENV",
+  "HEAT",
+  "HEAT_NESTED",
+  "HEAT_NET",
+  "HEAT_VOL",
+  "HELM",
+  "ICON",
+  "LIFECYCLE_OPERATIONS",
+  "MODEL_INVENTORY_PROFILE",
+  "MODEL_QUERY_SPEC",
+  "MURANO_PKG",
+  "NETWORK_CALL_FLOW",
+  "ONBOARDED_PACKAGE",
+  "OTHER",
+  "PERFORMANCE_COUNTER",
+  "PLAN",
+  "PM_DICTIONARY",
+  "PNF_SW_INFORMATION",
+  "PUPPET",
+  "SHELL_SCRIPT",
+  "SHELL",
+  "SNMP_POLL",
+  "SNMP_TRAP",
+  "TOSCA_CSAR",
+  "TOSCA_TEMPLATE",
+  "UCPE_LAYER_2_CONFIGURATION",
+  "VENDOR_LICENSE",
+  "VES_EVENTS",
+  "VF_LICENSE",
+  "VF_MODULES_METADATA",
+  "VNF_CATALOG",
+  "WORKFLOW",
+  "YANG_MODULE",
+  "YANG_XML",
+  "YANG"
+]
\ No newline at end of file
diff --git a/src/test/resources/__files/kafkaBootstrap.json b/src/test/resources/__files/kafkaBootstrap.json
new file mode 100644 (file)
index 0000000..1820ade
--- /dev/null
@@ -0,0 +1,5 @@
+{
+  "kafkaBootStrapServer": "localhost:9092",
+  "distrNotificationTopicName": "SDC-DISTR-NOTIF-TOPIC-AUTO",
+  "distrStatusTopicName": "SDC-DISTR-STATUS-TOPIC-AUTO"
+}
\ No newline at end of file
diff --git a/src/test/resources/__files/modelResponse.xml b/src/test/resources/__files/modelResponse.xml
new file mode 100644 (file)
index 0000000..36d07d8
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<model xmlns="http://org.onap.aai.inventory/v28">
+  <model-invariant-id>3a40ab73-6694-4e75-bb6d-9a4a86ce35b3</model-invariant-id>
+  <model-type>service</model-type>
+  <model-role>Network Service</model-role>
+  <resource-version>1710523260974</resource-version>
+</model>
\ No newline at end of file
diff --git a/src/test/resources/__files/service-TestSvc-csar-babel-response.json b/src/test/resources/__files/service-TestSvc-csar-babel-response.json
new file mode 100644 (file)
index 0000000..7103156
--- /dev/null
@@ -0,0 +1 @@
+[{"name":"AAI-test-svc-service-2.0.xml","type":"MODEL","payload":"<model xmlns=\"http://org.onap.aai.inventory/v28\">\n    <model-invariant-id>3c8bc8e7-e387-46ed-8616-70e99e2206dc</model-invariant-id>\n    <model-type>service</model-type>\n    <model-role>Network L1-3</model-role>\n    <model-vers>\n        <model-ver>\n            <model-version-id>71f47717-b100-4eac-940b-7d4e86a4cbb7</model-version-id>\n            <model-name>test-svc</model-name>\n            <model-version>2.0</model-version>\n            <model-description>test-svc</model-description>\n            <model-elements>\n                <model-element>\n                    <new-data-del-flag>T</new-data-del-flag>\n                    <cardinality>unbounded</cardinality>\n                    <model-elements/>\n                    <relationship-list>\n                        <relationship>\n                            <related-to>model-ver</related-to>\n                            <relationship-data>\n                                <relationship-key>model-ver.model-version-id</relationship-key>\n                                <relationship-value>46b92144-923a-4d20-b85a-3cbd847668a9</relationship-value>\n                            </relationship-data>\n                            <relationship-data>\n                                <relationship-key>model.model-invariant-id</relationship-key>\n                                <relationship-value>82194af1-3c2c-485a-8f44-420e22a9eaa4</relationship-value>\n                            </relationship-data>\n                        </relationship>\n                    </relationship-list>\n                </model-element>\n            </model-elements>\n        </model-ver>\n    </model-vers>\n</model>"}]
\ No newline at end of file
diff --git a/src/test/resources/__files/service-TestSvc-csar.csar b/src/test/resources/__files/service-TestSvc-csar.csar
new file mode 100644 (file)
index 0000000..711f068
Binary files /dev/null and b/src/test/resources/__files/service-TestSvc-csar.csar differ
diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties
new file mode 100644 (file)
index 0000000..69f4ff7
--- /dev/null
@@ -0,0 +1,11 @@
+CONFIG_HOME=src/test/resources
+spring.kafka.consumer.auto-offset-reset=earliest
+spring.kafka.consumer.group-id=aai
+spring.kafka.consumer.client-id=aai-model-loader   
+topics.distribution.notification=SDC-DISTR-NOTIF-TOPIC-AUTO
+
+spring.sleuth.enabled=false
+
+ml.distribution.connection.enabled=false # avoid having the distribution client running in the background (requires active kafka)
+
+spring.main.allow-bean-definition-overriding=true
\ No newline at end of file
index aef38e6..4bf73da 100644 (file)
@@ -11,7 +11,7 @@
                <appender-ref ref="STDOUT" />
        </logger>
 
-       <root level="debug">
+       <root level="INFO">
                <appender-ref ref="STDOUT" />
        </root>
 </configuration>
index 51a38c5..2db7c09 100644 (file)
@@ -1,16 +1,20 @@
 # Model Loader Distribution Client Configuration
 ml.distribution.ACTIVE_SERVER_TLS_AUTH=false
 ml.distribution.ASDC_ADDRESS=localhost:8443
+ml.distribution.ASDC_USE_HTTPS=false
 ml.distribution.CONSUMER_GROUP=aai-ml-group-test
 ml.distribution.CONSUMER_ID=aai-ml-id-test
-ml.distribution.ENVIRONMENT_NAME=env
+ml.distribution.ENVIRONMENT_NAME=AUTO
 ml.distribution.KEYSTORE_PASSWORD=
 ml.distribution.KEYSTORE_FILE=
 ml.distribution.PASSWORD=Aa123456
-ml.distribution.POLLING_INTERVAL=30
-ml.distribution.POLLING_TIMEOUT=20
+ml.distribution.POLLING_INTERVAL=15
+ml.distribution.POLLING_TIMEOUT=3
 ml.distribution.USER=ci
 ml.distribution.ARTIFACT_TYPES=MODEL_QUERY_SPEC,TOSCA_CSAR
+ml.distribution.SASL_JAAS_CONFIG=org.apache.kafka.common.security.scram.ScramLoginModule required username="aai-modelloader-ku" password="somePassword";
+ml.distribution.SECURITY_PROTOCOL=PLAINTEXT
+ml.distribution.SASL_MECHANISM=PLAIN
 
 # Disable ASDC polling & enable REST interface
 ml.distribution.ASDC_CONNECTION_DISABLE=true
index 78f179d..b2aac49 100644 (file)
@@ -24,8 +24,8 @@
 # because they are used in Jenkins, whose plug-in doesn't support
 
 major=1
-minor=12
-patch=0
+minor=13
+patch=6
 
 base_version=${major}.${minor}.${patch}