summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authormark.j.leonard <mark.j.leonard@gmail.com>2018-06-06 14:47:42 +0100
committermark.j.leonard <mark.j.leonard@gmail.com>2018-06-06 15:37:53 +0100
commitc5aea4a8bc398fc1c6220875e55b9520fd7f7524 (patch)
treeb0aeef15bed28487c5827990d60fc3bdcf95b67e /src
parentce332032dd208c5c769a2297409d8aca3f780fa8 (diff)
Refactor for Sonar smells and code coverage
Various code formatting and style fixes (to address Sonar code smells). Introduce a BabelServiceClientException to replace the use of the base Exception class. Make both the BabelServiceClient class and its Factory class use an interface, to allow for Spring injection (using annotations) and for simplified mocking. Refactor the Notification Publishing by making this the responsibility of the main Service classes and not the deployment manager. Issue-ID: AAI-1207 Change-Id: I6bf8a504fa7b98e9158c9976fd1d88c6c54027c1 Signed-off-by: mark.j.leonard <mark.j.leonard@gmail.com>
Diffstat (limited to 'src')
-rw-r--r--src/main/java/org/onap/aai/modelloader/ModelLoaderApplication.java (renamed from src/main/java/org/onap/aai/modelloader/service/ModelLoaderApplication.java)4
-rw-r--r--src/main/java/org/onap/aai/modelloader/config/ModelLoaderConfig.java69
-rw-r--r--src/main/java/org/onap/aai/modelloader/entity/Artifact.java2
-rw-r--r--src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifact.java5
-rw-r--r--src/main/java/org/onap/aai/modelloader/entity/model/BabelArtifactParsingException.java11
-rw-r--r--src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifact.java4
-rw-r--r--src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java4
-rw-r--r--src/main/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifact.java8
-rw-r--r--src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java5
-rw-r--r--src/main/java/org/onap/aai/modelloader/notification/CompDoneStatusMessageBuilder.java2
-rw-r--r--src/main/java/org/onap/aai/modelloader/notification/DistributionStatusMessageBuilder.java2
-rw-r--r--src/main/java/org/onap/aai/modelloader/notification/EventCallback.java41
-rw-r--r--src/main/java/org/onap/aai/modelloader/notification/NotificationDataImpl.java (renamed from src/main/java/org/onap/aai/modelloader/service/NotificationDataImpl.java)4
-rw-r--r--src/main/java/org/onap/aai/modelloader/notification/NotificationPublisher.java54
-rw-r--r--src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java6
-rw-r--r--src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java163
-rw-r--r--src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientException.java37
-rw-r--r--src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java230
-rw-r--r--src/main/java/org/onap/aai/modelloader/service/ArtifactDeploymentManager.java (renamed from src/main/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManager.java)41
-rw-r--r--src/main/java/org/onap/aai/modelloader/service/BabelServiceClientFactory.java30
-rw-r--r--src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java56
-rw-r--r--src/main/java/org/onap/aai/modelloader/service/ModelLoaderInterface.java8
-rw-r--r--src/main/java/org/onap/aai/modelloader/service/ModelLoaderService.java118
-rw-r--r--src/main/java/org/onap/aai/modelloader/service/SdcConnectionJob.java40
-rw-r--r--src/main/java/org/onap/aai/modelloader/util/JsonXmlConverter.java151
-rw-r--r--src/test/java/org/onap/aai/modelloader/TestModelLoaderApplication.java (renamed from src/test/java/org/onap/aai/modelloader/service/TestModelLoaderApplication.java)9
-rw-r--r--src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java (renamed from src/test/java/org/onap/aai/modelloader/config/ModelLoaderConfigTest.java)19
-rw-r--r--src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java (renamed from src/test/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandlerTest.java)90
-rw-r--r--src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java7
-rw-r--r--src/test/java/org/onap/aai/modelloader/entity/model/ModelArtifactParserTest.java122
-rw-r--r--src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java56
-rw-r--r--src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java2
-rw-r--r--src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactParser.java102
-rw-r--r--src/test/java/org/onap/aai/modelloader/entity/model/TestNamedQueryArtifactParser.java (renamed from src/test/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifactParserTest.java)13
-rw-r--r--src/test/java/org/onap/aai/modelloader/extraction/TestArtifactInfoExtractor.java (renamed from src/test/java/org/onap/aai/modelloader/extraction/ArtifactInfoExtractorTest.java)10
-rw-r--r--src/test/java/org/onap/aai/modelloader/fixture/ArtifactInfoBuilder.java14
-rw-r--r--src/test/java/org/onap/aai/modelloader/fixture/MockNotificationDataImpl.java (renamed from src/test/java/org/onap/aai/modelloader/fixture/TestNotificationDataImpl.java)14
-rw-r--r--src/test/java/org/onap/aai/modelloader/fixture/NotificationDataFixtureBuilder.java40
-rw-r--r--src/test/java/org/onap/aai/modelloader/fixture/ResourceInstanceBuilder.java8
-rw-r--r--src/test/java/org/onap/aai/modelloader/fixture/TestResourceInstanceImpl.java2
-rw-r--r--src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java (renamed from src/test/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManagerTest.java)124
-rw-r--r--src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java (renamed from src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java)187
-rw-r--r--src/test/java/org/onap/aai/modelloader/notification/TestBabelArtifactConverter.java (renamed from src/test/java/org/onap/aai/modelloader/notification/BabelArtifactConverterTest.java)32
-rw-r--r--src/test/java/org/onap/aai/modelloader/notification/TestEventCallback.java (renamed from src/test/java/org/onap/aai/modelloader/notification/EventCallbackTest.java)17
-rw-r--r--src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java (renamed from src/test/java/org/onap/aai/modelloader/service/TestNotificationDataImpl.java)6
-rw-r--r--src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java2
-rw-r--r--src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java41
-rw-r--r--src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java144
-rw-r--r--src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java8
-rw-r--r--src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java27
-rw-r--r--src/test/java/org/onap/aai/modelloader/service/MockBabelServiceClientFactory.java (renamed from src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientFactory.java)23
-rw-r--r--src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java8
-rw-r--r--src/test/java/org/onap/aai/modelloader/service/TestModelLoaderService.java86
-rw-r--r--src/test/java/org/onap/aai/modelloader/service/TestModelLoaderServiceWithSdc.java63
-rw-r--r--src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java24
-rw-r--r--src/test/java/org/onap/aai/modelloader/util/TestJsonXmlConverter.java (renamed from src/test/java/org/onap/aai/modelloader/util/JsonXmlConverterTest.java)44
-rw-r--r--src/test/resources/auth/aai-client-dummy.p12bin0 -> 2514 bytes
-rw-r--r--src/test/resources/convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml51
-rw-r--r--src/test/resources/model-loader-empty-auth-password.properties25
-rw-r--r--src/test/resources/model-loader-no-auth-password.properties25
-rw-r--r--src/test/resources/model-loader.properties12
-rw-r--r--src/test/resources/sdc_test/model-loader.properties30
62 files changed, 1662 insertions, 920 deletions
diff --git a/src/main/java/org/onap/aai/modelloader/service/ModelLoaderApplication.java b/src/main/java/org/onap/aai/modelloader/ModelLoaderApplication.java
index c0eb5f2..66c44a3 100644
--- a/src/main/java/org/onap/aai/modelloader/service/ModelLoaderApplication.java
+++ b/src/main/java/org/onap/aai/modelloader/ModelLoaderApplication.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -18,7 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.modelloader.service;
+package org.onap.aai.modelloader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
diff --git a/src/main/java/org/onap/aai/modelloader/config/ModelLoaderConfig.java b/src/main/java/org/onap/aai/modelloader/config/ModelLoaderConfig.java
index 3f03bb5..0a2bc85 100644
--- a/src/main/java/org/onap/aai/modelloader/config/ModelLoaderConfig.java
+++ b/src/main/java/org/onap/aai/modelloader/config/ModelLoaderConfig.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -43,30 +43,33 @@ public class ModelLoaderConfig implements IConfiguration {
private static final String SUFFIX_KEYSTORE_FILE = "KEYSTORE_FILE";
private static final String SUFFIX_KEYSTORE_PASS = "KEYSTORE_PASSWORD";
+ private static final String SUFFIX_TRUSTSTORE_FILE = "TRUSTSTORE_FILE";
+ private static final String SUFFIX_TRUSTSTORE_PASS = "TRUSTSTORE_PASSWORD";
+
// Configuration file properties
- protected static final String PROP_ML_DISTRIBUTION_ACTIVE_SERVER_TLS_AUTH =
- PREFIX_DISTRIBUTION_CLIENT + "ACTIVE_SERVER_TLS_AUTH";
- protected static final String PROP_ML_DISTRIBUTION_ASDC_CONNECTION_DISABLED =
- PREFIX_DISTRIBUTION_CLIENT + "ASDC_CONNECTION_DISABLE";
+ protected static final String PROP_ML_DISTRIBUTION_ACTIVE_SERVER_TLS_AUTH = PREFIX_DISTRIBUTION_CLIENT
+ + "ACTIVE_SERVER_TLS_AUTH";
+ protected static final String PROP_ML_DISTRIBUTION_ASDC_CONNECTION_DISABLED = PREFIX_DISTRIBUTION_CLIENT
+ + "ASDC_CONNECTION_DISABLE";
protected static final String PROP_ML_DISTRIBUTION_ASDC_ADDRESS = PREFIX_DISTRIBUTION_CLIENT + "ASDC_ADDRESS";
protected static final String PROP_ML_DISTRIBUTION_CONSUMER_GROUP = PREFIX_DISTRIBUTION_CLIENT + "CONSUMER_GROUP";
protected static final String PROP_ML_DISTRIBUTION_CONSUMER_ID = PREFIX_DISTRIBUTION_CLIENT + "CONSUMER_ID";
- protected static final String PROP_ML_DISTRIBUTION_ENVIRONMENT_NAME =
- PREFIX_DISTRIBUTION_CLIENT + "ENVIRONMENT_NAME";
- protected static final String PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD =
- PREFIX_DISTRIBUTION_CLIENT + SUFFIX_KEYSTORE_PASS;
- protected static final String PROP_ML_DISTRIBUTION_KEYSTORE_FILE =
- PREFIX_DISTRIBUTION_CLIENT + SUFFIX_KEYSTORE_FILE;
+ protected static final String PROP_ML_DISTRIBUTION_ENVIRONMENT_NAME = PREFIX_DISTRIBUTION_CLIENT
+ + "ENVIRONMENT_NAME";
+ protected static final String PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD = PREFIX_DISTRIBUTION_CLIENT
+ + SUFFIX_KEYSTORE_PASS;
+ protected static final String PROP_ML_DISTRIBUTION_KEYSTORE_FILE = PREFIX_DISTRIBUTION_CLIENT
+ + SUFFIX_KEYSTORE_FILE;
protected static final String PROP_ML_DISTRIBUTION_PASSWORD = PREFIX_DISTRIBUTION_CLIENT + "PASSWORD";
- protected static final String PROP_ML_DISTRIBUTION_POLLING_INTERVAL =
- PREFIX_DISTRIBUTION_CLIENT + "POLLING_INTERVAL";
+ protected static final String PROP_ML_DISTRIBUTION_POLLING_INTERVAL = PREFIX_DISTRIBUTION_CLIENT
+ + "POLLING_INTERVAL";
protected static final String PROP_ML_DISTRIBUTION_POLLING_TIMEOUT = PREFIX_DISTRIBUTION_CLIENT + "POLLING_TIMEOUT";
protected static final String PROP_ML_DISTRIBUTION_USER = PREFIX_DISTRIBUTION_CLIENT + "USER";
protected static final String PROP_ML_DISTRIBUTION_ARTIFACT_TYPES = PREFIX_DISTRIBUTION_CLIENT + "ARTIFACT_TYPES";
- protected static final String PROP_ML_DISTRIBUTION_MSG_BUS_ADDRESSES =
- PREFIX_DISTRIBUTION_CLIENT + "MSG_BUS_ADDRESSES";
- protected static final String PROP_ML_DISTRIBUTION_HTTPS_WITH_DMAAP =
- PREFIX_DISTRIBUTION_CLIENT + "USE_HTTPS_WITH_DMAAP";
+ protected static final String PROP_ML_DISTRIBUTION_MSG_BUS_ADDRESSES = PREFIX_DISTRIBUTION_CLIENT
+ + "MSG_BUS_ADDRESSES";
+ protected static final String PROP_ML_DISTRIBUTION_HTTPS_WITH_DMAAP = PREFIX_DISTRIBUTION_CLIENT
+ + "USE_HTTPS_WITH_DMAAP";
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;
@@ -80,6 +83,8 @@ public class ModelLoaderConfig implements IConfiguration {
protected static final String PROP_BABEL_BASE_URL = PREFIX_BABEL + "BASE_URL";
protected static final String PROP_BABEL_KEYSTORE_FILE = PREFIX_BABEL + SUFFIX_KEYSTORE_FILE;
protected static final String PROP_BABEL_KEYSTORE_PASSWORD = PREFIX_BABEL + SUFFIX_KEYSTORE_PASS;
+ protected static final String PROP_BABEL_TRUSTSTORE_FILE = PREFIX_BABEL + SUFFIX_TRUSTSTORE_FILE;
+ protected static final String PROP_BABEL_TRUSTSTORE_PASSWORD = PREFIX_BABEL + SUFFIX_TRUSTSTORE_PASS;
protected static final String PROP_BABEL_GENERATE_RESOURCE_URL = PREFIX_BABEL + "GENERATE_ARTIFACTS_URL";
protected static final String PROP_DEBUG_INGEST_SIMULATOR = PREFIX_DEBUG + "INGEST_SIMULATOR";
@@ -95,8 +100,8 @@ public class ModelLoaderConfig implements IConfiguration {
private String modelVersion = null;
- protected static final String FILESEP =
- (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
+ protected static final String FILESEP = (System.getProperty("file.separator") == null) ? "/"
+ : System.getProperty("file.separator");
public static void setConfigHome(String configHome) {
ModelLoaderConfig.configHome = configHome;
@@ -113,8 +118,10 @@ public class ModelLoaderConfig implements IConfiguration {
/**
* Original constructor
*
- * @param modelLoaderProperties properties needed to be configured for the model loader
- * @param certLocation location of the certificate
+ * @param modelLoaderProperties
+ * properties needed to be configured for the model loader
+ * @param certLocation
+ * location of the certificate
*/
public ModelLoaderConfig(Properties modelLoaderProperties, String certLocation) {
this.modelLoaderProperties = modelLoaderProperties;
@@ -139,11 +146,10 @@ public class ModelLoaderConfig implements IConfiguration {
}
}
-
@Override
public boolean activateServerTLSAuth() {
String value = modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ACTIVE_SERVER_TLS_AUTH);
- return value == null ? false : Boolean.parseBoolean(value);
+ return value != null && Boolean.parseBoolean(value);
}
@Override
@@ -209,7 +215,7 @@ public class ModelLoaderConfig implements IConfiguration {
@Override
public Boolean isUseHttpsWithDmaap() {
String useHTTPS = modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_HTTPS_WITH_DMAAP);
- return useHTTPS == null ? false : Boolean.valueOf(useHTTPS);
+ return useHTTPS != null && Boolean.valueOf(useHTTPS);
}
@Override
@@ -227,7 +233,7 @@ public class ModelLoaderConfig implements IConfiguration {
return null;
} else {
return certLocation + File.separator + filename;
- }
+ }
}
public String getAaiKeyStorePassword() {
@@ -238,6 +244,19 @@ public class ModelLoaderConfig implements IConfiguration {
return Password.deobfuscate(modelLoaderProperties.getProperty(PROP_BABEL_KEYSTORE_PASSWORD));
}
+ public String getBabelTrustStorePath() {
+ String filename = modelLoaderProperties.getProperty(PROP_BABEL_TRUSTSTORE_FILE);
+ if (filename == null) {
+ return null;
+ } else {
+ return certLocation + File.separator + filename;
+ }
+ }
+
+ public String getBabelTrustStorePassword() {
+ return Password.deobfuscate(modelLoaderProperties.getProperty(PROP_BABEL_TRUSTSTORE_PASSWORD));
+ }
+
public String getAaiBaseUrl() {
return modelLoaderProperties.getProperty(PROP_AAI_BASE_URL);
}
diff --git a/src/main/java/org/onap/aai/modelloader/entity/Artifact.java b/src/main/java/org/onap/aai/modelloader/entity/Artifact.java
index f576e24..f87535f 100644
--- a/src/main/java/org/onap/aai/modelloader/entity/Artifact.java
+++ b/src/main/java/org/onap/aai/modelloader/entity/Artifact.java
@@ -20,7 +20,7 @@
*/
package org.onap.aai.modelloader.entity;
-public abstract class Artifact {
+public class Artifact {
private String payload;
private ArtifactType type;
diff --git a/src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifact.java b/src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifact.java
index a8f4e60..9a84cf2 100644
--- a/src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifact.java
+++ b/src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifact.java
@@ -26,7 +26,10 @@ import org.onap.aai.modelloader.entity.ArtifactType;
public class VnfCatalogArtifact extends Artifact {
public VnfCatalogArtifact(String payload) {
- super(ArtifactType.VNF_CATALOG);
+ this(ArtifactType.VNF_CATALOG, payload);
+ }
+ public VnfCatalogArtifact(ArtifactType artifactType, String payload) {
+ super(artifactType);
setPayload(payload);
}
}
diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/BabelArtifactParsingException.java b/src/main/java/org/onap/aai/modelloader/entity/model/BabelArtifactParsingException.java
index a3f14ba..dfb649c 100644
--- a/src/main/java/org/onap/aai/modelloader/entity/model/BabelArtifactParsingException.java
+++ b/src/main/java/org/onap/aai/modelloader/entity/model/BabelArtifactParsingException.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -36,13 +36,4 @@ public class BabelArtifactParsingException extends Exception {
super(message);
}
- /**
- * Constructor for an instance of this exception with a message and actual exception encountered.
- *
- * @param message information about the exception
- * @param cause the actual exception that was encountered
- */
- public BabelArtifactParsingException(String message, Throwable cause) {
- super(message, cause);
- }
}
diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifact.java b/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifact.java
index 154cda1..705ceb5 100644
--- a/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifact.java
+++ b/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifact.java
@@ -209,7 +209,7 @@ public class ModelArtifact extends AbstractModelArtifact {
String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
String instance = getModelInvariantId();
- if ((!baseURL.endsWith("/")) && (!subURL.startsWith("/"))) {
+ if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
baseURL = baseURL + "/";
}
@@ -230,7 +230,7 @@ public class ModelArtifact extends AbstractModelArtifact {
+ AAI_MODEL_VER_SUB_URL;
String instance = getModelVerId();
- if ((!baseURL.endsWith("/")) && (!subURL.startsWith("/"))) {
+ if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
baseURL = baseURL + "/";
}
diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java b/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java
index e687be0..adab6df 100644
--- a/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java
+++ b/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java
@@ -54,8 +54,8 @@ public class ModelArtifactParser extends AbstractModelArtifactParser {
} else {
if (node.getNodeName().equalsIgnoreCase(MODEL_VER)) {
((ModelArtifact) model).setModelVer(node);
- if ((((ModelArtifact) model).getModelNamespace() != null)
- && (!((ModelArtifact) model).getModelNamespace().isEmpty())) {
+ if (((ModelArtifact) model).getModelNamespace() != null
+ && !((ModelArtifact) model).getModelNamespace().isEmpty()) {
Element e = (Element) node;
e.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns",
((ModelArtifact) model).getModelNamespace());
diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifact.java b/src/main/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifact.java
index 4df9879..a8fdc8e 100644
--- a/src/main/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifact.java
+++ b/src/main/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifact.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -60,11 +60,11 @@ public class NamedQueryArtifact extends AbstractModelArtifact {
List<Artifact> completedArtifacts) {
OperationResult getResponse =
aaiClient.getResource(getNamedQueryUrl(config), distId, MediaType.APPLICATION_XML_TYPE);
- if ((getResponse == null) || (getResponse.getResultCode() != Response.Status.OK.getStatusCode())) {
+ if (getResponse == null || getResponse.getResultCode() != Response.Status.OK.getStatusCode()) {
// Only attempt the PUT if the model doesn't already exist
OperationResult putResponse = aaiClient.putResource(getNamedQueryUrl(config), getPayload(), distId,
MediaType.APPLICATION_XML_TYPE);
- if ((putResponse != null) && (putResponse.getResultCode() == Response.Status.CREATED.getStatusCode())) {
+ if (putResponse != null && putResponse.getResultCode() == Response.Status.CREATED.getStatusCode()) {
completedArtifacts.add(this);
logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
@@ -92,7 +92,7 @@ public class NamedQueryArtifact extends AbstractModelArtifact {
String subURL = config.getAaiNamedQueryUrl(getModelNamespaceVersion()).trim();
String instance = this.getNamedQueryUuid();
- if ((!baseURL.endsWith("/")) && (!subURL.startsWith("/"))) {
+ if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
baseURL = baseURL + "/";
}
diff --git a/src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java b/src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java
index 9dbe397..febc99a 100644
--- a/src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java
+++ b/src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java
@@ -39,7 +39,8 @@ 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.restclient.BabelServiceClient;
-import org.onap.aai.modelloader.restclient.BabelServiceClientFactory;
+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;
@@ -202,7 +203,7 @@ public class ArtifactDownloadManager {
try {
logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel client");
babelClient = clientFactory.create(config);
- } catch (Exception e) {
+ } catch (BabelServiceClientException e) {
logger.error(ModelLoaderMsgs.BABEL_REST_REQUEST_ERROR, e, "POST", config.getBabelBaseUrl(),
"Error posting artifact " + artifact.getArtifactName() + " " + serviceVersion + " to Babel: "
+ e.getLocalizedMessage());
diff --git a/src/main/java/org/onap/aai/modelloader/notification/CompDoneStatusMessageBuilder.java b/src/main/java/org/onap/aai/modelloader/notification/CompDoneStatusMessageBuilder.java
index c389945..f198fa8 100644
--- a/src/main/java/org/onap/aai/modelloader/notification/CompDoneStatusMessageBuilder.java
+++ b/src/main/java/org/onap/aai/modelloader/notification/CompDoneStatusMessageBuilder.java
@@ -28,7 +28,7 @@ import org.onap.sdc.utils.DistributionStatusEnum;
/**
* This class is responsible for building an instance of {@link DistributionStatusMsg}.
*/
-public class CompDoneStatusMessageBuilder {
+public final class CompDoneStatusMessageBuilder {
private CompDoneStatusMessageBuilder() {}
diff --git a/src/main/java/org/onap/aai/modelloader/notification/DistributionStatusMessageBuilder.java b/src/main/java/org/onap/aai/modelloader/notification/DistributionStatusMessageBuilder.java
index 91cd3de..d799da0 100644
--- a/src/main/java/org/onap/aai/modelloader/notification/DistributionStatusMessageBuilder.java
+++ b/src/main/java/org/onap/aai/modelloader/notification/DistributionStatusMessageBuilder.java
@@ -29,7 +29,7 @@ import org.onap.sdc.utils.DistributionStatusEnum;
/**
* This class is responsible for building an instance of {@link DistributionStatusMsg}.
*/
-public class DistributionStatusMessageBuilder {
+public final class DistributionStatusMessageBuilder {
private DistributionStatusMessageBuilder() {}
diff --git a/src/main/java/org/onap/aai/modelloader/notification/EventCallback.java b/src/main/java/org/onap/aai/modelloader/notification/EventCallback.java
index 2baa217..42f72ce 100644
--- a/src/main/java/org/onap/aai/modelloader/notification/EventCallback.java
+++ b/src/main/java/org/onap/aai/modelloader/notification/EventCallback.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -28,13 +28,15 @@ 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.restclient.BabelServiceClientFactory;
+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.beans.factory.annotation.Autowired;
public class EventCallback implements INotificationCallback {
private static Logger logger = LoggerFactory.getInstance().getLogger(EventCallback.class.getName());
@@ -42,8 +44,11 @@ public class EventCallback implements INotificationCallback {
private ArtifactDeploymentManager artifactDeploymentManager;
private ArtifactDownloadManager artifactDownloadManager;
+ private NotificationPublisher notificationPublisher;
private IDistributionClient client;
private ModelLoaderConfig config;
+ @Autowired
+ private BabelServiceClientFactory babelServiceClientFactory;
public EventCallback(IDistributionClient client, ModelLoaderConfig config) {
this.client = client;
@@ -63,18 +68,35 @@ public class EventCallback implements INotificationCallback {
getArtifactDownloadManager().downloadArtifacts(data, artifacts, modelArtifacts, catalogArtifacts);
if (success) {
- success = getArtifactDeploymentManager().deploy(data, artifacts, modelArtifacts, catalogArtifacts);
+ success = getArtifactDeploymentManager().deploy(data, modelArtifacts, catalogArtifacts);
}
String statusString = success ? "SUCCESS" : "FAILURE";
auditLogger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
"Processed distribution " + data.getDistributionID() + " (" + statusString + ")");
+
+ publishNotifications(data, "TOSCA_CSAR", artifacts, success);
+
MDC.clear();
}
+
+ private void publishNotifications(INotificationData data, String filterType, List<IArtifactInfo> artifacts,
+ boolean deploymentSuccess) {
+ if (deploymentSuccess) {
+ artifacts.stream().filter(a -> filterType.equalsIgnoreCase(a.getArtifactType()))
+ .forEach(a -> getNotificationPublisher().publishDeploySuccess(client, data, a));
+ getNotificationPublisher().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");
+ }
+ }
+
private ArtifactDeploymentManager getArtifactDeploymentManager() {
if (artifactDeploymentManager == null) {
- artifactDeploymentManager = new ArtifactDeploymentManager(client, config);
+ artifactDeploymentManager = new ArtifactDeploymentManager(config);
}
return artifactDeploymentManager;
@@ -82,9 +104,18 @@ public class EventCallback implements INotificationCallback {
private ArtifactDownloadManager getArtifactDownloadManager() {
if (artifactDownloadManager == null) {
- artifactDownloadManager = new ArtifactDownloadManager(client, config, new BabelServiceClientFactory());
+ artifactDownloadManager = new ArtifactDownloadManager(client, config, babelServiceClientFactory);
}
return artifactDownloadManager;
}
+
+
+ private NotificationPublisher getNotificationPublisher() {
+ if (notificationPublisher == null) {
+ notificationPublisher = new NotificationPublisher();
+ }
+
+ return notificationPublisher;
+ }
}
diff --git a/src/main/java/org/onap/aai/modelloader/service/NotificationDataImpl.java b/src/main/java/org/onap/aai/modelloader/notification/NotificationDataImpl.java
index 536aa4a..566415e 100644
--- a/src/main/java/org/onap/aai/modelloader/service/NotificationDataImpl.java
+++ b/src/main/java/org/onap/aai/modelloader/notification/NotificationDataImpl.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -18,7 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.modelloader.service;
+package org.onap.aai.modelloader.notification;
import java.util.Collections;
import java.util.List;
diff --git a/src/main/java/org/onap/aai/modelloader/notification/NotificationPublisher.java b/src/main/java/org/onap/aai/modelloader/notification/NotificationPublisher.java
index 967a290..626399e 100644
--- a/src/main/java/org/onap/aai/modelloader/notification/NotificationPublisher.java
+++ b/src/main/java/org/onap/aai/modelloader/notification/NotificationPublisher.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -20,8 +20,9 @@
*/
package org.onap.aai.modelloader.notification;
-import java.io.FileInputStream;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
@@ -41,7 +42,7 @@ import org.onap.sdc.utils.DistributionStatusEnum;
/**
* This class is responsible for publishing the status of actions performed working with artifacts.
*/
-class NotificationPublisher {
+public class NotificationPublisher {
private static Logger logger = LoggerFactory.getInstance().getLogger(NotificationPublisher.class);
private static Logger metricsLogger = LoggerFactory.getInstance().getMetricsLogger(NotificationPublisher.class);
@@ -51,7 +52,7 @@ class NotificationPublisher {
public NotificationPublisher() {
Properties configProperties = new Properties();
try {
- configProperties.load(new FileInputStream(ModelLoaderConfig.propertiesFile()));
+ configProperties.load(Files.newInputStream(Paths.get(ModelLoaderConfig.propertiesFile())));
} catch (IOException e) {
String errorMsg = "Failed to load configuration: " + e.getMessage();
logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, e, errorMsg);
@@ -141,28 +142,10 @@ class NotificationPublisher {
* @param data data about the notification that resulted in this message being created
* @param artifact the specific artifact to have its deployment status reported on
*/
- void publishDeployFailure(IDistributionClient client, INotificationData data, IArtifactInfo artifact) {
+ public void publishDeployFailure(IDistributionClient client, INotificationData data, IArtifactInfo artifact) {
publishDeployStatus(client, data, artifact, DistributionStatusEnum.DEPLOY_ERROR, "failure");
}
- private void publishDeployStatus(IDistributionClient client, INotificationData data, IArtifactInfo artifact,
- DistributionStatusEnum distributionStatusEnum, String result) {
- if (publishingEnabled) {
- MdcOverride override = initMDCStartTime();
-
- IDistributionClientResult sendStatus = client.sendDeploymentStatus(
- DistributionStatusMessageBuilder.build(client, data, artifact, distributionStatusEnum));
- metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "deploy " + result,
- artifact.getArtifactName(), sendStatus.getDistributionActionResult().toString());
-
- if (sendStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
- logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
- "Failed to publish deploy " + result + " status: " + sendStatus.getDistributionMessageResult());
- }
- } else {
- logPublishingDisabled(distributionStatusEnum.toString(), result);
- }
- }
/**
* This method is responsible for publishing notification that the deployment of an artifact was succesful.
@@ -171,11 +154,11 @@ class NotificationPublisher {
* @param data data about the notification that resulted in this message being created
* @param artifact the specific artifact to have its deployment status reported on
*/
- void publishDeploySuccess(IDistributionClient client, INotificationData data, IArtifactInfo artifact) {
+ public void publishDeploySuccess(IDistributionClient client, INotificationData data, IArtifactInfo artifact) {
publishDeployStatus(client, data, artifact, DistributionStatusEnum.DEPLOY_OK, "success");
}
- void publishComponentSuccess(IDistributionClient client, INotificationData data) {
+ public void publishComponentSuccess(IDistributionClient client, INotificationData data) {
if (publishingEnabled) {
MdcOverride override = initMDCStartTime();
@@ -194,7 +177,7 @@ class NotificationPublisher {
}
}
- void publishComponentFailure(IDistributionClient client, INotificationData data, String errorReason) {
+ public void publishComponentFailure(IDistributionClient client, INotificationData data, String errorReason) {
if (publishingEnabled) {
MdcOverride override = initMDCStartTime();
@@ -214,6 +197,25 @@ class NotificationPublisher {
}
}
+ private void publishDeployStatus(IDistributionClient client, INotificationData data, IArtifactInfo artifact,
+ DistributionStatusEnum distributionStatusEnum, String result) {
+ if (publishingEnabled) {
+ MdcOverride override = initMDCStartTime();
+
+ IDistributionClientResult sendStatus = client.sendDeploymentStatus(
+ DistributionStatusMessageBuilder.build(client, data, artifact, distributionStatusEnum));
+ metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "deploy " + result,
+ artifact.getArtifactName(), sendStatus.getDistributionActionResult().toString());
+
+ if (sendStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
+ logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
+ "Failed to publish deploy " + result + " status: " + sendStatus.getDistributionMessageResult());
+ }
+ } else {
+ logPublishingDisabled(distributionStatusEnum.toString(), result);
+ }
+ }
+
private void logPublishingDisabled(String statusType, String message) {
logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
"Notification publishing is disabled, skipping publishing of the following status: " + statusType
diff --git a/src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java b/src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java
index 5576ea9..27db741 100644
--- a/src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java
+++ b/src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -133,7 +133,7 @@ public class AaiRestClient {
public OperationResult getAndDeleteResource(String url, String transId) {
// First, GET the model
OperationResult getResponse = getResource(url, transId, MediaType.APPLICATION_XML_TYPE);
- if ((getResponse == null) || (getResponse.getResultCode() != Response.Status.OK.getStatusCode())) {
+ if (getResponse == null || getResponse.getResultCode() != Response.Status.OK.getStatusCode()) {
return getResponse;
}
@@ -151,7 +151,7 @@ public class AaiRestClient {
public boolean useBasicAuth() {
- return (config.getAaiAuthenticationUser() != null) && (config.getAaiAuthenticationPassword() != null);
+ return config.getAaiAuthenticationUser() != null && config.getAaiAuthenticationPassword() != null;
}
private RestClient setupClient() {
diff --git a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java
index fa677a9..f69752b 100644
--- a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java
+++ b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -18,168 +18,15 @@
* 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.FileInputStream;
-import java.io.IOException;
-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.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.X509TrustManager;
-import javax.ws.rs.core.Response;
-import org.json.JSONObject;
import org.onap.aai.babel.service.data.BabelArtifact;
-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;
-
-/**
- * Initial version for testing End to End scenarios
- *
- */
-public class BabelServiceClient {
-
- private static Logger logger = LoggerFactory.getInstance().getLogger(BabelServiceClient.class);
-
- private static final String SSL_PROTOCOL = "TLS";
- private static final String KEYSTORE_ALGORITHM = "SunX509";
- private static final String KEYSTORE_TYPE = "PKCS12";
-
- private ModelLoaderConfig config;
- private Client client;
-
- private TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
- @Override
- public X509Certificate[] getAcceptedIssuers() {
- return null; // NOSONAR
- }
-
- @Override
- public void checkClientTrusted(X509Certificate[] certs, String authType) {
- // Do nothing
- }
-
- @Override
- public void checkServerTrusted(X509Certificate[] certs, String authType) {
- // Do nothing
- }
- }};
-
- public class BabelServiceException extends Exception {
-
- /**
- * Babel Service error response
- */
- private static final long serialVersionUID = 1L;
-
- public BabelServiceException(String message) {
- super(message);
- }
-
- }
-
- /**
- * @param config
- * @throws NoSuchAlgorithmException
- * @throws KeyStoreException
- * @throws CertificateException
- * @throws IOException
- * @throws UnrecoverableKeyException
- * @throws KeyManagementException
- */
- public BabelServiceClient(ModelLoaderConfig config) throws NoSuchAlgorithmException, KeyStoreException,
- CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
- this.config = config;
-
- logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel Service client");
-
- SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
- KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
-
- String clientCertPassword = config.getBabelKeyStorePassword();
-
- char[] pwd = null;
- if (clientCertPassword != null) {
- pwd = clientCertPassword.toCharArray();
- }
-
- String clientCertFileName = config.getBabelKeyStorePath();
- if (clientCertFileName != null) {
- FileInputStream fin = new FileInputStream(clientCertFileName);
- ks.load(fin, pwd);
- kmf.init(ks, pwd);
- ctx.init(kmf.getKeyManagers(), trustAllCerts, null);
- } else {
- ctx.init(null, trustAllCerts, 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");
- }
-
- /**
- * @param artifactPayload
- * @param artifactName
- * @param artifactVersion
- * @param transactionId
- * @return
- * @throws BabelServiceException
- */
- public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
- String transactionId) throws BabelServiceException {
- Objects.requireNonNull(artifactPayload);
-
- String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
-
- JSONObject obj = new JSONObject();
- obj.put("csar", encodedPayload);
- obj.put("artifactVersion", artifactVersion);
- obj.put("artifactName", artifactName);
-
- logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
- + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
-
- 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));
- logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
- "Babel response " + response.getStatus() + " " + sanitizedJson);
+public interface BabelServiceClient {
- if (response.getStatus() != Response.Status.OK.getStatusCode()) {
- throw new BabelServiceException(sanitizedJson);
- }
+ List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
+ String transactionId) throws BabelServiceClientException;
- return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());
- }
}
diff --git a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientException.java b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientException.java
new file mode 100644
index 0000000..0ce8037
--- /dev/null
+++ b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientException.java
@@ -0,0 +1,37 @@
+/**
+ * ============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.restclient;
+
+public class BabelServiceClientException extends Exception {
+
+ /**
+ * Babel Service Client Exception.
+ */
+ private static final long serialVersionUID = 1L;
+
+ public BabelServiceClientException(String message) {
+ super(message);
+ }
+
+ public BabelServiceClientException(Exception ex) {
+ super(ex);
+ }
+}
diff --git a/src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java b/src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java
new file mode 100644
index 0000000..f07d0d3
--- /dev/null
+++ b/src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java
@@ -0,0 +1,230 @@
+/**
+ * ============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.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.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.Logger;
+import org.onap.aai.cl.eelf.LoggerFactory;
+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 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");
+
+ 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) {
+ 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);
+ }
+
+ 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);
+ }
+
+ if (response.getStatus() != Response.Status.OK.getStatusCode()) {
+ throw new BabelServiceClientException(sanitizedJson);
+ }
+
+ return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());
+ }
+}
diff --git a/src/main/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManager.java b/src/main/java/org/onap/aai/modelloader/service/ArtifactDeploymentManager.java
index ca17261..af006f5 100644
--- a/src/main/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManager.java
+++ b/src/main/java/org/onap/aai/modelloader/service/ArtifactDeploymentManager.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -18,7 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.modelloader.notification;
+package org.onap.aai.modelloader.service;
import java.util.ArrayList;
import java.util.List;
@@ -27,8 +27,6 @@ import org.onap.aai.modelloader.entity.Artifact;
import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifactHandler;
import org.onap.aai.modelloader.entity.model.ModelArtifactHandler;
import org.onap.aai.modelloader.restclient.AaiRestClient;
-import org.onap.sdc.api.IDistributionClient;
-import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.INotificationData;
/**
@@ -36,29 +34,25 @@ import org.onap.sdc.api.notification.INotificationData;
*/
public class ArtifactDeploymentManager {
- private IDistributionClient client;
private ModelLoaderConfig config;
private ModelArtifactHandler modelArtifactHandler;
private VnfCatalogArtifactHandler vnfCatalogArtifactHandler;
- private NotificationPublisher notificationPublisher;
- public ArtifactDeploymentManager(IDistributionClient client, ModelLoaderConfig config) {
- this.client = client;
+ public ArtifactDeploymentManager(ModelLoaderConfig config) {
this.config = config;
}
/**
- * Deploys model and catalog artifacts to A&AI
+ * Deploys model and catalog artifacts to A&AI.
*
* @param data data about the notification that is being processed
- * @param artifacts the specific artifacts found in the data.
* @param modelArtifacts collection of artifacts that represent yml files found in a TOSCA_CSAR file that have been
* converted to XML and also those for model query specs
* @param catalogArtifacts collection of artifacts that represent vnf catalog files
* @return boolean <code>true</code> if all deployments were successful otherwise <code>false</code>
*/
- public boolean deploy(final INotificationData data, final List<IArtifactInfo> artifacts,
- final List<Artifact> modelArtifacts, final List<Artifact> catalogArtifacts) {
+ public boolean deploy(final INotificationData data, final List<Artifact> modelArtifacts,
+ final List<Artifact> catalogArtifacts) {
AaiRestClient aaiClient = new AaiRestClient(config);
String distributionId = data.getDistributionID();
@@ -79,24 +73,9 @@ public class ArtifactDeploymentManager {
}
}
- publishNotifications(data, "TOSCA_CSAR", artifacts, deploySuccess);
-
return deploySuccess;
}
- private void publishNotifications(INotificationData data, String filterType, List<IArtifactInfo> artifacts,
- boolean deploymentSuccess) {
- if (deploymentSuccess) {
- artifacts.stream().filter(a -> filterType.equalsIgnoreCase(a.getArtifactType()))
- .forEach(a -> getNotificationPublisher().publishDeploySuccess(client, data, a));
- getNotificationPublisher().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");
- }
- }
-
private ModelArtifactHandler getModelArtifactHandler() {
if (modelArtifactHandler == null) {
modelArtifactHandler = new ModelArtifactHandler(config);
@@ -105,14 +84,6 @@ public class ArtifactDeploymentManager {
return modelArtifactHandler;
}
- private NotificationPublisher getNotificationPublisher() {
- if (notificationPublisher == null) {
- notificationPublisher = new NotificationPublisher();
- }
-
- return notificationPublisher;
- }
-
private VnfCatalogArtifactHandler getVnfCatalogArtifactHandler() {
if (vnfCatalogArtifactHandler == null) {
this.vnfCatalogArtifactHandler = new VnfCatalogArtifactHandler(config);
diff --git a/src/main/java/org/onap/aai/modelloader/service/BabelServiceClientFactory.java b/src/main/java/org/onap/aai/modelloader/service/BabelServiceClientFactory.java
new file mode 100644
index 0000000..ce690c5
--- /dev/null
+++ b/src/main/java/org/onap/aai/modelloader/service/BabelServiceClientFactory.java
@@ -0,0 +1,30 @@
+/**
+ * ============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 org.onap.aai.modelloader.config.ModelLoaderConfig;
+import org.onap.aai.modelloader.restclient.BabelServiceClient;
+import org.onap.aai.modelloader.restclient.BabelServiceClientException;
+
+public interface BabelServiceClientFactory {
+ public BabelServiceClient create(ModelLoaderConfig config) throws BabelServiceClientException;
+}
diff --git a/src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java b/src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java
new file mode 100644
index 0000000..2414991
--- /dev/null
+++ b/src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java
@@ -0,0 +1,56 @@
+/**
+ * ============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);
+ }
+ }
+
+}
diff --git a/src/main/java/org/onap/aai/modelloader/service/ModelLoaderInterface.java b/src/main/java/org/onap/aai/modelloader/service/ModelLoaderInterface.java
index 6796090..e65e02c 100644
--- a/src/main/java/org/onap/aai/modelloader/service/ModelLoaderInterface.java
+++ b/src/main/java/org/onap/aai/modelloader/service/ModelLoaderInterface.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -31,15 +31,15 @@ public interface ModelLoaderInterface {
@RequestMapping(value = "/loadModel/{modelid}", //
method = RequestMethod.GET, produces = "application/json")
@ResponseBody
- public Response loadModel(String modelid);
+ Response loadModel(String modelid);
@RequestMapping(value = "/saveModel/{modelid}/{modelname}", //
method = RequestMethod.PUT, produces = "application/json")
@ResponseBody
- public Response saveModel(String modelid, String modelname);
+ Response saveModel(String modelid, String modelname);
@RequestMapping(value = "/ingestModel/{modelName}/{modelVersion}", //
method = RequestMethod.POST, produces = "application/json")
@ResponseBody
- public Response ingestModel(String modelid, String modelVersion, String payload) throws IOException;
+ Response ingestModel(String modelid, String modelVersion, String payload) throws IOException;
}
diff --git a/src/main/java/org/onap/aai/modelloader/service/ModelLoaderService.java b/src/main/java/org/onap/aai/modelloader/service/ModelLoaderService.java
index 06d6e30..f8ab60f 100644
--- a/src/main/java/org/onap/aai/modelloader/service/ModelLoaderService.java
+++ b/src/main/java/org/onap/aai/modelloader/service/ModelLoaderService.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -20,8 +20,9 @@
*/
package org.onap.aai.modelloader.service;
-import java.io.FileInputStream;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
@@ -30,21 +31,22 @@ 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.cl.api.Logger;
import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.modelloader.config.ModelLoaderConfig;
import org.onap.aai.modelloader.entity.Artifact;
-import org.onap.aai.modelloader.notification.ArtifactDeploymentManager;
import org.onap.aai.modelloader.notification.ArtifactDownloadManager;
import org.onap.aai.modelloader.notification.EventCallback;
-import org.onap.aai.modelloader.restclient.BabelServiceClientFactory;
+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.notification.INotificationData;
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;
@@ -58,15 +60,14 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/services/model-loader/v1/model-service")
public class ModelLoaderService implements ModelLoaderInterface {
- static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
-
- protected static final String FILESEP =
- (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
+ private static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
@Value("${CONFIG_HOME}")
private String configDir;
private IDistributionClient client;
private ModelLoaderConfig config;
+ @Autowired
+ private BabelServiceClientFactory babelClientFactory;
/**
* Responsible for loading configuration files and calling initialization.
@@ -78,7 +79,7 @@ public class ModelLoaderService implements ModelLoaderInterface {
ModelLoaderConfig.setConfigHome(configDir);
Properties configProperties = new Properties();
try {
- configProperties.load(new FileInputStream(configDir + FILESEP + "model-loader.properties"));
+ configProperties.load(Files.newInputStream(Paths.get(configDir, "model-loader.properties")));
config = new ModelLoaderConfig(configProperties);
if (!config.getASDCConnectionDisabled()) {
initSdcClient();
@@ -92,7 +93,7 @@ public class ModelLoaderService implements ModelLoaderInterface {
/**
* Responsible for stopping the connection to the distribution client before the resource is destroyed.
*/
- protected void preShutdownOperations() {
+ public void preShutdownOperations() {
logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
if (client != null) {
client.stop();
@@ -110,19 +111,13 @@ public class ModelLoaderService implements ModelLoaderInterface {
IDistributionClientResult initResult = client.init(config, callback);
- if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
- 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);
- } else {
+ if (initResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
// Start distribution client
logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
IDistributionClientResult startResult = client.start();
- if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
+ 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);
@@ -130,10 +125,17 @@ public class ModelLoaderService implements ModelLoaderInterface {
Timer timer = new Timer();
TimerTask task = new SdcConnectionJob(client, config, callback, timer);
timer.schedule(task, new Date(), 60000);
- } else {
- logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
}
+ } 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));
}
@@ -160,51 +162,57 @@ public class ModelLoaderService implements ModelLoaderInterface {
@Override
public Response ingestModel(@PathVariable String modelName, @PathVariable String modelVersion,
@RequestBody String payload) throws IOException {
- boolean success;
+ Response response;
if (config.getIngestSimulatorEnabled()) {
- try {
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");
+ response = processTestArtifact(modelName, modelVersion, payload);
+ } else {
+ logger.debug("Simulation interface disabled");
+ response = Response.serverError().build();
+ }
- List<Artifact> catalogArtifacts = new ArrayList<>();
- List<Artifact> modelArtifacts = new ArrayList<>();
+ return response;
+ }
- IArtifactInfo artifactInfo = new ArtifactInfoImpl();
- ((ArtifactInfoImpl) artifactInfo).setArtifactName(modelName);
- ((ArtifactInfoImpl) artifactInfo).setArtifactVersion(modelVersion);
+ private Response processTestArtifact(String modelName, String modelVersion, String payload) {
+ IArtifactInfo artifactInfo = new ArtifactInfoImpl();
+ ((ArtifactInfoImpl) artifactInfo).setArtifactName(modelName);
+ ((ArtifactInfoImpl) artifactInfo).setArtifactVersion(modelVersion);
- byte[] csarFile = Base64.getDecoder().decode(payload);
+ Response response;
+ try {
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact " + modelName + " " + modelVersion);
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Generating xml models from test artifact");
+ byte[] csarFile = Base64.getDecoder().decode(payload);
- new ArtifactDownloadManager(client, config, new BabelServiceClientFactory()).processToscaArtifacts(
- modelArtifacts, catalogArtifacts, csarFile, artifactInfo, "test-transaction-id", modelVersion);
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Generating XML models from test artifact");
- List<IArtifactInfo> artifacts = new ArrayList<>();
- artifacts.add(artifactInfo);
- INotificationData notificationData = new NotificationDataImpl();
- ((NotificationDataImpl) notificationData).setDistributionID("TestDistributionID");
+ List<Artifact> modelArtifacts = new ArrayList<>();
+ List<Artifact> catalogArtifacts = new ArrayList<>();
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Loading xml models from test artifact");
+ new ArtifactDownloadManager(client, config, babelClientFactory).processToscaArtifacts(modelArtifacts,
+ catalogArtifacts, csarFile, artifactInfo, "test-transaction-id", modelVersion);
- success = new ArtifactDeploymentManager(client, config).deploy(notificationData, artifacts,
- modelArtifacts, catalogArtifacts);
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Loading xml models from test artifacts: "
+ + modelArtifacts.size() + " model(s) and " + catalogArtifacts.size() + " catalog(s)");
- } catch (Exception e) {
- return Response.serverError().entity(e).build();
+ NotificationDataImpl notificationData = new NotificationDataImpl();
+ notificationData.setDistributionID("TestDistributionID");
+ boolean success =
+ new ArtifactDeploymentManager(config).deploy(notificationData, modelArtifacts, catalogArtifacts);
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Deployment success was " + success);
+ response = success ? Response.ok().build() : Response.serverError().build();
+ } catch (Exception e) {
+ String responseMessage = e.getMessage();
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Exception handled: " + responseMessage);
+ if (config.getASDCConnectionDisabled()) {
+ // Make sure the NotificationPublisher logger is invoked as per the standard processing flow.
+ new NotificationPublisher().publishDeployFailure(client, new NotificationDataImpl(), artifactInfo);
+ } else {
+ responseMessage += "\nSDC publishing is enabled but has been bypassed";
}
- } else {
- logger.debug("Simulation interface disabled");
- success = false;
- }
-
- Response response;
- if (success) {
- response = Response.ok().build();
- } else {
- response = Response.serverError().build();
+ response = Response.serverError().entity(responseMessage).type(MediaType.APPLICATION_XML).build();
}
-
return response;
}
}
diff --git a/src/main/java/org/onap/aai/modelloader/service/SdcConnectionJob.java b/src/main/java/org/onap/aai/modelloader/service/SdcConnectionJob.java
index 82e0bc6..9a6c6e9 100644
--- a/src/main/java/org/onap/aai/modelloader/service/SdcConnectionJob.java
+++ b/src/main/java/org/onap/aai/modelloader/service/SdcConnectionJob.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -31,14 +31,15 @@ import org.onap.sdc.api.results.IDistributionClientResult;
import org.onap.sdc.utils.DistributionActionResultEnum;
public class SdcConnectionJob extends TimerTask {
- static Logger logger = LoggerFactory.getInstance().getLogger(SdcConnectionJob.class.getName());
+ private static final Logger logger = LoggerFactory.getInstance().getLogger(SdcConnectionJob.class.getName());
- private IDistributionClient client;
+ private final IDistributionClient client;
private ModelLoaderConfig config;
private EventCallback callback;
private Timer timer;
public SdcConnectionJob(IDistributionClient client, ModelLoaderConfig config, EventCallback callback, Timer timer) {
+ super();
this.client = client;
this.timer = timer;
this.callback = callback;
@@ -48,26 +49,27 @@ public class SdcConnectionJob extends TimerTask {
@Override
public void run() {
if (!config.getASDCConnectionDisabled()) {
-
- IDistributionClientResult initResult = client.init(config, callback);
-
- if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
- String errorMsg =
- "Failed to initialize distribution client: " + initResult.getDistributionMessageResult();
- logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
- return;
- }
-
- IDistributionClientResult startResult = client.start();
- if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
- String errorMsg = "Failed to start distribution client: " + startResult.getDistributionMessageResult();
- logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
- return;
+ final IDistributionClientResult initResult = client.init(config, callback);
+ if (initResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
+ startClient();
+ } else {
+ logConnectionError("Failed to initialize", initResult);
}
+ }
+ }
- // Success. Cancel the timer job
+ private void startClient() {
+ final IDistributionClientResult startResult = client.start();
+ if (startResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
timer.cancel();
logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
+ } else {
+ logConnectionError("Failed to start", startResult);
}
}
+
+ private void logConnectionError(String msgPrefix, IDistributionClientResult result) {
+ final String errorMsg = msgPrefix + " distribution client: " + result.getDistributionMessageResult();
+ logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
+ }
}
diff --git a/src/main/java/org/onap/aai/modelloader/util/JsonXmlConverter.java b/src/main/java/org/onap/aai/modelloader/util/JsonXmlConverter.java
index 48a33b5..87cfdcc 100644
--- a/src/main/java/org/onap/aai/modelloader/util/JsonXmlConverter.java
+++ b/src/main/java/org/onap/aai/modelloader/util/JsonXmlConverter.java
@@ -1,74 +1,77 @@
-/**
- * ============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.util;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.json.XML;
-
-public class JsonXmlConverter {
-
- private JsonXmlConverter() {
- throw new AssertionError("Instantiating utility class.");
- }
-
- /**
- * Determines whether or not the supplied text string represents a valid JSON structure or not.
- *
- * @param text The text to be evaluated.
- * @return - true if the string represents a valid JSON object, false, otherwise.
- */
- public static boolean isValidJson(String text) {
- try {
- new JSONObject(text);
- } catch (JSONException ex) {
- try {
- new JSONArray(text);
- } catch (JSONException ex1) {
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Takes a text string representing a valid JSON structure and converts it to an equivalent XML string.
- *
- * @param jsonText The JSON string to convert to XML.
- * @return an XML string representation of the supplied JSON string.
- */
- public static String convertJsonToXml(String jsonText) {
- return XML.toString(new JSONObject(jsonText));
- }
-
- /**
- * Takes a text string representing a valid XML structure and converts it to an equivalent JSON string.
- *
- * @param xmlText The XML string to convert to JSON.
- * @return a JSON string representation of the supplied XML string.
- */
- public static String convertXmlToJson(String xmlText) {
- JSONObject jsonObj = XML.toJSONObject(xmlText);
- return jsonObj.toString();
- }
-}
+/**
+ * ============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.util;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.json.XML;
+
+public final class JsonXmlConverter {
+
+ private JsonXmlConverter() {
+ throw new AssertionError("Instantiating utility class.");
+ }
+
+ /**
+ * Determines whether or not the supplied text string represents a valid JSON structure or not.
+ *
+ * @param text The text to be evaluated.
+ * @return - true if the string represents a valid JSON object, false, otherwise.
+ */
+ public static boolean isValidJson(String text) {
+ boolean isValid;
+ try {
+ new JSONObject(text);
+ isValid = true;
+ } catch (JSONException ex) {
+ try {
+ new JSONArray(text);
+ isValid = true;
+ } catch (JSONException ex1) {
+ isValid = false;
+ }
+ }
+
+ return isValid;
+ }
+
+ /**
+ * Takes a text string representing a valid JSON structure and converts it to an equivalent XML string.
+ *
+ * @param jsonText The JSON string to convert to XML.
+ * @return an XML string representation of the supplied JSON string.
+ */
+ public static String convertJsonToXml(String jsonText) {
+ return XML.toString(new JSONObject(jsonText));
+ }
+
+ /**
+ * Takes a text string representing a valid XML structure and converts it to an equivalent JSON string.
+ *
+ * @param xmlText The XML string to convert to JSON.
+ * @return a JSON string representation of the supplied XML string.
+ */
+ public static String convertXmlToJson(String xmlText) {
+ JSONObject jsonObj = XML.toJSONObject(xmlText);
+ return jsonObj.toString();
+ }
+}
diff --git a/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderApplication.java b/src/test/java/org/onap/aai/modelloader/TestModelLoaderApplication.java
index 0f3ed45..c54f43e 100644
--- a/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderApplication.java
+++ b/src/test/java/org/onap/aai/modelloader/TestModelLoaderApplication.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -18,12 +18,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.modelloader.service;
+package org.onap.aai.modelloader;
import org.junit.Test;
+import org.onap.aai.modelloader.ModelLoaderApplication;
/**
- * Tests for ModelLoaderApplication class
+ * Tests for ModelLoaderApplication class.
*
*/
public class TestModelLoaderApplication {
@@ -34,7 +35,7 @@ public class TestModelLoaderApplication {
@Test
public void testServiceStarts() {
- // The SDC Distribution Client is expected to fail to initialise.
+ // The SDC Distribution Client is disabled.
ModelLoaderApplication.main(new String[0]);
}
diff --git a/src/test/java/org/onap/aai/modelloader/config/ModelLoaderConfigTest.java b/src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java
index e8060e2..bfd793a 100644
--- a/src/test/java/org/onap/aai/modelloader/config/ModelLoaderConfigTest.java
+++ b/src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -34,10 +34,10 @@ import org.onap.aai.modelloader.restclient.AaiRestClient;
import org.onap.sdc.utils.ArtifactTypeEnum;
/**
- * Tests for ModelLoaderConfig class
+ * Tests for ModelLoaderConfig class.
*
*/
-public class ModelLoaderConfigTest {
+public class TestModelLoaderConfig {
@Test
public void testYangModelArtifactType() {
@@ -89,7 +89,7 @@ public class ModelLoaderConfigTest {
}
@Test
- public void testDecryptAAIAuthenticationPassword() {
+ public void testDecryptAaiAuthenticationPassword() {
String password = "myvoiceismypassword";
ModelLoaderConfig config =
createObfuscatedTestConfig(ModelLoaderConfig.PROP_AAI_AUTHENTICATION_PASSWORD, password);
@@ -97,7 +97,7 @@ public class ModelLoaderConfigTest {
}
@Test
- public void testDecryptAAIKeystorePassword() {
+ public void testDecryptAaiKeystorePassword() {
String password = "myvoiceismypassword";
ModelLoaderConfig config = createObfuscatedTestConfig(ModelLoaderConfig.PROP_AAI_KEYSTORE_PASSWORD, password);
assertEquals(password, config.getAaiKeyStorePassword());
@@ -148,8 +148,7 @@ public class ModelLoaderConfigTest {
}
@Test
- public void testNoAAIAuth() throws IOException {
-
+ public void testMissingAuthenticationProperties() throws IOException {
Properties props = new Properties();
props.load(new FileInputStream("src/test/resources/model-loader-empty-auth-password.properties"));
@@ -180,8 +179,10 @@ public class ModelLoaderConfigTest {
/**
- * @param propertyName
- * @param propertyValue
+ * Create a Model Loader Configuration object from the supplied Property.
+ *
+ * @param propertyName property key
+ * @param propertyValue value of the property
* @return a new ModelLoaderConfig object containing a single obfuscated property value
*/
private ModelLoaderConfig createObfuscatedTestConfig(String propertyName, String propertyValue) {
diff --git a/src/test/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandlerTest.java b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java
index b6d4564..b54bb20 100644
--- a/src/test/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandlerTest.java
+++ b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -20,12 +20,15 @@
*/
package org.onap.aai.modelloader.entity.catalog;
-import static org.junit.Assert.assertTrue;
+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.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
+import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
@@ -41,24 +44,19 @@ import org.onap.aai.modelloader.entity.Artifact;
import org.onap.aai.modelloader.restclient.AaiRestClient;
import org.onap.aai.restclient.client.OperationResult;
-public class VnfCatalogArtifactHandlerTest {
+public class TestVnfCatalogArtifactHandler {
protected static String CONFIG_FILE = "model-loader.properties";
- @Test
- public void testWithMocks() throws Exception {
-
- Properties configProperties = new Properties();
- try {
- configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE));
- } catch (IOException e) {
- fail();
- }
- ModelLoaderConfig config = new ModelLoaderConfig(configProperties, null);
- config.setModelVersion("11");
-
- AaiRestClient mockRestClient = mock(AaiRestClient.class);
+ private AaiRestClient mockRestClient = mock(AaiRestClient.class);
+ /**
+ * Update A&AI with 4 images, 2 of which already exist.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testUpdateVnfImages() throws Exception {
// GET operation
OperationResult mockGetResp = mock(OperationResult.class);
@@ -69,32 +67,64 @@ public class VnfCatalogArtifactHandlerTest {
.thenReturn(Response.Status.NOT_FOUND.getStatusCode())
.thenReturn(Response.Status.OK.getStatusCode());
// @formatter:on
+
when(mockRestClient.getResource(Mockito.anyString(), Mockito.anyString(), Mockito.any(MediaType.class)))
.thenReturn(mockGetResp);
+ mockPutOperations();
- // PUT operation
- OperationResult mockPutResp = mock(OperationResult.class);
+ // Example VNF Catalog XML
+ VnfCatalogArtifactHandler handler = new VnfCatalogArtifactHandler(createConfig());
+ assertThat(handler.pushArtifacts(createVnfCatalogArtifact(), "test", new ArrayList<Artifact>(), mockRestClient),
+ is(true));
- when(mockPutResp.getResultCode()).thenReturn(Response.Status.CREATED.getStatusCode());
- when(mockRestClient.putResource(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
- Mockito.any(MediaType.class))).thenReturn(mockPutResp);
+ assertPutOperationsSucceeded();
+ }
+
+ private ModelLoaderConfig createConfig() {
+ Properties configProperties = new Properties();
+ try {
+ configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE));
+ } catch (IOException e) {
+ fail();
+ }
+ ModelLoaderConfig config = new ModelLoaderConfig(configProperties, null);
+ return config;
+ }
- // Example VNF Catalog with
- VnfCatalogArtifactHandler vnfCAH = new VnfCatalogArtifactHandler(config);
+ /**
+ * Example VNF Catalog based on JSON data (returned by Babel)
+ *
+ * @return test Artifacts
+ * @throws IOException
+ * @throws UnsupportedEncodingException
+ */
+ private List<Artifact> createVnfCatalogArtifact() throws IOException, UnsupportedEncodingException {
String examplePath = "src/test/resources/imagedataexample.json";
byte[] encoded = Files.readAllBytes(Paths.get(examplePath));
List<Artifact> artifacts = new ArrayList<Artifact>();
artifacts.add(new VnfCatalogArtifact(new String(encoded, "utf-8")));
+ return artifacts;
+ }
- assertTrue(vnfCAH.pushArtifacts(artifacts, "test", new ArrayList<Artifact>(), mockRestClient));
+ /**
+ * Always return CREATED (success) for a PUT operation.
+ */
+ private void mockPutOperations() {
+ OperationResult mockPutResp = mock(OperationResult.class);
+ when(mockPutResp.getResultCode()).thenReturn(Response.Status.CREATED.getStatusCode());
+ when(mockRestClient.putResource(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
+ Mockito.any(MediaType.class))).thenReturn(mockPutResp);
+ }
+ private void assertPutOperationsSucceeded() {
// Only two of the VNF images should be pushed
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
- AaiRestClient r = Mockito.verify(mockRestClient, Mockito.times(2));
- r.putResource(Mockito.anyString(), argument.capture(), Mockito.anyString(), Mockito.any(MediaType.class));
- assertTrue(argument.getAllValues().get(0).contains("3.16.9"));
- assertTrue(argument.getAllValues().get(0).contains("VM00"));
- assertTrue(argument.getAllValues().get(1).contains("3.16.1"));
- assertTrue(argument.getAllValues().get(1).contains("VM01"));
+ AaiRestClient mockedClient = Mockito.verify(mockRestClient, Mockito.times(2));
+ mockedClient.putResource(Mockito.anyString(), argument.capture(), Mockito.anyString(),
+ Mockito.any(MediaType.class));
+ assertThat(argument.getAllValues().get(0), containsString("3.16.9"));
+ assertThat(argument.getAllValues().get(0), containsString("VM00"));
+ assertThat(argument.getAllValues().get(1), containsString("3.16.1"));
+ assertThat(argument.getAllValues().get(1), containsString("VM01"));
}
}
diff --git a/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java
index a41ddf9..c8b14f7 100644
--- a/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java
+++ b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfImageException.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -27,7 +27,7 @@ import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
- * Tests for NotificationDataImpl class
+ * Tests for NotificationDataImpl class.
*
*/
public class TestVnfImageException {
@@ -41,8 +41,7 @@ public class TestVnfImageException {
assertThat(exception.getImageId(), is(equalTo("id2")));
assertThat(exception.getResultCode().get(), is(equalTo(1)));
- Exception e = new Exception("message");
- exception = new VnfImageException(e);
+ exception = new VnfImageException(new Exception("message"));
assertThat(exception.getImageId(), is(equalTo("message")));
}
diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/ModelArtifactParserTest.java b/src/test/java/org/onap/aai/modelloader/entity/model/ModelArtifactParserTest.java
deleted file mode 100644
index 84a4313..0000000
--- a/src/test/java/org/onap/aai/modelloader/entity/model/ModelArtifactParserTest.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Copyright © 2017-2018 European Software Marketing Ltd.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.aai.modelloader.entity.model;
-
-import static org.junit.Assert.assertTrue;
-
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.List;
-import org.junit.Test;
-import org.onap.aai.modelloader.entity.Artifact;
-
-public class ModelArtifactParserTest {
-
- @Test
- public void testParseModelFileNoDeps() throws Exception {
- final String MODEL_FILE = "src/test/resources/models/l3-network-widget.xml";
-
- try {
- String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE)));
-
- ModelArtifactParser parser = new ModelArtifactParser();
- List<Artifact> modelList = parser.parse(fileString, "test-artifact");
-
- assertTrue(modelList.size() == 1);
-
- ModelArtifact model = (ModelArtifact) modelList.get(0);
- System.out.println(model.toString());
-
- assertTrue(model.getModelInvariantId().equalsIgnoreCase("3d560d81-57d0-438b-a2a1-5334dba0651a"));
- assertTrue(model.getModelNamespace().equalsIgnoreCase("http://org.openecomp.aai.inventory/v9"));
- assertTrue(model.getModelNamespaceVersion().equalsIgnoreCase("v9"));
- assertTrue(model.getType().toString().equalsIgnoreCase("MODEL"));
- System.out.println(model.getDependentModelIds().size());
- assertTrue(model.getDependentModelIds().size() == 0);
- } catch (Exception e) {
- e.printStackTrace();
- assertTrue(false);
- }
- }
-
- @Test
- public void testParseModelFileDeps() throws Exception {
- final String MODEL_FILE = "src/test/resources/models/AAI-stellService-service-1.xml";
-
- try {
- String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE)));
-
- ModelArtifactParser parser = new ModelArtifactParser();
- List<Artifact> modelList = parser.parse(fileString, "test-artifact");
-
- assertTrue(modelList.size() == 1);
-
- ModelArtifact model = (ModelArtifact) modelList.get(0);
- System.out.println(model.toString());
-
- assertTrue(model.getModelInvariantId().equalsIgnoreCase("fedf9da3-6a74-4813-8fa2-221a98b0e7ad"));
- assertTrue(model.getModelVerId().equalsIgnoreCase("e0373537-7f66-4094-9939-e2f5de6ff5f6"));
- assertTrue(model.getType().toString().equalsIgnoreCase("MODEL"));
- assertTrue(model.getDependentModelIds().size() == 3);
- assertTrue(model.getDependentModelIds()
- .contains("5c12984d-db0f-4300-a0e0-9791775cc40f|88bdbadf-db8a-490f-881e-c8effcbc3f66"));
- assertTrue(model.getDependentModelIds()
- .contains("959b7c09-9f34-4e5f-8b63-505381db176e|374d0899-bbc2-4403-9320-fe9bebef75c6"));
- } catch (Exception e) {
- e.printStackTrace();
- assertTrue(false);
- }
- }
-
- @Test
- public void testParseModelFileInvalidArtifact() throws Exception {
- final String MODEL_FILE = "src/test/resources/models/invalid-model.xml";
-
- try {
- String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE)));
-
- ModelArtifactParser parser = new ModelArtifactParser();
- List<Artifact> modelList = parser.parse(fileString, "test-artifact");
-
- assertTrue(modelList == null || modelList.isEmpty());
- } catch (Exception e) {
- e.printStackTrace();
- assertTrue(false);
- }
- }
-
- @Test
- public void testParseModelFileIncompleteArtifact() throws Exception {
- final String MODEL_FILE = "src/test/resources/models/incomplete-model.xml";
-
- try {
- String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE)));
-
- ModelArtifactParser parser = new ModelArtifactParser();
- List<Artifact> modelList = parser.parse(fileString, "test-artifact");
-
- assertTrue(modelList == null || modelList.isEmpty());
- } catch (Exception e) {
- e.printStackTrace();
- assertTrue(false);
- }
- }
-}
diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java b/src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java
index d1d54b7..8f4bf8d 100644
--- a/src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java
+++ b/src/test/java/org/onap/aai/modelloader/entity/model/ModelSorterTest.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -24,6 +24,7 @@ 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.isEmptyString;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
@@ -40,17 +41,18 @@ public class ModelSorterTest {
ModelArtifact model = buildTestModel();
ModelSorter.Node nodeA = new ModelSorter.Node(model);
ModelSorter.Node nodeB = new ModelSorter.Node(model);
- ModelSorter.Node nodeC = new ModelSorter.Node(model);
ModelSorter.Edge edgeA = new ModelSorter.Edge(nodeA, nodeB);
- ModelSorter.Edge edgeB = new ModelSorter.Edge(nodeA, nodeB);
- ModelSorter.Edge edgeC = new ModelSorter.Edge(nodeB, nodeA);
- ModelSorter.Edge edgeD = new ModelSorter.Edge(nodeA, nodeC);
assertThat(edgeA, is(equalTo(edgeA)));
assertThat(edgeA, is(not(equalTo(null))));
assertThat(edgeA, is(not(equalTo(model))));
+ ModelSorter.Edge edgeB = new ModelSorter.Edge(nodeA, nodeB);
+ ModelSorter.Edge edgeC = new ModelSorter.Edge(nodeB, nodeA);
+
+ ModelSorter.Node nodeC = new ModelSorter.Node(model);
+ ModelSorter.Edge edgeD = new ModelSorter.Edge(nodeA, nodeC);
assertThat(edgeA, is(equalTo(edgeB)));
assertThat(edgeA, is(not(equalTo(edgeC))));
assertThat(edgeA, is(not(equalTo(edgeD))));
@@ -60,18 +62,32 @@ public class ModelSorterTest {
public void nodeEquality() throws BabelArtifactParsingException {
ModelArtifact model = buildTestModel();
ModelSorter.Node nodeA = new ModelSorter.Node(model);
- ModelSorter.Node nodeB = new ModelSorter.Node(model);
assertThat(nodeA, is(equalTo(nodeA)));
assertThat(nodeA, is(not(equalTo(null))));
assertThat(nodeA, is(not(equalTo(model))));
+ ModelSorter.Node nodeB = new ModelSorter.Node(model);
assertThat(nodeA, is(equalTo(nodeB)));
assertThat(nodeA.toString(), is(equalTo(nodeB.toString())));
assertThat(nodeA, is(not(equalTo(new ModelSorter.Node(new ModelArtifact())))));
}
@Test
+ public void testToString() throws BabelArtifactParsingException {
+ ModelArtifact model = buildTestModel();
+
+ ModelSorter.Node nodeA = new ModelSorter.Node(model);
+ assertThat(nodeA.toString(), not(isEmptyString()));
+
+ ModelSorter.Node nodeB = new ModelSorter.Node(model);
+ nodeA.addEdge(nodeB);
+ assertThat(nodeA.toString(), not(isEmptyString()));
+ assertThat(nodeB.toString(), not(isEmptyString()));
+
+ }
+
+ @Test
public void noModels() throws BabelArtifactParsingException {
assertThat(new ModelSorter().sort(null), is(nullValue()));
assertThat(new ModelSorter().sort(Collections.emptyList()).size(), is(0));
@@ -84,20 +100,32 @@ public class ModelSorterTest {
@Test
public void multipleModels() throws BabelArtifactParsingException {
- Artifact a = buildTestModel("aaaa", "mvaaaa", "cccc|mvcccc");
- Artifact b = buildTestModel("bbbb", "mvbbbb", "aaaa|mvaaaa");
- Artifact c = buildTestModel("cccc", "mvcccc");
- List<Artifact> expected = Arrays.asList(c, a, b);
- assertThat(new ModelSorter().sort(Arrays.asList(a, b, c)), is(expected));
+ Artifact artA = buildTestModel("aaaa", "mvaaaa", "cccc|mvcccc");
+ Artifact artB = buildTestModel("bbbb", "mvbbbb", "aaaa|mvaaaa");
+ Artifact artC = buildTestModel("cccc", "mvcccc");
+ List<Artifact> expected = Arrays.asList(artC, artA, artB);
+ assertThat(new ModelSorter().sort(Arrays.asList(artA, artB, artC)), is(expected));
+ }
+
+
+ @Test
+ public void multipleModelsWithMultipleIncomingEdges() throws BabelArtifactParsingException {
+ ModelArtifact artA = buildTestModel("aaaa", "mvaaaa", "cccc|mvcccc");
+ Artifact artB = buildTestModel("bbbb", "mvbbbb", "aaaa|mvaaaa");
+ Artifact artC = buildTestModel("cccc", "mvcccc");
+ Artifact artD = buildTestModel("dddd", "mvdddd", "cccc|mvcccc");
+ artA.addDependentModelId("dddd|mvdddd");
+ List<Artifact> expected = Arrays.asList(artC, artD, artA, artB);
+ assertThat(new ModelSorter().sort(Arrays.asList(artA, artB, artC, artD)), is(expected));
}
@Test
public void multipleModelsAndNamedQueries() throws BabelArtifactParsingException {
- Artifact a = buildTestModel("aaaa", "1111", "cccc|2222");
+ Artifact artifact = buildTestModel("aaaa", "1111", "cccc|2222");
Artifact nq1 = buildTestNamedQuery("nq1", "aaaa|1111");
Artifact nq2 = buildTestNamedQuery("nqw", "existing-model");
- List<Artifact> expected = Arrays.asList(a, nq2, nq1);
- assertThat(new ModelSorter().sort(Arrays.asList(nq1, nq2, a)), is(expected));
+ List<Artifact> expected = Arrays.asList(artifact, nq2, nq1);
+ assertThat(new ModelSorter().sort(Arrays.asList(nq1, nq2, artifact)), is(expected));
}
@Test(expected = BabelArtifactParsingException.class)
diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java
index 82990de..2a951a8 100644
--- a/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java
+++ b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactParser.java b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactParser.java
new file mode 100644
index 0000000..aef0acc
--- /dev/null
+++ b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactParser.java
@@ -0,0 +1,102 @@
+/**
+ * ============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.entity.model;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.nullValue;
+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.onap.aai.modelloader.entity.Artifact;
+import org.springframework.util.CollectionUtils;
+
+public class TestModelArtifactParser {
+
+ private static final String MODEL_FILE = "src/test/resources/models/l3-network-widget.xml";
+ private static final String MODEL_FILE_SERVICE = "src/test/resources/models/AAI-stellService-service-1.xml";
+ private static final String MODEL_FILE_INCOMPLETE = "src/test/resources/models/incomplete-model.xml";
+ private static final String MODEL_FILE_INVALID = "src/test/resources/models/invalid-model.xml";
+
+ @Test
+ public void testParseModelFileNoDeps() throws Exception {
+ String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE)));
+
+ ModelArtifactParser parser = new ModelArtifactParser();
+ List<Artifact> modelList = parser.parse(fileString, "test-artifact");
+
+ assertThat(modelList.size(), is(1));
+
+ ModelArtifact model = (ModelArtifact) modelList.get(0);
+ assertThat(model.toString(), is(not(nullValue())));
+
+ assertThat(model.getModelInvariantId(), equalToIgnoringCase("3d560d81-57d0-438b-a2a1-5334dba0651a"));
+ assertThat(model.getModelNamespace(), equalToIgnoringCase("http://org.openecomp.aai.inventory/v9"));
+ assertThat(model.getModelNamespaceVersion(), equalToIgnoringCase("v9"));
+ assertThat(model.getType().toString(), equalToIgnoringCase("MODEL"));
+ assertThat(model.getDependentModelIds().size(), is(0));
+ }
+
+ @Test
+ public void testParseModelFileDeps() throws Exception {
+ String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE_SERVICE)));
+
+ ModelArtifactParser parser = new ModelArtifactParser();
+ List<Artifact> modelList = parser.parse(fileString, "test-artifact");
+
+ assertThat(modelList.size(), is(1));
+
+ ModelArtifact model = (ModelArtifact) modelList.get(0);
+ assertThat(model.toString(), is(not(nullValue())));
+ assertThat(model.getModelInvariantId(), equalToIgnoringCase("fedf9da3-6a74-4813-8fa2-221a98b0e7ad"));
+ assertThat(model.getModelVerId(), equalToIgnoringCase("e0373537-7f66-4094-9939-e2f5de6ff5f6"));
+ assertThat(model.getType().toString(), equalToIgnoringCase("MODEL"));
+ assertThat(model.getDependentModelIds().size(), is(3));
+ assertThat(model.getDependentModelIds()
+ .contains("5c12984d-db0f-4300-a0e0-9791775cc40f|88bdbadf-db8a-490f-881e-c8effcbc3f66"), is(true));
+ assertThat(model.getDependentModelIds()
+ .contains("959b7c09-9f34-4e5f-8b63-505381db176e|374d0899-bbc2-4403-9320-fe9bebef75c6"), is(true));
+ }
+
+ @Test
+ public void testParseModelFileInvalidArtifact() throws Exception {
+ String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE_INVALID)));
+
+ ModelArtifactParser parser = new ModelArtifactParser();
+ List<Artifact> modelList = parser.parse(fileString, "test-artifact");
+
+ assertThat(CollectionUtils.isEmpty(modelList), is(true));
+ }
+
+ @Test
+ public void testParseModelFileIncompleteArtifact() throws Exception {
+ String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE_INCOMPLETE)));
+
+ ModelArtifactParser parser = new ModelArtifactParser();
+ List<Artifact> modelList = parser.parse(fileString, "test-artifact");
+
+ assertThat(CollectionUtils.isEmpty(modelList), is(true));
+ }
+}
diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifactParserTest.java b/src/test/java/org/onap/aai/modelloader/entity/model/TestNamedQueryArtifactParser.java
index fa2d2d7..f676f8e 100644
--- a/src/test/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifactParserTest.java
+++ b/src/test/java/org/onap/aai/modelloader/entity/model/TestNamedQueryArtifactParser.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -20,6 +20,9 @@
*/
package org.onap.aai.modelloader.entity.model;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.Matchers.isEmptyString;
+import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.nio.file.Files;
@@ -28,12 +31,12 @@ import java.util.List;
import org.junit.Test;
import org.onap.aai.modelloader.entity.Artifact;
-public class NamedQueryArtifactParserTest {
+public class TestNamedQueryArtifactParser {
+
+ private static final String MODEL_FILE = "src/test/resources/models/named-query-wan-connector.xml";
@Test
public void testParseNamedQuery() throws Exception {
- final String MODEL_FILE = "src/test/resources/models/named-query-wan-connector.xml";
-
try {
String fileString = new String(Files.readAllBytes(Paths.get(MODEL_FILE)));
@@ -43,8 +46,8 @@ public class NamedQueryArtifactParserTest {
assertTrue(modelList.size() == 1);
NamedQueryArtifact model = (NamedQueryArtifact) modelList.get(0);
- System.out.println(model.toString());
+ assertThat(model.toString(), not(isEmptyString()));
assertTrue(model.getNamedQueryUuid().equalsIgnoreCase("94cac189-8d88-4d63-a194-f44214e080ff"));
assertTrue(model.getType().toString().equalsIgnoreCase("NAMED_QUERY"));
assertTrue(model.getDependentModelIds().size() == 4);
diff --git a/src/test/java/org/onap/aai/modelloader/extraction/ArtifactInfoExtractorTest.java b/src/test/java/org/onap/aai/modelloader/extraction/TestArtifactInfoExtractor.java
index 8ae2c7e..3957c7c 100644
--- a/src/test/java/org/onap/aai/modelloader/extraction/ArtifactInfoExtractorTest.java
+++ b/src/test/java/org/onap/aai/modelloader/extraction/TestArtifactInfoExtractor.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -33,14 +33,14 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.modelloader.fixture.ArtifactInfoBuilder;
-import org.onap.aai.modelloader.fixture.TestNotificationDataImpl;
+import org.onap.aai.modelloader.fixture.MockNotificationDataImpl;
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.INotificationData;
/**
- * Tests {@link ArtifactInfoExtractor}
+ * Tests {@link ArtifactInfoExtractor}.
*/
-public class ArtifactInfoExtractorTest {
+public class TestArtifactInfoExtractor {
private ArtifactInfoExtractor extractor;
@@ -65,7 +65,7 @@ public class ArtifactInfoExtractorTest {
@Test
public void extract_dataHasNullArtifacts() {
- doEmptyArtifactsTest(new TestNotificationDataImpl());
+ doEmptyArtifactsTest(new MockNotificationDataImpl());
}
@Test
diff --git a/src/test/java/org/onap/aai/modelloader/fixture/ArtifactInfoBuilder.java b/src/test/java/org/onap/aai/modelloader/fixture/ArtifactInfoBuilder.java
index aa475f3..a22e46f 100644
--- a/src/test/java/org/onap/aai/modelloader/fixture/ArtifactInfoBuilder.java
+++ b/src/test/java/org/onap/aai/modelloader/fixture/ArtifactInfoBuilder.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -42,12 +42,12 @@ public class ArtifactInfoBuilder {
*/
public static IArtifactInfo build(final String type, final String name, final String description,
final String version) {
- IArtifactInfo artifact = new ArtifactInfoImpl();
+ ArtifactInfoImpl artifact = new ArtifactInfoImpl();
- ((ArtifactInfoImpl) artifact).setArtifactType(type);
- ((ArtifactInfoImpl) artifact).setArtifactName(name);
- ((ArtifactInfoImpl) artifact).setArtifactDescription(description);
- ((ArtifactInfoImpl) artifact).setArtifactVersion(version);
+ artifact.setArtifactType(type);
+ artifact.setArtifactName(name);
+ artifact.setArtifactDescription(description);
+ artifact.setArtifactVersion(version);
return artifact;
}
@@ -63,7 +63,7 @@ public class ArtifactInfoBuilder {
* <p/>
*
* @param artifactInfoBits a two dimensional array of data used to build the artifacts
- * @return List<IArtifactInfo> a list of artifacts built from the given array of info
+ * @return List&lt;IArtifactInfo&gt; a list of artifacts built from the given array of info
*/
static List<IArtifactInfo> buildArtifacts(final String[][] artifactInfoBits) {
List<IArtifactInfo> artifacts = new ArrayList<>();
diff --git a/src/test/java/org/onap/aai/modelloader/fixture/TestNotificationDataImpl.java b/src/test/java/org/onap/aai/modelloader/fixture/MockNotificationDataImpl.java
index a7defdf..7851690 100644
--- a/src/test/java/org/onap/aai/modelloader/fixture/TestNotificationDataImpl.java
+++ b/src/test/java/org/onap/aai/modelloader/fixture/MockNotificationDataImpl.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -28,15 +28,15 @@ import org.onap.sdc.api.notification.IResourceInstance;
/**
* This class is an implementation of INotificationData for test purposes.
*/
-public class TestNotificationDataImpl implements INotificationData {
+public class MockNotificationDataImpl implements INotificationData {
- private String distributionID;
+ private String distributionId;
private List<IResourceInstance> resources;
private List<IArtifactInfo> serviceArtifacts;
@Override
public String getDistributionID() {
- return distributionID;
+ return distributionId;
}
@Override
@@ -70,7 +70,7 @@ public class TestNotificationDataImpl implements INotificationData {
}
@Override
- public IArtifactInfo getArtifactMetadataByUUID(String s) {
+ public IArtifactInfo getArtifactMetadataByUUID(String uuid) {
return null;
}
@@ -87,8 +87,8 @@ public class TestNotificationDataImpl implements INotificationData {
this.serviceArtifacts = serviceArtifacts;
}
- public void setDistributionID(String distributionID) {
- this.distributionID = distributionID;
+ public void setDistributionId(String distributionId) {
+ this.distributionId = distributionId;
}
@Override
diff --git a/src/test/java/org/onap/aai/modelloader/fixture/NotificationDataFixtureBuilder.java b/src/test/java/org/onap/aai/modelloader/fixture/NotificationDataFixtureBuilder.java
index 44f59a3..133a7af 100644
--- a/src/test/java/org/onap/aai/modelloader/fixture/NotificationDataFixtureBuilder.java
+++ b/src/test/java/org/onap/aai/modelloader/fixture/NotificationDataFixtureBuilder.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -32,17 +32,19 @@ import org.onap.sdc.api.notification.IResourceInstance;
public class NotificationDataFixtureBuilder {
private static final String DESCRIPTION_OF_RESOURCE = "description of resource";
- private static final INotificationData EMPTY_NOTIFICATION_DATA = new TestNotificationDataImpl();
+ private static final MockNotificationDataImpl EMPTY_NOTIFICATION_DATA = new MockNotificationDataImpl();
private static final String MODEL_QUERY_SPEC = "MODEL_QUERY_SPEC";
- private static final INotificationData NOTIFICATION_DATA_WITH_CATALOG_FILE = new TestNotificationDataImpl();
- private static final INotificationData NOTIFICATION_DATA_WITH_MODEL_QUERY_SPEC = new TestNotificationDataImpl();
- private static final INotificationData NOTIFICATION_DATA_WITH_INVALID_TYPE = new TestNotificationDataImpl();
- private static final INotificationData NOTIFICATION_DATA_WITH_ONE_OF_EACH = new TestNotificationDataImpl();
- private static final INotificationData NOTIFICATION_DATA_WITH_ONE_RESOURCE = new TestNotificationDataImpl();
- private static final INotificationData NOTIFICATION_DATA_WITH_ONE_SERVICE = new TestNotificationDataImpl();
- private static final INotificationData NOTIFICATION_DATA_WITH_ONE_SERVICE_AND_RESOURCES =
- new TestNotificationDataImpl();
- private static final INotificationData NOTIFICATION_DATA_WITH_TOSCA_CSAR_FILE = new TestNotificationDataImpl();
+ private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_CATALOG_FILE = new MockNotificationDataImpl();
+ private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_MODEL_QUERY_SPEC =
+ new MockNotificationDataImpl();
+ private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_INVALID_TYPE = new MockNotificationDataImpl();
+ private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_ONE_OF_EACH = new MockNotificationDataImpl();
+ private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_ONE_RESOURCE = new MockNotificationDataImpl();
+ private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_ONE_SERVICE = new MockNotificationDataImpl();
+ private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_ONE_SERVICE_AND_RESOURCES =
+ new MockNotificationDataImpl();
+ private static final MockNotificationDataImpl NOTIFICATION_DATA_WITH_TOSCA_CSAR_FILE =
+ new MockNotificationDataImpl();
private static final String RESOURCE = "resource";
private static final String TOSCA_CSAR = "TOSCA_CSAR";
private static final String INVALID_TYPE = "INVALID_TYPE";
@@ -61,8 +63,8 @@ public class NotificationDataFixtureBuilder {
}
private static void buildEmptyNotificationData() {
- ((TestNotificationDataImpl) EMPTY_NOTIFICATION_DATA).setResources(new ArrayList<>());
- ((TestNotificationDataImpl) EMPTY_NOTIFICATION_DATA).setServiceArtifacts(new ArrayList<>());
+ EMPTY_NOTIFICATION_DATA.setResources(new ArrayList<>());
+ EMPTY_NOTIFICATION_DATA.setServiceArtifacts(new ArrayList<>());
}
private static void buildWithCatalogFile() {
@@ -74,7 +76,7 @@ public class NotificationDataFixtureBuilder {
List<IArtifactInfo> artifacts =
ArtifactInfoBuilder.buildArtifacts(new String[][] {{"R", RESOURCE, DESCRIPTION_OF_RESOURCE, VERSION}});
resources.add(ResourceInstanceBuilder.build(artifacts));
- ((TestNotificationDataImpl) NOTIFICATION_DATA_WITH_ONE_RESOURCE).setResources(resources);
+ NOTIFICATION_DATA_WITH_ONE_RESOURCE.setResources(resources);
}
private static void buildWithModelQuerySpec() {
@@ -96,18 +98,18 @@ public class NotificationDataFixtureBuilder {
artifacts = ArtifactInfoBuilder
.buildArtifacts(new String[][] {{MODEL_QUERY_SPEC, "resource2", "description of resource2", VERSION}});
resources.add(ResourceInstanceBuilder.build(artifacts));
- ((TestNotificationDataImpl) NOTIFICATION_DATA_WITH_ONE_OF_EACH).setResources(resources);
+ NOTIFICATION_DATA_WITH_ONE_OF_EACH.setResources(resources);
}
private static void buildWithOneService() {
buildService("S", NOTIFICATION_DATA_WITH_ONE_SERVICE);
}
- private static void buildService(String type, INotificationData data) {
+ private static void buildService(String type, MockNotificationDataImpl data) {
List<IArtifactInfo> artifacts = new ArrayList<>();
artifacts.add(ArtifactInfoBuilder.build(type, "service", "description of service", "s1.0"));
- ((TestNotificationDataImpl) data).setDistributionID("ID");
- ((TestNotificationDataImpl) data).setServiceArtifacts(artifacts);
+ data.setDistributionId("ID");
+ data.setServiceArtifacts(artifacts);
}
private static void buildWithOneServiceAndResources() {
@@ -117,7 +119,7 @@ public class NotificationDataFixtureBuilder {
List<IArtifactInfo> artifacts = ArtifactInfoBuilder
.buildArtifacts(new String[][] {{TOSCA_CSAR, RESOURCE, "description of resource", VERSION}});
resources.add(ResourceInstanceBuilder.build(artifacts));
- ((TestNotificationDataImpl) NOTIFICATION_DATA_WITH_ONE_SERVICE_AND_RESOURCES).setResources(resources);
+ NOTIFICATION_DATA_WITH_ONE_SERVICE_AND_RESOURCES.setResources(resources);
}
private static void buildWithToscaCsarFile() {
diff --git a/src/test/java/org/onap/aai/modelloader/fixture/ResourceInstanceBuilder.java b/src/test/java/org/onap/aai/modelloader/fixture/ResourceInstanceBuilder.java
index 01e00f8..b88614b 100644
--- a/src/test/java/org/onap/aai/modelloader/fixture/ResourceInstanceBuilder.java
+++ b/src/test/java/org/onap/aai/modelloader/fixture/ResourceInstanceBuilder.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -36,10 +36,8 @@ class ResourceInstanceBuilder {
* @return IResourceInstance implementation of IResourceInstance for test purposes
*/
static IResourceInstance build(final List<IArtifactInfo> artifacts) {
- IResourceInstance instance = new TestResourceInstanceImpl();
-
- ((TestResourceInstanceImpl) instance).setArtifacts(artifacts);
-
+ TestResourceInstanceImpl instance = new TestResourceInstanceImpl();
+ instance.setArtifacts(artifacts);
return instance;
}
}
diff --git a/src/test/java/org/onap/aai/modelloader/fixture/TestResourceInstanceImpl.java b/src/test/java/org/onap/aai/modelloader/fixture/TestResourceInstanceImpl.java
index 7eaebb5..0f2751b 100644
--- a/src/test/java/org/onap/aai/modelloader/fixture/TestResourceInstanceImpl.java
+++ b/src/test/java/org/onap/aai/modelloader/fixture/TestResourceInstanceImpl.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
diff --git a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManagerTest.java b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java
index 9d6f3c4..d8cb19a 100644
--- a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDeploymentManagerTest.java
+++ b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -20,7 +20,8 @@
*/
package org.onap.aai.modelloader.notification;
-import static org.junit.Assert.assertFalse;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
@@ -45,14 +46,15 @@ import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifactHandler;
import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException;
import org.onap.aai.modelloader.entity.model.ModelArtifactHandler;
import org.onap.aai.modelloader.extraction.InvalidArchiveException;
+import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder;
+import org.onap.aai.modelloader.service.ArtifactDeploymentManager;
import org.onap.aai.modelloader.util.ArtifactTestUtils;
-import org.onap.sdc.api.IDistributionClient;
import org.onap.sdc.api.notification.INotificationData;
/**
- * Tests {@link ArtifactDeploymentManager }
+ * Tests {@link ArtifactDeploymentManager}.
*/
-public class ArtifactDeploymentManagerTest {
+public class TestArtifactDeploymentManager {
private static final String CONFIG_FILE = "model-loader.properties";
private static final String SHOULD_HAVE_RETURNED_FALSE = "This should have returned false";
@@ -60,39 +62,53 @@ public class ArtifactDeploymentManagerTest {
private Properties configProperties;
private ArtifactDeploymentManager manager;
- private IDistributionClient mockDistributionClient;
private ModelArtifactHandler mockModelArtifactHandler;
- private NotificationPublisher mockNotificationPublisher;
private VnfCatalogArtifactHandler mockVnfCatalogArtifactHandler;
@Before
public void setup() throws IOException {
configProperties = new Properties();
configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE));
- ModelLoaderConfig config = new ModelLoaderConfig(configProperties, null);
- mockDistributionClient = mock(IDistributionClient.class);
mockModelArtifactHandler = mock(ModelArtifactHandler.class);
- mockNotificationPublisher = mock(NotificationPublisher.class);
mockVnfCatalogArtifactHandler = mock(VnfCatalogArtifactHandler.class);
- manager = new ArtifactDeploymentManager(mockDistributionClient, config);
+ manager = new ArtifactDeploymentManager(new ModelLoaderConfig(configProperties, null));
Whitebox.setInternalState(manager, "modelArtifactHandler", mockModelArtifactHandler);
- Whitebox.setInternalState(manager, "notificationPublisher", mockNotificationPublisher);
Whitebox.setInternalState(manager, "vnfCatalogArtifactHandler", mockVnfCatalogArtifactHandler);
}
@After
public void tearDown() {
configProperties = null;
- mockDistributionClient = null;
mockModelArtifactHandler = null;
- mockNotificationPublisher = null;
mockVnfCatalogArtifactHandler = null;
manager = null;
}
+ @Test
+ public void deploy_csarDeploymentsFailed() throws IOException, BabelArtifactParsingException {
+ INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile();
+ byte[] xml = new ArtifactTestUtils().loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml");
+ List<BabelArtifact> toscaArtifacts = setupTest(xml, data);
+ List<Artifact> modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts);
+
+ when(mockModelArtifactHandler.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(),
+ any());
+ Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).pushArtifacts(eq(modelArtifacts),
+ eq(data.getDistributionID()), any(), any());
+ Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList<Artifact>()), eq(data.getDistributionID()),
+ any());
+ Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(eq(new ArrayList<Artifact>()),
+ eq(data.getDistributionID()), any());
+ }
+
private List<BabelArtifact> setupTest(byte[] xml, INotificationData data) throws IOException {
List<BabelArtifact> toscaArtifacts = new ArrayList<>();
org.onap.sdc.api.notification.IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0);
@@ -115,11 +131,8 @@ public class ArtifactDeploymentManagerTest {
when(mockModelArtifactHandler.pushArtifacts(any(), any(), any(), any())).thenReturn(true);
when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any()))
.thenReturn(false);
- Mockito.doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data,
- data.getServiceArtifacts().get(0));
- assertFalse(SHOULD_HAVE_RETURNED_FALSE,
- manager.deploy(data, data.getServiceArtifacts(), new ArrayList<>(), catalogFiles));
+ assertThat(SHOULD_HAVE_RETURNED_FALSE, manager.deploy(data, new ArrayList<>(), catalogFiles), is(false));
Mockito.verify(mockModelArtifactHandler).pushArtifacts(eq(new ArrayList<Artifact>()),
eq(data.getDistributionID()), any(), any());
@@ -129,15 +142,27 @@ public class ArtifactDeploymentManagerTest {
any());
Mockito.verify(mockVnfCatalogArtifactHandler).rollback(eq(new ArrayList<Artifact>()),
eq(data.getDistributionID()), any());
- Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data,
- data.getServiceArtifacts().get(0));
}
- private void doFailedCombinedTests(boolean modelsOK, boolean catalogsOK)
+ @Test
+ public void testNoArtifactsDeployed() throws IOException, BabelArtifactParsingException, InvalidArchiveException {
+ doFailedCombinedTests(false, false);
+ }
+
+ @Test
+ public void testModelsNotDeployed() throws IOException, BabelArtifactParsingException, InvalidArchiveException {
+ doFailedCombinedTests(false, true);
+ }
+
+ @Test
+ public void testCatalogsNotDeployed() throws IOException, BabelArtifactParsingException, InvalidArchiveException {
+ doFailedCombinedTests(true, false);
+ }
+
+ private void doFailedCombinedTests(boolean modelsDeployed, boolean catalogsDeployed)
throws IOException, BabelArtifactParsingException, InvalidArchiveException {
INotificationData data = getNotificationDataWithOneOfEach();
- ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils();
- byte[] xml = artifactTestUtils.loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml");
+ byte[] xml = new ArtifactTestUtils().loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml");
List<BabelArtifact> toscaArtifacts = setupTest(xml, data);
List<Artifact> modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts);
@@ -145,35 +170,25 @@ public class ArtifactDeploymentManagerTest {
catalogFiles.add(new VnfCatalogArtifact("Some catalog content"));
when(mockVnfCatalogArtifactHandler.pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()), any(), any()))
- .thenReturn(catalogsOK);
+ .thenReturn(catalogsDeployed);
when(mockModelArtifactHandler.pushArtifacts(eq(modelArtifacts), eq(data.getDistributionID()), any(), any()))
- .thenReturn(modelsOK);
+ .thenReturn(modelsDeployed);
- Mockito.doNothing().when(mockNotificationPublisher).publishDeploySuccess(mockDistributionClient, data,
- data.getServiceArtifacts().get(0));
- Mockito.doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data,
- data.getServiceArtifacts().get(0));
-
- assertFalse(SHOULD_HAVE_RETURNED_FALSE,
- manager.deploy(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles));
+ 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(),
any());
- if (modelsOK) {
+ if (modelsDeployed) {
Mockito.verify(mockVnfCatalogArtifactHandler).pushArtifacts(eq(catalogFiles), eq(data.getDistributionID()),
any(), any());
}
- if (modelsOK && catalogsOK) {
- Mockito.verify(mockNotificationPublisher).publishDeploySuccess(mockDistributionClient, data,
- data.getServiceArtifacts().get(0));
+ if (modelsDeployed && catalogsDeployed) {
Mockito.verify(mockModelArtifactHandler, Mockito.never()).rollback(any(), any(), any());
Mockito.verify(mockVnfCatalogArtifactHandler, Mockito.never()).rollback(any(), any(), any());
} else {
- Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data,
- data.getServiceArtifacts().get(0));
- if (modelsOK) {
+ if (modelsDeployed) {
Mockito.verify(mockModelArtifactHandler).rollback(eq(new ArrayList<Artifact>()),
eq(data.getDistributionID()), any());
Mockito.verify(mockVnfCatalogArtifactHandler).rollback(eq(new ArrayList<Artifact>()),
@@ -186,4 +201,35 @@ public class ArtifactDeploymentManagerTest {
}
}
+ /**
+ * Deploy both models and VNF images.
+ *
+ * @throws IOException
+ * @throws BabelArtifactParsingException
+ * @throws InvalidArchiveException
+ */
+ @Test
+ public void testDeploySuccess() throws IOException, BabelArtifactParsingException, InvalidArchiveException {
+ INotificationData data = getNotificationDataWithOneOfEach();
+ byte[] xml = new ArtifactTestUtils().loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml");
+ List<BabelArtifact> toscaArtifacts = setupTest(xml, data);
+ List<Artifact> modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts);
+
+ 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()))
+ .thenReturn(true);
+ when(mockModelArtifactHandler.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()),
+ any(), any());
+ Mockito.verify(mockModelArtifactHandler).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());
+ }
}
diff --git a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java
index 2c02487..030a0ff 100644
--- a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java
+++ b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -20,8 +20,10 @@
*/
package org.onap.aai.modelloader.notification;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.collection.IsEmptyCollection.empty;
+import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -32,14 +34,10 @@ import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.ge
import static org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile;
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 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;
@@ -48,10 +46,12 @@ import org.mockito.Mockito;
import org.mockito.internal.util.reflection.Whitebox;
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.entity.model.BabelArtifactParsingException;
import org.onap.aai.modelloader.restclient.BabelServiceClient;
-import org.onap.aai.modelloader.restclient.BabelServiceClient.BabelServiceException;
-import org.onap.aai.modelloader.restclient.BabelServiceClientFactory;
+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;
@@ -61,13 +61,9 @@ import org.onap.sdc.impl.DistributionClientDownloadResultImpl;
import org.onap.sdc.utils.DistributionActionResultEnum;
/**
- * Tests {@link ArtifactDownloadManager}
+ * Tests {@link ArtifactDownloadManager}.
*/
-public class ArtifactDownloadManagerTest {
-
- private static final String FALSE_SHOULD_HAVE_BEEN_RETURNED = "A value of 'false' should have been returned";
- private static final String OOPS = "oops";
- private static final String TRUE_SHOULD_HAVE_BEEN_RETURNED = "A value of 'true' should have been returned";
+public class TestArtifactDownloadManager {
private ArtifactDownloadManager downloadManager;
private BabelServiceClient mockBabelClient;
@@ -82,7 +78,7 @@ public class ArtifactDownloadManagerTest {
mockDistributionClient = mock(IDistributionClient.class);
mockNotificationPublisher = mock(NotificationPublisher.class);
mockBabelArtifactConverter = mock(BabelArtifactConverter.class);
- mockClientFactory = mock(BabelServiceClientFactory.class);
+ mockClientFactory = mock(HttpsBabelServiceClientFactory.class);
when(mockClientFactory.create(Mockito.any())).thenReturn(mockBabelClient);
Properties configProperties = new Properties();
@@ -101,61 +97,50 @@ public class ArtifactDownloadManagerTest {
mockNotificationPublisher = null;
}
+ /**
+ * Test downloading zero artifacts from SDC.
+ */
@Test
- public void downloadArtifacts_emptyListSupplied() {
- List<org.onap.aai.modelloader.entity.Artifact> modelFiles = new ArrayList<>();
- List<org.onap.aai.modelloader.entity.Artifact> catalogFiles = new ArrayList<>();
-
- assertTrue(TRUE_SHOULD_HAVE_BEEN_RETURNED, downloadManager
- .downloadArtifacts(getNotificationDataWithOneService(), new ArrayList<>(), modelFiles, catalogFiles));
-
+ public void testDownloadWithZeroArtifacts() {
+ List<Artifact> modelFiles = new ArrayList<>();
+ List<Artifact> catalogFiles = new ArrayList<>();
+ assertThat(downloadManager.downloadArtifacts(getNotificationDataWithOneService(), new ArrayList<>(), modelFiles,
+ catalogFiles), is(true));
+ assertThat(modelFiles, is(empty()));
+ assertThat(catalogFiles, is(empty()));
Mockito.verifyZeroInteractions(mockBabelClient, mockDistributionClient, mockNotificationPublisher,
mockBabelArtifactConverter);
}
@Test
- public void downloadArtifacts_artifactDownloadFails() {
+ public void testArtifactDownloadFails() {
INotificationData data = getNotificationDataWithOneService();
IArtifactInfo artifact = data.getServiceArtifacts().get(0);
- when(mockDistributionClient.download(artifact))
- .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.FAIL, OOPS, null));
+ String errorMessage = "error msg";
+ when(mockDistributionClient.download(artifact)).thenReturn(
+ createDistributionClientDownloadResult(DistributionActionResultEnum.FAIL, errorMessage, null));
doNothing().when(mockNotificationPublisher).publishDownloadFailure(mockDistributionClient, data, artifact,
- OOPS);
+ errorMessage);
- assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED,
- downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null));
+ assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null), is(false));
Mockito.verify(mockDistributionClient).download(artifact);
- Mockito.verify(mockNotificationPublisher).publishDownloadFailure(mockDistributionClient, data, artifact, OOPS);
+ Mockito.verify(mockNotificationPublisher).publishDownloadFailure(mockDistributionClient, data, artifact,
+ errorMessage);
Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter);
}
- private IDistributionClientDownloadResult createDistributionClientDownloadResult(
- DistributionActionResultEnum status, String message, byte[] payload) {
- IDistributionClientDownloadResult downloadResult = new DistributionClientDownloadResultImpl(status, message);
-
- ((DistributionClientDownloadResultImpl) downloadResult).setArtifactPayload(payload);
-
- return downloadResult;
- }
-
@Test
- public void downloadArtifacts_noSuchAlgorithmExceptionFromCreatingBabelClient() throws Exception {
- doCreateBabelClientFailureTest(NoSuchAlgorithmException.class);
- }
-
- @SuppressWarnings("unchecked")
- private void doCreateBabelClientFailureTest(Class<? extends Throwable> exception) throws Exception {
- when(mockClientFactory.create(Mockito.any())).thenThrow(exception);
+ public void testErrorCreatingBabelClient() throws Exception {
+ when(mockClientFactory.create(Mockito.any())).thenThrow(new BabelServiceClientException(new Exception()));
INotificationData data = getNotificationDataWithToscaCsarFile();
IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0);
setupValidDownloadCsarMocks(data, artifactInfo, new ArtifactTestUtils());
doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo);
- assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED,
- downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null));
+ assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null), is(false));
Mockito.verify(mockDistributionClient).download(artifactInfo);
Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo);
@@ -165,49 +150,17 @@ public class ArtifactDownloadManagerTest {
}
@Test
- public void downloadArtifacts_keyStoreExceptionFromCreatingBabelClient() throws Exception {
- doCreateBabelClientFailureTest(KeyStoreException.class);
- }
-
- @Test
- public void downloadArtifacts_certificateExceptionFromCreatingBabelClient() throws Exception {
- doCreateBabelClientFailureTest(CertificateException.class);
- }
-
- @Test
- public void downloadArtifacts_iOExceptionFromCreatingBabelClient() throws Exception {
- doCreateBabelClientFailureTest(IOException.class);
- }
-
- @Test
- public void downloadArtifacts_unrecoverableKeyExceptionFromCreatingBabelClient() throws Exception {
- doCreateBabelClientFailureTest(UnrecoverableKeyException.class);
- }
-
- @Test
- public void downloadArtifacts_keyManagementExceptionFromCreatingBabelClient() throws Exception {
- doCreateBabelClientFailureTest(KeyManagementException.class);
- }
-
- /**
- * Test disabled as exception handling needs to be reworked
- *
- * @throws IOException
- */
- @SuppressWarnings("unchecked")
- @Test
- public void downloadArtifacts_invalidToscaCsarFile() throws IOException, BabelServiceException {
+ public void downloadArtifacts_invalidToscaCsarFile() throws IOException, BabelServiceClientException {
INotificationData data = getNotificationDataWithToscaCsarFile();
IArtifactInfo artifact = data.getServiceArtifacts().get(0);
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(Matchers.any(), Matchers.anyString(), Matchers.anyString(),
- Matchers.anyString())).thenThrow(BabelServiceException.class);
+ Matchers.anyString())).thenThrow(new BabelServiceClientException(""));
doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact);
- assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED,
- downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null));
+ assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null), is(false));
Mockito.verify(mockDistributionClient).download(artifact);
Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
@@ -230,8 +183,8 @@ public class ArtifactDownloadManagerTest {
DistributionActionResultEnum.SUCCESS, null, "This is not a valid Model Query Spec".getBytes()));
doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
- assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED,
- downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, null));
+ assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, null),
+ is(false));
Mockito.verify(mockDistributionClient).download(artifact);
Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
@@ -242,7 +195,7 @@ public class ArtifactDownloadManagerTest {
@Test
public void downloadArtifacts_validToscaCsarFile()
- throws IOException, BabelServiceException, BabelArtifactParsingException {
+ throws IOException, BabelServiceClientException, BabelArtifactParsingException {
INotificationData data = getNotificationDataWithToscaCsarFile();
IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0);
@@ -250,10 +203,9 @@ public class ArtifactDownloadManagerTest {
List<org.onap.aai.modelloader.entity.Artifact> modelArtifacts = new ArrayList<>();
List<org.onap.aai.modelloader.entity.Artifact> catalogFiles = new ArrayList<>();
- assertTrue(TRUE_SHOULD_HAVE_BEEN_RETURNED,
- downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles));
-
- assertTrue("There should not have been any catalog files", catalogFiles.size() == 0);
+ assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles),
+ is(true));
+ assertThat(catalogFiles.size(), is(0));
Mockito.verify(mockDistributionClient).download(artifactInfo);
Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo);
@@ -264,7 +216,7 @@ public class ArtifactDownloadManagerTest {
}
private void setupValidDownloadCsarMocks(INotificationData data, IArtifactInfo artifactInfo,
- ArtifactTestUtils artifactTestUtils) throws IOException, BabelServiceException {
+ ArtifactTestUtils artifactTestUtils) throws IOException, BabelServiceClientException {
when(mockDistributionClient.download(artifactInfo))
.thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.SUCCESS, null,
artifactTestUtils.loadResource("compressedArtifacts/service-VscpaasTest-csar.csar")));
@@ -280,20 +232,19 @@ public class ArtifactDownloadManagerTest {
}
@Test
- public void downloadArtifacts_validModelQuerySpec()
- throws IOException, BabelServiceException, BabelArtifactParsingException {
- ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils();
+ public void downloadArtifactsWithValidModelQuerySpec()
+ throws IOException, BabelServiceClientException, BabelArtifactParsingException {
INotificationData data = getNotificationDataWithModelQuerySpec();
IArtifactInfo artifact = data.getServiceArtifacts().get(0);
- setupValidModelQuerySpecMocks(artifactTestUtils, data, artifact);
+ setupValidModelQuerySpecMocks(new ArtifactTestUtils(), data, artifact);
List<org.onap.aai.modelloader.entity.Artifact> modelFiles = new ArrayList<>();
List<org.onap.aai.modelloader.entity.Artifact> catalogFiles = new ArrayList<>();
- assertTrue(TRUE_SHOULD_HAVE_BEEN_RETURNED,
- downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelFiles, catalogFiles));
+ assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelFiles, catalogFiles),
+ is(true));
- assertTrue("There should have been some model artifacts", !modelFiles.isEmpty());
- assertTrue("There should not have been any catalog artifacts", catalogFiles.isEmpty());
+ assertThat(modelFiles, is(not(IsEmptyCollection.empty())));
+ assertThat(catalogFiles, is(empty()));
Mockito.verify(mockDistributionClient).download(artifact);
Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
@@ -311,7 +262,7 @@ public class ArtifactDownloadManagerTest {
@Test
public void downloadArtifacts_validCsarAndModelFiles()
- throws IOException, BabelServiceException, BabelArtifactParsingException {
+ throws IOException, BabelServiceClientException, BabelArtifactParsingException {
ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils();
INotificationData data = getNotificationDataWithOneOfEach();
List<IArtifactInfo> artifacts = new ArrayList<>();
@@ -327,8 +278,7 @@ public class ArtifactDownloadManagerTest {
List<org.onap.aai.modelloader.entity.Artifact> modelFiles = new ArrayList<>();
List<org.onap.aai.modelloader.entity.Artifact> catalogFiles = new ArrayList<>();
- assertTrue(TRUE_SHOULD_HAVE_BEEN_RETURNED,
- downloadManager.downloadArtifacts(data, artifacts, modelFiles, catalogFiles));
+ assertThat(downloadManager.downloadArtifacts(data, artifacts, modelFiles, catalogFiles), is(true));
Mockito.verify(mockDistributionClient).download(serviceArtifact);
Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, serviceArtifact);
@@ -360,12 +310,12 @@ public class ArtifactDownloadManagerTest {
when(mockBabelClient.postArtifact(Matchers.any(), Matchers.anyString(), Matchers.anyString(),
Matchers.anyString())).thenReturn(createBabelArtifacts());
- List<org.onap.aai.modelloader.entity.Artifact> modelArtifacts = new ArrayList<>();
- List<org.onap.aai.modelloader.entity.Artifact> catalogFiles = new ArrayList<>();
- assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED,
- downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles));
-
- assertTrue("There should not have been any catalog files", catalogFiles.size() == 0);
+ List<Artifact> modelArtifacts = new ArrayList<>();
+ List<Artifact> catalogFiles = new ArrayList<>();
+ assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), modelArtifacts, catalogFiles),
+ is(false));
+ assertThat(modelArtifacts, is(empty()));
+ assertThat(catalogFiles, is(empty()));
Mockito.verify(mockDistributionClient).download(artifactInfo);
Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo);
@@ -375,24 +325,27 @@ public class ArtifactDownloadManagerTest {
}
@Test
- public void downloadArtifacts_invalidType()
- throws IOException, BabelServiceException, BabelArtifactParsingException {
+ public void downloadArtifactsWithInvalidType()
+ throws IOException, BabelServiceClientException, BabelArtifactParsingException {
INotificationData data = getNotificationDataWithInvalidType();
IArtifactInfo artifact = data.getServiceArtifacts().get(0);
- List<org.onap.aai.modelloader.entity.Artifact> catalogArtifacts = new ArrayList<>();
-
when(mockDistributionClient.download(artifact)).thenReturn(createDistributionClientDownloadResult(
DistributionActionResultEnum.SUCCESS, null, "This content does not matter.".getBytes()));
doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
- assertFalse(FALSE_SHOULD_HAVE_BEEN_RETURNED,
- downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, catalogArtifacts));
-
+ assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, new ArrayList<>()),
+ is(false));
Mockito.verify(mockDistributionClient).download(artifact);
Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact);
Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact);
-
Mockito.verifyZeroInteractions(mockBabelClient, mockBabelArtifactConverter);
}
+
+ private IDistributionClientDownloadResult createDistributionClientDownloadResult(
+ DistributionActionResultEnum status, String message, byte[] payload) {
+ DistributionClientDownloadResultImpl downloadResult = new DistributionClientDownloadResultImpl(status, message);
+ downloadResult.setArtifactPayload(payload);
+ return downloadResult;
+ }
}
diff --git a/src/test/java/org/onap/aai/modelloader/notification/BabelArtifactConverterTest.java b/src/test/java/org/onap/aai/modelloader/notification/TestBabelArtifactConverter.java
index e9e6059..718c415 100644
--- a/src/test/java/org/onap/aai/modelloader/notification/BabelArtifactConverterTest.java
+++ b/src/test/java/org/onap/aai/modelloader/notification/TestBabelArtifactConverter.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -20,6 +20,7 @@
*/
package org.onap.aai.modelloader.notification;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -28,15 +29,18 @@ import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.onap.aai.babel.service.data.BabelArtifact;
+import org.onap.aai.modelloader.entity.Artifact;
+import org.onap.aai.modelloader.entity.ArtifactType;
import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException;
import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder;
+import org.onap.aai.modelloader.util.ArtifactTestUtils;
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.INotificationData;
/**
- * Tests {@link BabelArtifactConverter}
+ * Tests {@link BabelArtifactConverter}.
*/
-public class BabelArtifactConverterTest {
+public class TestBabelArtifactConverter {
@Test(expected = NullPointerException.class)
public void convert_nullToscaFiles() throws BabelArtifactParsingException {
@@ -45,20 +49,20 @@ public class BabelArtifactConverterTest {
}
@Test
- public void convert_emptyToscaFiles() throws BabelArtifactParsingException {
+ public void testEmptyToscaFiles() throws BabelArtifactParsingException {
assertTrue("Nothing should have been returned",
new BabelArtifactConverter().convertToModel(new ArrayList<>()).isEmpty());
}
@Test(expected = BabelArtifactParsingException.class)
- public void convert_problemWithConvertedXML() throws IOException, BabelArtifactParsingException {
- byte[] problemXML =
+ 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();
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");
@@ -74,4 +78,18 @@ public class BabelArtifactConverterTest {
return toscaArtifacts;
}
+
+ @Test
+ public void convert_singleResourceFile() throws BabelArtifactParsingException, IOException {
+ INotificationData data = NotificationDataFixtureBuilder.getNotificationDataWithToscaCsarFile();
+
+ byte[] xml = new ArtifactTestUtils().loadResource("convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml");
+ List<BabelArtifact> toscaArtifacts = setupTest(xml, data);
+
+ List<Artifact> modelArtifacts = new BabelArtifactConverter().convertToModel(toscaArtifacts);
+
+ assertTrue("There should have been 1 artifact", modelArtifacts.size() == 1);
+ assertEquals(new String(xml), modelArtifacts.get(0).getPayload());
+ assertEquals(ArtifactType.MODEL, modelArtifacts.get(0).getType());
+ }
}
diff --git a/src/test/java/org/onap/aai/modelloader/notification/EventCallbackTest.java b/src/test/java/org/onap/aai/modelloader/notification/TestEventCallback.java
index 57a4c09..1215a7b 100644
--- a/src/test/java/org/onap/aai/modelloader/notification/EventCallbackTest.java
+++ b/src/test/java/org/onap/aai/modelloader/notification/TestEventCallback.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -36,13 +36,14 @@ import org.mockito.internal.util.reflection.Whitebox;
import org.onap.aai.modelloader.config.ModelLoaderConfig;
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;
/**
- * Tests {@link EventCallback}
+ * Tests {@link EventCallback}.
*/
-public class EventCallbackTest {
+public class TestEventCallback {
private static final String CONFIG_FILE = "model-loader.properties";
@@ -53,6 +54,7 @@ public class EventCallbackTest {
private ArtifactDeploymentManager mockArtifactDeploymentManager;
private ArtifactDownloadManager mockArtifactDownloadManager;
private IDistributionClient mockDistributionClient;
+ private NotificationPublisher mockNotificationPublisher;
@Before
public void setup() throws IOException {
@@ -63,11 +65,13 @@ public class EventCallbackTest {
mockArtifactDeploymentManager = mock(ArtifactDeploymentManager.class);
mockArtifactDownloadManager = mock(ArtifactDownloadManager.class);
mockDistributionClient = mock(IDistributionClient.class);
+ mockNotificationPublisher = mock(NotificationPublisher.class);
eventCallback = new EventCallback(mockDistributionClient, config);
Whitebox.setInternalState(eventCallback, "artifactDeploymentManager", mockArtifactDeploymentManager);
Whitebox.setInternalState(eventCallback, "artifactDownloadManager", mockArtifactDownloadManager);
+ Whitebox.setInternalState(eventCallback, "notificationPublisher", mockNotificationPublisher);
}
@After
@@ -103,14 +107,13 @@ public class EventCallbackTest {
when(mockArtifactDownloadManager.downloadArtifacts(any(INotificationData.class), any(List.class),
any(List.class), any(List.class))).thenReturn(true);
- when(mockArtifactDeploymentManager.deploy(any(INotificationData.class), any(List.class), any(List.class),
- any(List.class))).thenReturn(true);
+ when(mockArtifactDeploymentManager.deploy(any(INotificationData.class), any(List.class), any(List.class)))
+ .thenReturn(true);
eventCallback.activateCallback(data);
verify(mockArtifactDownloadManager).downloadArtifacts(any(INotificationData.class), any(List.class),
any(List.class), any(List.class));
- verify(mockArtifactDeploymentManager).deploy(any(INotificationData.class), any(List.class), any(List.class),
- any(List.class));
+ verify(mockArtifactDeploymentManager).deploy(any(INotificationData.class), any(List.class), any(List.class));
}
}
diff --git a/src/test/java/org/onap/aai/modelloader/service/TestNotificationDataImpl.java b/src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java
index 395b1f3..c045910 100644
--- a/src/test/java/org/onap/aai/modelloader/service/TestNotificationDataImpl.java
+++ b/src/test/java/org/onap/aai/modelloader/notification/TestNotificationDataImpl.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -18,7 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.modelloader.service;
+package org.onap.aai.modelloader.notification;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
@@ -37,7 +37,6 @@ public class TestNotificationDataImpl {
public void testGettersAndSetters() {
NotificationDataImpl data = new NotificationDataImpl();
String distributionId = "testid";
- String context = "testcontext";
data.setDistributionID(distributionId);
assertThat(data.getDistributionID(), is(equalTo(distributionId)));
@@ -53,6 +52,7 @@ public class TestNotificationDataImpl {
assertThat(data.getServiceArtifacts().size(), is(0));
// Unsupported method!
+ String context = "testcontext";
data.setWorkloadContext(context);
assertThat(data.getWorkloadContext(), is(equalTo(null)));
}
diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java b/src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java
index bc91b2f..4939fd6 100644
--- a/src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java
+++ b/src/test/java/org/onap/aai/modelloader/notification/TestNotificationPublisher.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
diff --git a/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java b/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java
new file mode 100644
index 0000000..604aca7
--- /dev/null
+++ b/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java
@@ -0,0 +1,41 @@
+/**
+ * ============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.restclient;
+
+import java.util.Collections;
+import java.util.List;
+import org.onap.aai.babel.service.data.BabelArtifact;
+import org.onap.aai.modelloader.config.ModelLoaderConfig;
+
+/**
+ * Mocked Client for interfacing with Babel.
+ *
+ */
+public class MockBabelServiceClient implements BabelServiceClient {
+
+ public MockBabelServiceClient(ModelLoaderConfig config) throws BabelServiceClientException {}
+
+ @Override
+ public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
+ String transactionId) throws BabelServiceClientException {
+ return Collections.emptyList();
+ }
+}
diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java
new file mode 100644
index 0000000..8b1b22c
--- /dev/null
+++ b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java
@@ -0,0 +1,144 @@
+/**
+ * ============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.restclient;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.onap.aai.modelloader.config.ModelLoaderConfig;
+import org.onap.aai.modelloader.entity.ArtifactType;
+import org.onap.aai.modelloader.entity.model.ModelArtifact;
+import org.onap.aai.modelloader.entity.model.ModelArtifactParser;
+import org.onap.aai.restclient.client.OperationResult;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+public class TestAaiRestClient {
+
+ private static final String MODEL_FILE = "src/test/resources/models/l3-network-widget.xml";
+
+ // This test requires a running A&AI system. To test locally, annotate with org.junit.Test
+ public void testRestClient() throws Exception {
+ Properties props = new Properties();
+ props.setProperty("ml.distribution.ARTIFACT_TYPES", "MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG");
+ props.setProperty("ml.aai.BASE_URL", "https://localhost:8443");
+ props.setProperty("ml.aai.MODEL_URL", "/aai/v9/service-design-and-creation/models/model/");
+ props.setProperty("ml.aai.KEYSTORE_FILE", "aai-client-cert.p12");
+ props.setProperty("ml.aai.KEYSTORE_PASSWORD", "OBF:1i9a1u2a1unz1lr61wn51wn11lss1unz1u301i6o");
+
+ ModelLoaderConfig config = new ModelLoaderConfig(props, ".");
+
+ File xmlFile = new File(MODEL_FILE);
+ DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
+ dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ Document doc = dbFactory.newDocumentBuilder().parse(xmlFile);
+
+ NodeList nodesList = doc.getDocumentElement().getChildNodes();
+
+ // Get the model IDs
+
+ // @formatter:off
+ String modelInvariantId =
+ getNodesStream(nodesList)
+ .filter(childNode -> childNode.getNodeName().equals(ModelArtifactParser.MODEL_INVARIANT_ID))
+ .findFirst()
+ .map(Node::getTextContent)
+ .orElse(null);
+
+ String modelId = getNodesStream(nodesList)
+ .flatMap(n -> getNodesStream(n.getChildNodes()))
+ .filter(childNode -> childNode.getNodeName().equals(ModelArtifactParser.MODEL_VER))
+ .findFirst()
+ .map(n -> n.getChildNodes().item(1).getTextContent())
+ .orElse(null);
+ // @formatter:on
+
+ try {
+ // Build the model artifact
+ ModelArtifact model = new ModelArtifact();
+ model.setModelInvariantId(modelInvariantId);
+ model.setModelVerId(modelId);
+ model.setPayload(readFile(MODEL_FILE));
+ model.setModelNamespace("http://org.openecomp.aai.inventory/v9");
+
+ AaiRestClient aaiClient = new AaiRestClient(config);
+
+ // GET model
+ OperationResult opResult =
+ aaiClient.getResource(getUrl(model, config), "example-trans-id-0", MediaType.APPLICATION_XML_TYPE);
+ assertTrue(opResult.getResultCode() == Response.Status.NOT_FOUND.getStatusCode());
+
+ // PUT the model
+ opResult = aaiClient.putResource(getUrl(model, config), model.getPayload(), "example-trans-id-1",
+ MediaType.APPLICATION_XML_TYPE);
+ assertTrue(opResult.getResultCode() == Response.Status.CREATED.getStatusCode());
+
+ // DELETE the model
+ opResult = aaiClient.getAndDeleteResource(getUrl(model, config), "example-trans-id-3");
+ assertTrue(opResult.getResultCode() == Response.Status.NO_CONTENT.getStatusCode());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private Stream<Node> getNodesStream(NodeList nodeList) {
+ return IntStream.range(0, nodeList.getLength()).mapToObj(nodeList::item);
+ }
+
+ static String readFile(String path) throws IOException {
+ byte[] encoded = Files.readAllBytes(Paths.get(path));
+ return new String(encoded);
+ }
+
+ private String getUrl(ModelArtifact model, ModelLoaderConfig config) {
+ String subUrl;
+ if (model.getType().equals(ArtifactType.MODEL)) {
+ subUrl = config.getAaiModelUrl(model.getModelNamespaceVersion()).trim();
+ } else {
+ subUrl = config.getAaiNamedQueryUrl(model.getModelNamespaceVersion()).trim();
+ }
+
+ String baseUrl = config.getAaiBaseUrl().trim();
+ if (!baseUrl.endsWith("/") && !subUrl.startsWith("/")) {
+ baseUrl = baseUrl + "/";
+ }
+
+ if (baseUrl.endsWith("/") && subUrl.startsWith("/")) {
+ baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
+ }
+
+ if (!subUrl.endsWith("/")) {
+ subUrl = subUrl + "/";
+ }
+
+ return baseUrl + subUrl + model.getModelInvariantId();
+ }
+}
diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java
index 96620ee..ac2d7e4 100644
--- a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java
+++ b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -39,7 +39,7 @@ import org.junit.Test;
import org.onap.aai.modelloader.config.ModelLoaderConfig;
/**
- * Local testing of the Babel service
+ * Local testing of the A&AI Service client.
*
*/
public class TestAaiServiceClient {
@@ -55,6 +55,8 @@ public class TestAaiServiceClient {
Properties props = new Properties();
props.put("ml.aai.KEYSTORE_PASSWORD", "2244");
+ props.put("ml.aai.KEYSTORE_FILE", "src/test/resources/auth/aai-client-cert.p12");
+ props.put("ml.aai.KEYSTORE_PASSWORD", "OBF:1i9a1u2a1unz1lr61wn51wn11lss1unz1u301i6o");
ModelLoaderConfig config = new ModelLoaderConfig(props, ".");
aaiClient = new AaiRestClient(config);
}
@@ -73,7 +75,7 @@ public class TestAaiServiceClient {
@Test
public void testOperations() {
- String url = "http://localhost";
+ String url = "http://localhost:8080";
String transId = "";
MediaType mediaType = MediaType.APPLICATION_JSON_TYPE;
aaiClient.getResource(url, "", mediaType);
diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java b/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java
index b42fee4..4f99bfc 100644
--- a/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java
+++ b/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -31,11 +31,6 @@ import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
-import java.security.KeyManagementException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@@ -51,10 +46,10 @@ import org.junit.Before;
import org.junit.Test;
import org.onap.aai.babel.service.data.BabelArtifact;
import org.onap.aai.modelloader.config.ModelLoaderConfig;
-import org.onap.aai.modelloader.restclient.BabelServiceClient.BabelServiceException;
+import org.onap.aai.modelloader.service.HttpsBabelServiceClientFactory;
/**
- * Local testing of the Babel service
+ * Local testing of the Babel service client.
*
*/
public class TestBabelServiceClient {
@@ -62,16 +57,14 @@ public class TestBabelServiceClient {
private Server server;
private String responseBody;
- {
+ @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);
- }
- @Before
- public void startJetty() throws Exception {
server = new Server(8080);
server.setHandler(getMockHandler());
server.start();
@@ -83,14 +76,17 @@ public class TestBabelServiceClient {
}
@Test
- public void testRestClient() throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException,
- KeyStoreException, CertificateException, IOException, BabelServiceException, URISyntaxException {
+ 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 BabelServiceClientFactory().create(new ModelLoaderConfig(configProperties, "."));
+ 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");
@@ -120,4 +116,3 @@ public class TestBabelServiceClient {
return handler;
}
}
-
diff --git a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientFactory.java b/src/test/java/org/onap/aai/modelloader/service/MockBabelServiceClientFactory.java
index 4354710..fa369ce 100644
--- a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientFactory.java
+++ b/src/test/java/org/onap/aai/modelloader/service/MockBabelServiceClientFactory.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -18,21 +18,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.modelloader.restclient;
+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.MockBabelServiceClient;
+import org.springframework.stereotype.Service;
-public class BabelServiceClientFactory {
+@Service
+public class MockBabelServiceClientFactory implements BabelServiceClientFactory {
- public BabelServiceClient create(ModelLoaderConfig config) throws UnrecoverableKeyException, KeyManagementException,
- NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
- return new BabelServiceClient(config);
+ @Override
+ public BabelServiceClient create(ModelLoaderConfig config) throws BabelServiceClientException {
+ return new MockBabelServiceClient(config);
}
}
diff --git a/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java b/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java
index 366d5a5..ec55f15 100644
--- a/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java
+++ b/src/test/java/org/onap/aai/modelloader/service/TestArtifactInfoImpl.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -39,19 +39,19 @@ public class TestArtifactInfoImpl {
public void testGettersAndSetters() {
ArtifactInfoImpl info = new ArtifactInfoImpl();
String artifactName = "testname";
- String artifactType = "test-type";
- String artifactVersion = "v1";
- String artifactDescription = "test description";
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)));
diff --git a/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderService.java b/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderService.java
new file mode 100644
index 0000000..8e07650
--- /dev/null
+++ b/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderService.java
@@ -0,0 +1,86 @@
+/**
+ * ============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.is;
+import static org.junit.Assert.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.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, MockBabelServiceClientFactory.class})
+@TestPropertySource(properties = {"CONFIG_HOME=src/test/resources",})
+public class TestModelLoaderService {
+
+ @Autowired
+ private ModelLoaderService service;
+
+ @After
+ public void shutdown() {
+ service.preShutdownOperations();
+ }
+
+ @Test
+ public void testMissingConfig() {
+ new ModelLoaderService().start();
+ }
+
+ @Test
+ public void testLoadModel() {
+ Response response = service.loadModel("");
+ assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
+ }
+
+ @Test
+ public void testSaveModel() {
+ Response response = service.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));
+ 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));
+ assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
+ }
+
+}
diff --git a/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderServiceWithSdc.java b/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderServiceWithSdc.java
new file mode 100644
index 0000000..ff0614b
--- /dev/null
+++ b/src/test/java/org/onap/aai/modelloader/service/TestModelLoaderServiceWithSdc.java
@@ -0,0 +1,63 @@
+/**
+ * ============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.is;
+import static org.junit.Assert.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.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})
+@TestPropertySource(properties = {"CONFIG_HOME=src/test/resources/sdc_test",})
+public class TestModelLoaderServiceWithSdc {
+
+ @Autowired
+ private ModelLoaderService service;
+
+ @After
+ public void shutdown() {
+ service.preShutdownOperations();
+ }
+
+ @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));
+ assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
+ }
+
+
+}
diff --git a/src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java b/src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java
index 9b6ea06..752f389 100644
--- a/src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java
+++ b/src/test/java/org/onap/aai/modelloader/util/ArtifactTestUtils.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -21,14 +21,34 @@
package org.onap.aai.modelloader.util;
import java.io.IOException;
+import java.net.URL;
import org.apache.commons.io.IOUtils;
+import org.onap.aai.babel.service.data.BabelArtifact;
/**
* This class provides some utilities to assist with running tests.
*/
public class ArtifactTestUtils {
+ public static BabelArtifact loadModelArtifact(String resource) throws IOException {
+ return new BabelArtifact("ModelArtifact", BabelArtifact.ArtifactType.MODEL,
+ ArtifactTestUtils.loadResourceAsString(resource));
+ }
public byte[] loadResource(String resourceName) throws IOException {
- return IOUtils.toByteArray(ArtifactTestUtils.class.getClassLoader().getResource(resourceName));
+ URL resource = getResource(resourceName);
+ if (resource != null) {
+ return IOUtils.toByteArray(resource);
+ } else {
+ throw new IOException("Cannot locate resource: " + resourceName);
+ }
+ }
+
+ public static String loadResourceAsString(String resourceName) throws IOException {
+ return IOUtils.toString(getResource(resourceName));
}
+
+ private static URL getResource(String resourceName) {
+ return ArtifactTestUtils.class.getClassLoader().getResource(resourceName);
+ }
+
}
diff --git a/src/test/java/org/onap/aai/modelloader/util/JsonXmlConverterTest.java b/src/test/java/org/onap/aai/modelloader/util/TestJsonXmlConverter.java
index 2271c57..4b7db56 100644
--- a/src/test/java/org/onap/aai/modelloader/util/JsonXmlConverterTest.java
+++ b/src/test/java/org/onap/aai/modelloader/util/TestJsonXmlConverter.java
@@ -1,5 +1,5 @@
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
@@ -20,8 +20,8 @@
*/
package org.onap.aai.modelloader.util;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream;
import java.nio.file.Files;
@@ -33,25 +33,30 @@ import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-public class JsonXmlConverterTest {
+public class TestJsonXmlConverter {
- @Test
- public void testConversion() throws Exception {
- final String XML_MODEL_FILE = "src/test/resources/models/l3-network-widget.xml";
- final String JSON_MODEL_FILE = "src/test/resources/models/l3-network-widget.json";
+ private static final String XML_MODEL_FILE = "src/test/resources/models/l3-network-widget.xml";
+ private static final String JSON_MODEL_FILE = "src/test/resources/models/l3-network-widget.json";
- try {
- byte[] encoded = Files.readAllBytes(Paths.get(XML_MODEL_FILE));
- String originalXML = new String(encoded);
+ @Test
+ public void testJsonIsValid() {
+ assertThat(JsonXmlConverter.isValidJson("{}"), is(true));
+ assertThat(JsonXmlConverter.isValidJson("[]"), is(true));
- assertFalse(JsonXmlConverter.isValidJson(originalXML));
+ assertThat(JsonXmlConverter.isValidJson("{"), is(false));
+ assertThat(JsonXmlConverter.isValidJson("["), is(false));
+ }
+ @Test
+ public void testConversion() throws Exception {
+ byte[] encoded = Files.readAllBytes(Paths.get(XML_MODEL_FILE));
+ assertThat(JsonXmlConverter.isValidJson(new String(encoded)), is(false));
encoded = Files.readAllBytes(Paths.get(JSON_MODEL_FILE));
- String originalJSON = new String(encoded);
+ String originalJson = new String(encoded);
- assertTrue(JsonXmlConverter.isValidJson(originalJSON));
+ assertThat(JsonXmlConverter.isValidJson(originalJson), is(true));
- String xmlFromJson = JsonXmlConverter.convertJsonToXml(originalJSON);
+ String xmlFromJson = JsonXmlConverter.convertJsonToXml(originalJson);
// Spot check one of the attributes
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
@@ -69,10 +74,9 @@ public class JsonXmlConverterTest {
}
}
- assertTrue(modelVid.equals("3d560d81-57d0-438b-a2a1-5334dba0651a"));
- } catch (Exception e) {
- e.printStackTrace();
- assertTrue(false);
- }
+ assertThat(modelVid.equals("3d560d81-57d0-438b-a2a1-5334dba0651a"), is(true));
+
+ // Convert the XML form back into JSON
+ JsonXmlConverter.convertXmlToJson(xmlFromJson);
}
}
diff --git a/src/test/resources/auth/aai-client-dummy.p12 b/src/test/resources/auth/aai-client-dummy.p12
new file mode 100644
index 0000000..ce363f5
--- /dev/null
+++ b/src/test/resources/auth/aai-client-dummy.p12
Binary files differ
diff --git a/src/test/resources/convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml b/src/test/resources/convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml
new file mode 100644
index 0000000..bc723c1
--- /dev/null
+++ b/src/test/resources/convertedYmls/AAI-SCP-Test-VSP-resource-1.0.xml
@@ -0,0 +1,51 @@
+<model xmlns="http://org.openecomp.aai.inventory/v10">
+ <model-invariant-id>b2b88a73-5c55-4984-99dd-a35c55935d14</model-invariant-id>
+ <model-type>resource</model-type>
+ <model-vers>
+ <model-ver>
+ <model-version-id>2e42bac2-318a-410c-b8ff-3b3a31351be7</model-version-id>
+ <model-name>SCP-Test-VSP</model-name>
+ <model-version>1.0</model-version>
+ <model-description>SCP Test VSP</model-description>
+ <model-elements>
+ <model-element>
+ <new-data-del-flag>T</new-data-del-flag>
+ <cardinality>unbounded</cardinality>
+ <model-elements>
+ <model-element>
+ <new-data-del-flag>T</new-data-del-flag>
+ <cardinality>unbounded</cardinality>
+ <model-elements/>
+ <relationship-list>
+ <relationship>
+ <related-to>model-ver</related-to>
+ <relationship-data>
+ <relationship-key>model-ver.model-version-id</relationship-key>
+ <relationship-value>06258c44-ab48-4b4b-a5db-16892f7d1e76</relationship-value>
+ </relationship-data>
+ <relationship-data>
+ <relationship-key>model.model-invariant-id</relationship-key>
+ <relationship-value>6f288081-b321-47c9-b038-6de70079a3bf</relationship-value>
+ </relationship-data>
+ </relationship>
+ </relationship-list>
+ </model-element>
+ </model-elements>
+ <relationship-list>
+ <relationship>
+ <related-to>model-ver</related-to>
+ <relationship-data>
+ <relationship-key>model-ver.model-version-id</relationship-key>
+ <relationship-value>93a6166f-b3d5-4f06-b4ba-aed48d009ad9</relationship-value>
+ </relationship-data>
+ <relationship-data>
+ <relationship-key>model.model-invariant-id</relationship-key>
+ <relationship-value>acc6edd8-a8d4-4b93-afaa-0994068be14c</relationship-value>
+ </relationship-data>
+ </relationship>
+ </relationship-list>
+ </model-element>
+ </model-elements>
+ </model-ver>
+ </model-vers>
+</model> \ No newline at end of file
diff --git a/src/test/resources/model-loader-empty-auth-password.properties b/src/test/resources/model-loader-empty-auth-password.properties
index 91fd527..fabd855 100644
--- a/src/test/resources/model-loader-empty-auth-password.properties
+++ b/src/test/resources/model-loader-empty-auth-password.properties
@@ -1,22 +1,27 @@
# Model Loader Distribution Client Configuration
ml.distribution.ACTIVE_SERVER_TLS_AUTH=false
-ml.distribution.ASDC_ADDRESS=
+ml.distribution.ASDC_ADDRESS=localhost:8443
+ml.distribution.MSG_BUS_ADDRESSES=localhost
ml.distribution.CONSUMER_GROUP=aai-ml-group-test
ml.distribution.CONSUMER_ID=aai-ml-id-test
-ml.distribution.ENVIRONMENT_NAME=
+ml.distribution.ENVIRONMENT_NAME=env
ml.distribution.KEYSTORE_PASSWORD=
-ml.distribution.KEYSTORE_FILE=asdc-client.jks
-ml.distribution.PASSWORD=
+ml.distribution.KEYSTORE_FILE=
+ml.distribution.PASSWORD=Aa123456
ml.distribution.POLLING_INTERVAL=30
ml.distribution.POLLING_TIMEOUT=20
ml.distribution.USER=ci
-ml.distribution.ARTIFACT_TYPES=MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG
+ml.distribution.ARTIFACT_TYPES=MODEL_QUERY_SPEC,TOSCA_CSAR
-# Model Loader AAI REST Client Configuration
-ml.aai.BASE_URL=
-ml.aai.MODEL_URL=/aai/v8/service-design-and-creation/models/model/
-ml.aai.NAMED_QUERY_URL=/aai/v8/service-design-and-creation/named-queries/named-query/
-ml.aai.VNF_IMAGE_URL=/aai/v8/service-design-and-creation/vnf-images
+# Disable ASDC polling & enable REST interface
+ml.distribution.ASDC_CONNECTION_DISABLE=true
+ml.debug.INGEST_SIMULATOR=enabled
+
+# Model Loader Client Configuration for the A&AI REST interface
+ml.aai.BASE_URL=https://localhost:8443
+ml.aai.MODEL_URL=/aai/v*/service-design-and-creation/models/model/
+ml.aai.NAMED_QUERY_URL=/aai/v*/service-design-and-creation/named-queries/named-query/
+ml.aai.VNF_IMAGE_URL=/aai/v*/service-design-and-creation/vnf-images
ml.aai.KEYSTORE_FILE=aai-client-cert.p12
ml.aai.KEYSTORE_PASSWORD=
ml.aai.AUTH_USER=ModelLoader
diff --git a/src/test/resources/model-loader-no-auth-password.properties b/src/test/resources/model-loader-no-auth-password.properties
index 2f36934..96b24c8 100644
--- a/src/test/resources/model-loader-no-auth-password.properties
+++ b/src/test/resources/model-loader-no-auth-password.properties
@@ -1,21 +1,26 @@
# Model Loader Distribution Client Configuration
ml.distribution.ACTIVE_SERVER_TLS_AUTH=false
-ml.distribution.ASDC_ADDRESS=
+ml.distribution.ASDC_ADDRESS=localhost:8443
+ml.distribution.MSG_BUS_ADDRESSES=localhost
ml.distribution.CONSUMER_GROUP=aai-ml-group-test
ml.distribution.CONSUMER_ID=aai-ml-id-test
-ml.distribution.ENVIRONMENT_NAME=
+ml.distribution.ENVIRONMENT_NAME=env
ml.distribution.KEYSTORE_PASSWORD=
-ml.distribution.KEYSTORE_FILE=asdc-client.jks
-ml.distribution.PASSWORD=
+ml.distribution.KEYSTORE_FILE=
+ml.distribution.PASSWORD=Aa123456
ml.distribution.POLLING_INTERVAL=30
ml.distribution.POLLING_TIMEOUT=20
ml.distribution.USER=ci
-ml.distribution.ARTIFACT_TYPES=MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG
+ml.distribution.ARTIFACT_TYPES=MODEL_QUERY_SPEC,TOSCA_CSAR
-# Model Loader AAI REST Client Configuration
-ml.aai.BASE_URL=
-ml.aai.MODEL_URL=/aai/v8/service-design-and-creation/models/model/
-ml.aai.NAMED_QUERY_URL=/aai/v8/service-design-and-creation/named-queries/named-query/
-ml.aai.VNF_IMAGE_URL=/aai/v8/service-design-and-creation/vnf-images
+# Disable ASDC polling & enable REST interface
+ml.distribution.ASDC_CONNECTION_DISABLE=true
+ml.debug.INGEST_SIMULATOR=enabled
+
+# Model Loader Client Configuration for the A&AI REST interface
+ml.aai.BASE_URL=https://localhost:8443
+ml.aai.MODEL_URL=/aai/v*/service-design-and-creation/models/model/
+ml.aai.NAMED_QUERY_URL=/aai/v*/service-design-and-creation/named-queries/named-query/
+ml.aai.VNF_IMAGE_URL=/aai/v*/service-design-and-creation/vnf-images
ml.aai.KEYSTORE_FILE=aai-client-cert.p12
ml.aai.KEYSTORE_PASSWORD=
diff --git a/src/test/resources/model-loader.properties b/src/test/resources/model-loader.properties
index 9f3226a..3ba1519 100644
--- a/src/test/resources/model-loader.properties
+++ b/src/test/resources/model-loader.properties
@@ -1,20 +1,24 @@
# Model Loader Distribution Client Configuration
ml.distribution.ACTIVE_SERVER_TLS_AUTH=false
-ml.distribution.ASDC_ADDRESS=localhost
+ml.distribution.ASDC_ADDRESS=localhost:8443
ml.distribution.MSG_BUS_ADDRESSES=localhost
ml.distribution.CONSUMER_GROUP=aai-ml-group-test
ml.distribution.CONSUMER_ID=aai-ml-id-test
ml.distribution.ENVIRONMENT_NAME=env
ml.distribution.KEYSTORE_PASSWORD=
-ml.distribution.KEYSTORE_FILE=asdc-client.jks
+ml.distribution.KEYSTORE_FILE=
ml.distribution.PASSWORD=Aa123456
ml.distribution.POLLING_INTERVAL=30
ml.distribution.POLLING_TIMEOUT=20
ml.distribution.USER=ci
-ml.distribution.ARTIFACT_TYPES=MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG
+ml.distribution.ARTIFACT_TYPES=MODEL_QUERY_SPEC,TOSCA_CSAR
+
+# Disable ASDC polling & enable REST interface
+ml.distribution.ASDC_CONNECTION_DISABLE=true
+ml.debug.INGEST_SIMULATOR=enabled
# Model Loader Client Configuration for the A&AI REST interface
-ml.aai.BASE_URL=
+ml.aai.BASE_URL=https://localhost:8443
ml.aai.MODEL_URL=/aai/v*/service-design-and-creation/models/model/
ml.aai.NAMED_QUERY_URL=/aai/v*/service-design-and-creation/named-queries/named-query/
ml.aai.VNF_IMAGE_URL=/aai/v*/service-design-and-creation/vnf-images
diff --git a/src/test/resources/sdc_test/model-loader.properties b/src/test/resources/sdc_test/model-loader.properties
new file mode 100644
index 0000000..ee5c0ed
--- /dev/null
+++ b/src/test/resources/sdc_test/model-loader.properties
@@ -0,0 +1,30 @@
+# Model Loader Distribution Client Configuration
+ml.distribution.ACTIVE_SERVER_TLS_AUTH=false
+ml.distribution.ASDC_ADDRESS=localhost:8443
+ml.distribution.MSG_BUS_ADDRESSES=localhost
+ml.distribution.CONSUMER_GROUP=aai-ml-group-test
+ml.distribution.CONSUMER_ID=aai-ml-id-test
+ml.distribution.ENVIRONMENT_NAME=env
+ml.distribution.KEYSTORE_PASSWORD=
+ml.distribution.KEYSTORE_FILE=
+ml.distribution.PASSWORD=Aa123456
+ml.distribution.POLLING_INTERVAL=30
+ml.distribution.POLLING_TIMEOUT=20
+ml.distribution.USER=ci
+ml.distribution.ARTIFACT_TYPES=MODEL_QUERY_SPEC,TOSCA_CSAR
+
+# Model Loader Client Configuration for the A&AI REST interface
+ml.aai.BASE_URL=https://localhost:8443
+ml.aai.MODEL_URL=/aai/v*/service-design-and-creation/models/model/
+ml.aai.NAMED_QUERY_URL=/aai/v*/service-design-and-creation/named-queries/named-query/
+ml.aai.VNF_IMAGE_URL=/aai/v*/service-design-and-creation/vnf-images
+ml.aai.KEYSTORE_FILE=aai-client-cert.p12
+ml.aai.KEYSTORE_PASSWORD=
+ml.aai.AUTH_USER=ModelLoader
+ml.aai.AUTH_PASSWORD=
+
+# Model Loader Client Configuration for the Babel Service
+ml.babel.BASE_URL=
+ml.babel.GENERATE_ARTIFACTS_URL=
+ml.babel.KEYSTORE_FILE=
+ml.babel.KEYSTORE_PASSWORD=