.checkstyle
.idea/
*.iml
+.vscode
\ No newline at end of file
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:
- 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'
<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>
<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>
--- /dev/null
+distribution_type: container
+container_release_tag: 1.13.5
+project: model-loader
+ref: ba282826d84f17e3156de99c39e6b1d50813f8ba
+containers:
+ - name: model-loader
+ version: 1.13-STAGING-20240326T082727Z
--- /dev/null
+distribution_type: maven
+log_dir: aai-model-loader-maven-stage-master/1396/
+project: model-loader
+version: 1.13.5
--- /dev/null
+distribution_type: container
+container_release_tag: 1.13.6
+project: model-loader
+ref: df2ad94ee9b641a4c2c19969816a6275f6d056e3
+containers:
+ - name: model-loader
+ version: 1.13-STAGING-20240417T124725Z
* ============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;
}
--- /dev/null
+/**
+ * ============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());
+ }
+ }
+
+}
--- /dev/null
+/**
+ * ============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();
+ }
+}
--- /dev/null
+/**
+ * ============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);
+ }
+ }
+}
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
*
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;
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;
}
}
+ 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");
+ }
+
}
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
/**\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
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());
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;
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;
/**
* 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());
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) {
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;
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.
*
* 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;
}
/**
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;
}
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());
}
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()) {
}
}
- 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.");
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;
- }
}
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}.
* @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();
* @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<>();
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
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";
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;
- }
}
*/
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;
- }
-
}
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);
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;
* 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";
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);
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;
}
--- /dev/null
+/**
+ * ============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();
+ }
+}
+++ /dev/null
-/**
- * ============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());
- }
-}
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;
}
/**
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;
- }
}
*/
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;
}
+++ /dev/null
-/**
- * ============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;
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;
*/
@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;
}
/**
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: "
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) {
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;
#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}
--- /dev/null
+/**
+ * ============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);
+ }
+}
--- /dev/null
+/**
+ * ============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
*/
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;
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;
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
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;
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
--- /dev/null
+/**
+ * ============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
--- /dev/null
+/**
+ * ============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);
+ }
+}
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;
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;
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.
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 {
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() {
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;
@Mock
private AaiRestClient aaiClient;
- @Before
+ @BeforeEach
public void setupMocks() {
- MockitoAnnotations.initMocks(this);
+ MockitoAnnotations.openMocks(this);
}
@Test
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;
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 {
*/
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;
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;
private ArtifactInfoExtractor extractor;
- @Before
+ @BeforeEach
public void setup() {
extractor = new ArtifactInfoExtractor();
}
- @After
+ @AfterEach
public void tearDown() {
extractor = null;
}
}
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
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
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
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");
}
}
--- /dev/null
+/**
+ * ============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);
+ }
+
+}
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;
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;
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
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<>();
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
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<>();
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
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<>();
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
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);
--- /dev/null
+/**
+ * ============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
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;
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;
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}.
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;
}
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());
}
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());
}
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());
}
}
}
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());
}
}
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;
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;
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}.
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;
catalogFiles), is(true));
assertThat(modelFiles, is(empty()));
assertThat(catalogFiles, is(empty()));
- Mockito.verifyZeroInteractions(mockBabelClient, mockDistributionClient, mockNotificationPublisher,
+ Mockito.verifyNoInteractions(mockBabelClient, mockDistributionClient, mockNotificationPublisher,
mockBabelArtifactConverter);
}
Mockito.verify(mockNotificationPublisher).publishDownloadFailure(mockDistributionClient, data, artifact,
errorMessage);
- Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter);
+ Mockito.verifyNoInteractions(mockBabelClient, mockBabelArtifactConverter);
}
@Test
Mockito.verify(mockDistributionClient).download(artifactInfo);
Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo);
Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo);
-
- Mockito.verifyZeroInteractions(mockBabelArtifactConverter);
}
@Test
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);
}
Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact);
- Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter);
+ Mockito.verifyNoInteractions(mockBabelClient, mockBabelArtifactConverter);
}
@Test
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());
}
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() {
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,
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());
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<>();
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());
}
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(
*/
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;
*/
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 {
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());
}
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}.
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;
verify(mockArtifactDownloadManager).downloadArtifacts(any(INotificationData.class), any(List.class),
any(List.class), any(List.class));
- Mockito.verifyZeroInteractions(mockArtifactDeploymentManager);
+ Mockito.verifyNoInteractions(mockArtifactDeploymentManager);
}
@SuppressWarnings("unchecked")
+++ /dev/null
-/**
- * ============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())));
- }
-
-}
*/
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;
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);
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;
/**
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();
}
}
*/
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;
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;
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;
/**
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();
}
@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);
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);
}
};
*/
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)));
}
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;
- }
}
--- /dev/null
+/**
+ * ============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);
+ }
+
+}
+++ /dev/null
-/**
- * ============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()));
}
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()));
}
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;
}
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) {
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
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;
--- /dev/null
+[
+ "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
--- /dev/null
+{
+ "kafkaBootStrapServer": "localhost:9092",
+ "distrNotificationTopicName": "SDC-DISTR-NOTIF-TOPIC-AUTO",
+ "distrStatusTopicName": "SDC-DISTR-STATUS-TOPIC-AUTO"
+}
\ No newline at end of file
--- /dev/null
+<?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
--- /dev/null
+[{"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
--- /dev/null
+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
<appender-ref ref="STDOUT" />
</logger>
- <root level="debug">
+ <root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
# 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
# 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}