summaryrefslogtreecommitdiffstats
path: root/cps-ncmp-service
diff options
context:
space:
mode:
Diffstat (limited to 'cps-ncmp-service')
-rw-r--r--cps-ncmp-service/pom.xml2
-rw-r--r--cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/NetworkCmProxyDataService.java9
-rw-r--r--cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/JsonUtils.java52
-rwxr-xr-xcps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImpl.java145
-rw-r--r--cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/client/DmiRestClient.java22
-rw-r--r--cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/config/NcmpConfiguration.java4
-rw-r--r--cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/NcmpException.java12
-rw-r--r--cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/operation/DmiOperations.java18
-rw-r--r--cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/models/PersistenceCmHandlesList.java8
-rw-r--r--cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/JsonUtilsSpec.groovy51
-rw-r--r--cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplSpec.groovy136
-rw-r--r--cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/client/DmiRestClientSpec.groovy28
-rw-r--r--cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/config/NcmpConfigurationSpec.groovy52
-rw-r--r--cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/operation/DmiOperationsSpec.groovy14
-rw-r--r--cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/models/PersistenceCmHandleSpec.groovy42
-rw-r--r--cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/models/moduleReferenceSpec.groovy25
-rw-r--r--cps-ncmp-service/src/test/resources/application.yml23
17 files changed, 510 insertions, 133 deletions
diff --git a/cps-ncmp-service/pom.xml b/cps-ncmp-service/pom.xml
index fc01c3b1ca..294b290161 100644
--- a/cps-ncmp-service/pom.xml
+++ b/cps-ncmp-service/pom.xml
@@ -26,7 +26,7 @@
<parent>
<groupId>org.onap.cps</groupId>
<artifactId>cps-parent</artifactId>
- <version>1.1.0-SNAPSHOT</version>
+ <version>2.0.1-SNAPSHOT</version>
<relativePath>../cps-parent/pom.xml</relativePath>
</parent>
diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/NetworkCmProxyDataService.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/NetworkCmProxyDataService.java
index 0693f61e44..60669b9169 100644
--- a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/NetworkCmProxyDataService.java
+++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/NetworkCmProxyDataService.java
@@ -28,6 +28,7 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
import org.onap.cps.spi.FetchDescendantsOption;
import org.onap.cps.spi.model.DataNode;
+import org.onap.cps.spi.model.ModuleReference;
/*
* Datastore interface for handling CPS data.
@@ -154,4 +155,12 @@ public interface NetworkCmProxyDataService {
@NotNull String resourceIdentifier,
@NotNull Object requestBody,
String contentType);
+
+ /**
+ * Retrieve module references for the given cm handle.
+ *
+ * @param cmHandle cm handle
+ * @return a collection of modules names and revisions
+ */
+ Collection<ModuleReference> getYangResourcesModuleReferences(@NotNull String cmHandle);
}
diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/JsonUtils.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/JsonUtils.java
new file mode 100644
index 0000000000..6768777e17
--- /dev/null
+++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/JsonUtils.java
@@ -0,0 +1,52 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.ncmp.api.impl;
+
+public class JsonUtils {
+
+ private static final String BACK_SLASH = "\\";
+ private static final String NEW_LINE = "\n";
+ private static final String QUOTE = "\"";
+
+ private JsonUtils() {
+ throw new IllegalStateException();
+ }
+
+ /**
+ * Remove redundant beginning and end characters.
+ * @param input string to format
+ * @return formatted string
+ */
+ public static String removeWrappingTokens(final String input) {
+ return input.substring(1, input.length() - 1);
+ }
+
+ /**
+ * Remove redundant escape characters.
+ * @param input string to format
+ * @return formatted string
+ */
+ public static String removeRedundantEscapeCharacters(final String input) {
+ return input.replace(BACK_SLASH + "n", NEW_LINE)
+ .replace(BACK_SLASH + QUOTE, QUOTE)
+ .replace(BACK_SLASH + BACK_SLASH + QUOTE, BACK_SLASH + QUOTE);
+ }
+}
diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImpl.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImpl.java
index dfe5603431..a28b73c427 100755
--- a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImpl.java
+++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImpl.java
@@ -76,6 +76,8 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
private static final String NCMP_DMI_SERVICE_NAME = "dmi-service-name";
+ private static final String REVISION = "revision";
+
private CpsDataService cpsDataService;
private ObjectMapper objectMapper;
@@ -88,8 +90,6 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
private CpsAdminService cpsAdminService;
- public static final String NO_NAMESPACE = null;
-
/**
* Constructor Injection for Dependencies.
* @param dmiOperations DMI operation
@@ -215,7 +215,7 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
.cmHandleProperties(cmHandlePropertiesMap)
.build();
final var dmiRequestBody = prepareOperationBody(dmiRequestBodyObject);
- final ResponseEntity<Void> responseEntity = dmiOperations
+ final ResponseEntity<String> responseEntity = dmiOperations
.createResourceDataPassThroughRunningFromDmi(dmiServiceName,
cmHandle,
resourceIdentifier,
@@ -223,13 +223,17 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
handleResponseForPost(responseEntity);
}
+ @Override
+ public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandle) {
+ return cpsModuleService.getYangResourcesModuleReferences(NF_PROXY_DATASPACE_NAME, cmHandle);
+ }
+
private DataNode fetchDataNodeFromDmiRegistryForCmHandle(final String cmHandle) {
final String xpathForDmiRegistryToFetchCmHandle = "/dmi-registry/cm-handles[@id='" + cmHandle + "']";
- final var dataNode = cpsDataService.getDataNode(NCMP_DATASPACE_NAME,
+ return cpsDataService.getDataNode(NCMP_DATASPACE_NAME,
NCMP_DMI_REGISTRY_ANCHOR,
xpathForDmiRegistryToFetchCmHandle,
FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
- return dataNode;
}
private String prepareOperationBody(final GenericRequestBody requestBodyObject) {
@@ -242,9 +246,9 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
}
}
- private Map<String, String> getCmHandlePropertiesAsMap(final Collection<DataNode> cmHandlePropertiesList) {
- if (cmHandlePropertiesList == null || cmHandlePropertiesList.size() == 0) {
- return null;
+ private static Map<String, String> getCmHandlePropertiesAsMap(final Collection<DataNode> cmHandlePropertiesList) {
+ if (cmHandlePropertiesList == null || cmHandlePropertiesList.isEmpty()) {
+ return Collections.emptyMap();
}
final Map<String, String> cmHandlePropertiesMap = new LinkedHashMap<>();
for (final var node: cmHandlePropertiesList) {
@@ -254,7 +258,7 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
return cmHandlePropertiesMap;
}
- private Object handleResponse(final @NotNull ResponseEntity<Object> responseEntity) {
+ private static Object handleResponse(final @NotNull ResponseEntity<Object> responseEntity) {
if (responseEntity.getStatusCode() == HttpStatus.OK) {
return responseEntity.getBody();
} else {
@@ -264,8 +268,8 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
}
}
- private void handleResponseForPost(final @NotNull ResponseEntity<Void> responseEntity) {
- if (responseEntity.getStatusCode() != HttpStatus.CREATED) {
+ private static void handleResponseForPost(final @NotNull ResponseEntity<String> responseEntity) {
+ if (responseEntity.getStatusCode() != HttpStatus.OK) {
throw new NcmpException("Not able to create resource data.",
"DMI status code: " + responseEntity.getStatusCodeValue()
+ ", DMI response body: " + responseEntity.getBody());
@@ -275,11 +279,11 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
private String getGenericRequestBody(final DataNode cmHandleDataNode) {
final Collection<DataNode> cmHandlePropertiesList = cmHandleDataNode.getChildDataNodes();
final Map<String, String> cmHandlePropertiesMap = getCmHandlePropertiesAsMap(cmHandlePropertiesList);
- final var requetBodyObject = GenericRequestBody.builder()
+ final var requestBodyObject = GenericRequestBody.builder()
.operation(GenericRequestBody.OperationEnum.READ)
.cmHandleProperties(cmHandlePropertiesMap)
.build();
- return prepareOperationBody(requetBodyObject);
+ return prepareOperationBody(requestBodyObject);
}
private void parseAndUpdateCmHandlesInDmiRegistration(final DmiPluginRegistration dmiPluginRegistration) {
@@ -295,10 +299,7 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
cpsDataService.updateNodeLeavesAndExistingDescendantLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
"/dmi-registry", cmHandlesJsonData, NO_TIMESTAMP);
} catch (final JsonProcessingException e) {
- log.error("Parsing error occurred while converting Object to JSON DMI Registry.");
- throw new DataValidationException(
- "Parsing error occurred while processing DMI Plugin Registration" + dmiPluginRegistration, e
- .getMessage(), e);
+ handleJsonProcessingException(dmiPluginRegistration, e);
}
}
@@ -310,26 +311,40 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
final PersistenceCmHandle persistenceCmHandle =
toPersistenceCmHandle(dmiPluginRegistration.getDmiPlugin(), cmHandle);
persistenceCmHandlesList.add(persistenceCmHandle);
- createAnchorAndSyncModel(persistenceCmHandle);
}
final String cmHandleJsonData = objectMapper.writeValueAsString(persistenceCmHandlesList);
- cpsDataService.saveListNodeData(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, "/dmi-registry",
- cmHandleJsonData, NO_TIMESTAMP);
+
+ registerAndSyncNode(persistenceCmHandlesList, cmHandleJsonData);
} catch (final JsonProcessingException e) {
- log.error("Parsing error occurred while converting Object to JSON for DMI Registry.");
- throw new DataValidationException(
- "Parsing error occurred while processing DMI Plugin Registration" + dmiPluginRegistration, e
- .getMessage(), e);
+ handleJsonProcessingException(dmiPluginRegistration, e);
}
}
- private PersistenceCmHandle toPersistenceCmHandle(final String dmiPluginService,
- final CmHandle cmHandle) {
+ private static void handleJsonProcessingException(final DmiPluginRegistration dmiPluginRegistration,
+ final JsonProcessingException e) {
+ final String message = "Parsing error occurred while processing DMI Plugin Registration"
+ + dmiPluginRegistration;
+ log.error(message);
+ throw new DataValidationException(message, e.getMessage(), e);
+ }
+
+ private void registerAndSyncNode(final PersistenceCmHandlesList persistenceCmHandlesList,
+ final String cmHandleJsonData) {
+ cpsDataService.saveListNodeData(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, "/dmi-registry",
+ cmHandleJsonData, NO_TIMESTAMP);
+
+ for (final PersistenceCmHandle persistenceCmHandle : persistenceCmHandlesList.getPersistenceCmHandles()) {
+ createAnchorAndSyncModel(persistenceCmHandle);
+ }
+ }
+
+ private static PersistenceCmHandle toPersistenceCmHandle(final String dmiPluginService,
+ final CmHandle cmHandle) {
final PersistenceCmHandle persistenceCmHandle = new PersistenceCmHandle();
persistenceCmHandle.setDmiServiceName(dmiPluginService);
persistenceCmHandle.setId(cmHandle.getCmHandleID());
if (cmHandle.getCmHandleProperties() == null) {
- persistenceCmHandle.setAdditionalProperties(Collections.EMPTY_MAP);
+ persistenceCmHandle.setAdditionalProperties(Collections.emptyMap());
} else {
persistenceCmHandle.setAdditionalProperties(cmHandle.getCmHandleProperties());
}
@@ -350,31 +365,64 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
protected void createAnchorAndSyncModel(final PersistenceCmHandle cmHandle) {
final var modulesForCmHandle =
dmiOperations.getResourceFromDmi(cmHandle.getDmiServiceName(), cmHandle.getId(), "modules");
-
- final List<ModuleReference> moduleReferencesFromDmiForCmHandle = getModuleReferences(modulesForCmHandle);
-
- final var knownModuleReferencesInCps = cpsModuleService.getAllYangResourcesModuleReferences();
-
+ final List<ModuleReference> moduleReferencesFromDmiForCmHandle =
+ getModuleReferences(modulesForCmHandle);
+ final var knownModuleReferencesInCps =
+ cpsModuleService.getYangResourceModuleReferences(NF_PROXY_DATASPACE_NAME);
final List<ModuleReference> existingModuleReferences = new ArrayList<>();
+
+ final List<ModuleReference> unknownModuleReferences = new ArrayList<>();
for (final ModuleReference moduleReferenceFromDmiForCmHandle : moduleReferencesFromDmiForCmHandle) {
if (knownModuleReferencesInCps.contains(moduleReferenceFromDmiForCmHandle)) {
existingModuleReferences.add(moduleReferenceFromDmiForCmHandle);
+ } else {
+ unknownModuleReferences.add(moduleReferenceFromDmiForCmHandle);
}
}
+ final JsonObject requestBodyAsJson = getRequestBodyAsJson(unknownModuleReferences);
+
final Map<String, String> newYangResourcesModuleNameToContentMap =
- getNewYangResources(cmHandle);
+ getNewYangResources(cmHandle, requestBodyAsJson.toString());
- cpsModuleService.createSchemaSetFromModules(NCMP_DATASPACE_NAME, cmHandle.getId(),
+ cpsModuleService.createSchemaSetFromModules(NF_PROXY_DATASPACE_NAME, cmHandle.getId(),
newYangResourcesModuleNameToContentMap, existingModuleReferences);
- cpsAdminService.createAnchor(NCMP_DATASPACE_NAME, cmHandle.getId(), cmHandle.getId());
+ cpsAdminService.createAnchor(NF_PROXY_DATASPACE_NAME, cmHandle.getId(), cmHandle.getId());
+ }
+
+ private static JsonObject getRequestBodyAsJson(final List<ModuleReference> unknownModuleReferences) {
+
+ final JsonObject requestBodyAsJson = new JsonObject();
+ requestBodyAsJson.addProperty("operation", "read");
+
+ final JsonArray moduleReferencesAsJson = getModuleReferencesAsJson(unknownModuleReferences);
+
+ final JsonObject data = new JsonObject();
+ data.add("modules", moduleReferencesAsJson);
+ requestBodyAsJson.add("data", data);
+
+ return requestBodyAsJson;
}
- private Map<String, String> getNewYangResources(final PersistenceCmHandle cmHandle) {
- final var moduleResourcesAsJsonString = dmiOperations.getResourceFromDmi(
- cmHandle.getDmiServiceName(), cmHandle.getId(), "moduleResources");
- final JsonArray moduleResources = new Gson().fromJson(moduleResourcesAsJsonString.getBody(), JsonArray.class);
+ private static JsonArray getModuleReferencesAsJson(final List<ModuleReference> unknownModuleReferences) {
+ final JsonArray moduleReferences = new JsonArray();
+
+ for (final ModuleReference moduleReference : unknownModuleReferences) {
+ final JsonObject moduleReferenceAsJson = new JsonObject();
+ moduleReferenceAsJson.addProperty("name", moduleReference.getModuleName());
+ moduleReferenceAsJson.addProperty(REVISION, moduleReference.getRevision());
+ moduleReferences.add(moduleReferenceAsJson);
+ }
+ return moduleReferences;
+ }
+
+ private Map<String, String> getNewYangResources(final PersistenceCmHandle cmHandle, final String jsonData) {
+ final var moduleResourcesAsJsonString = dmiOperations.getResourceFromDmiWithJsonData(
+ cmHandle.getDmiServiceName(), jsonData, cmHandle.getId(), "moduleResources");
+
+ final JsonArray moduleResources = new Gson().fromJson(moduleResourcesAsJsonString.getBody(),
+ JsonArray.class);
final Map<String, String> newYangResourcesModuleNameToContentMap = new HashMap<>();
for (final JsonElement moduleResource : moduleResources) {
@@ -384,29 +432,34 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
return newYangResourcesModuleNameToContentMap;
}
- private YangResource toYangResource(final JsonObject yangResourceAsJson) {
+ private static YangResource toYangResource(final JsonObject yangResourceAsJson) {
final YangResource yangResource = new YangResource();
yangResource.setModuleName(yangResourceAsJson.get("moduleName").getAsString());
yangResource.setRevision(yangResourceAsJson.get("revision").getAsString());
- yangResource.setYangSource(yangResourceAsJson.get("yangSource").getAsString());
+ final String yangSourceJson = yangResourceAsJson.get("yangSource").getAsString();
+
+ String yangSource = JsonUtils.removeWrappingTokens(yangSourceJson);
+ yangSource = JsonUtils.removeRedundantEscapeCharacters(yangSource);
+ yangResource.setYangSource(yangSource);
+
return yangResource;
}
- private List<ModuleReference> getModuleReferences(final ResponseEntity<String> response) {
+ private static List<ModuleReference> getModuleReferences(final ResponseEntity<String> response) {
final List<ModuleReference> modulesFromDmiForCmHandle = new ArrayList<>();
final JsonObject convertedObject = new Gson().fromJson(response.getBody(), JsonObject.class);
final JsonArray moduleReferencesAsJson = convertedObject.getAsJsonArray("schemas");
for (final JsonElement moduleReferenceAsJson : moduleReferencesAsJson) {
- final ModuleReference moduleReference = toModuleReference((JsonObject) moduleReferenceAsJson);
+ final ModuleReference moduleReference =
+ toModuleReference((JsonObject) moduleReferenceAsJson);
modulesFromDmiForCmHandle.add(moduleReference);
}
return modulesFromDmiForCmHandle;
}
- private ModuleReference toModuleReference(final JsonObject moduleReferenceAsJson) {
+ private static ModuleReference toModuleReference(final JsonObject moduleReferenceAsJson) {
final var moduleReference = new ModuleReference();
- moduleReference.setName(moduleReferenceAsJson.get("moduleName").getAsString());
- moduleReference.setNamespace(NO_NAMESPACE);
+ moduleReference.setModuleName(moduleReferenceAsJson.get("moduleName").getAsString());
moduleReference.setRevision(moduleReferenceAsJson.get("revision").getAsString());
return moduleReference;
}
diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/client/DmiRestClient.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/client/DmiRestClient.java
index af691f6341..fc70708f92 100644
--- a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/client/DmiRestClient.java
+++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/client/DmiRestClient.java
@@ -46,10 +46,18 @@ public class DmiRestClient {
return restTemplate.exchange(dmiResourceUrl, HttpMethod.PUT, httpEntity, Object.class);
}
- public ResponseEntity<Void> postOperationWithJsonData(final String dmiResourceUrl,
- final String jsonData, final HttpHeaders headers) {
- final var httpEntity = new HttpEntity<>(jsonData, configureHttpHeaders(headers));
- return restTemplate.postForEntity(dmiResourceUrl, httpEntity, Void.class);
+ /**
+ * Sends POST operation to DMI with json body containing module references.
+ * @param dmiResourceUrl dmi resource url
+ * @param jsonData json data body
+ * @param httpHeaders http headers
+ * @return response entity of type String
+ */
+ public ResponseEntity<String> postOperationWithJsonData(final String dmiResourceUrl,
+ final String jsonData,
+ final HttpHeaders httpHeaders) {
+ final var httpEntity = new HttpEntity<>(jsonData, configureHttpHeaders(httpHeaders));
+ return restTemplate.postForEntity(dmiResourceUrl, httpEntity, String.class);
}
private HttpHeaders configureHttpHeaders(final HttpHeaders httpHeaders) {
@@ -58,6 +66,12 @@ public class DmiRestClient {
return httpHeaders;
}
+ /**
+ * Sends POST operation to DMI.
+ * @param dmiResourceUrl dmi resource url
+ * @param httpHeaders http headers
+ * @return response entity of type String
+ */
public ResponseEntity<String> postOperation(final String dmiResourceUrl, final HttpHeaders httpHeaders) {
final var httpEntity = new HttpEntity<>(configureHttpHeaders(httpHeaders));
return restTemplate.exchange(dmiResourceUrl, HttpMethod.POST, httpEntity, String.class);
diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/config/NcmpConfiguration.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/config/NcmpConfiguration.java
index a834bfcd90..c4e82d3290 100644
--- a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/config/NcmpConfiguration.java
+++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/config/NcmpConfiguration.java
@@ -41,7 +41,7 @@ public class NcmpConfiguration {
}
@Bean
- public RestTemplate restTemplate(final RestTemplateBuilder restTemplateBuilder) {
+ public static RestTemplate restTemplate(final RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.build();
}
-} \ No newline at end of file
+}
diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/NcmpException.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/NcmpException.java
index ff53464096..2c75b5d992 100644
--- a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/NcmpException.java
+++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/NcmpException.java
@@ -43,17 +43,5 @@ public class NcmpException extends RuntimeException {
this.details = details;
}
- /**
- * Constructor.
- *
- * @param message the error message
- * @param details the error details
- * @param cause the cause of the exception
- */
- public NcmpException(final String message, final String details, final Throwable cause) {
- super(message, cause);
- this.details = details;
- }
-
}
diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/operation/DmiOperations.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/operation/DmiOperations.java
index d6feaf3adf..71af3d4cfe 100644
--- a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/operation/DmiOperations.java
+++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/operation/DmiOperations.java
@@ -76,7 +76,23 @@ public class DmiOperations {
final var dmiResourceDataUrl = getDmiResourceUrl(dmiServiceName, cmHandle, resourceName);
final var httpHeaders = new HttpHeaders();
return dmiRestClient.postOperation(dmiResourceDataUrl, httpHeaders);
+ }
+ /**
+ * Get resources from DMI for modules.
+ *
+ * @param dmiServiceName dmi service name
+ * @param jsonData module names and revisions as JSON
+ * @param cmHandle cmHandle
+ * @param resourceName name of the resource(s)
+ * @return {@code ResponseEntity} response entity
+ */
+ public ResponseEntity<String> getResourceFromDmiWithJsonData(final String dmiServiceName,
+ final String jsonData,
+ final String cmHandle,
+ final String resourceName) {
+ final String dmiResourceDataUrl = getDmiResourceUrl(dmiServiceName, cmHandle, resourceName);
+ return dmiRestClient.postOperationWithJsonData(dmiResourceDataUrl, jsonData, new HttpHeaders());
}
/**
@@ -141,7 +157,7 @@ public class DmiOperations {
* @param jsonBody json body for put operation
* @return {@code ResponseEntity} response entity
*/
- public ResponseEntity<Void> createResourceDataPassThroughRunningFromDmi(final String dmiServiceName,
+ public ResponseEntity<String> createResourceDataPassThroughRunningFromDmi(final String dmiServiceName,
final String cmHandle,
final String resourceId,
final String jsonBody) {
diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/models/PersistenceCmHandlesList.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/models/PersistenceCmHandlesList.java
index beeb00f116..f35abf60b6 100644
--- a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/models/PersistenceCmHandlesList.java
+++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/models/PersistenceCmHandlesList.java
@@ -23,11 +23,13 @@ package org.onap.cps.ncmp.api.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
+import lombok.Getter;
+@Getter
public class PersistenceCmHandlesList {
@JsonProperty("cm-handles")
- private List<PersistenceCmHandle> persistenceCmHandles;
+ private List<PersistenceCmHandle> persistenceCmHandles = new ArrayList<>();
/**
* Add a persistenceCmHandle.
@@ -35,10 +37,6 @@ public class PersistenceCmHandlesList {
* @param persistenceCmHandle the persistenceCmHandle to add
*/
public void add(final PersistenceCmHandle persistenceCmHandle) {
- if (persistenceCmHandles == null) {
- persistenceCmHandles = new ArrayList<>();
- }
persistenceCmHandles.add(persistenceCmHandle);
}
-
}
diff --git a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/JsonUtilsSpec.groovy b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/JsonUtilsSpec.groovy
new file mode 100644
index 0000000000..be27dfad5d
--- /dev/null
+++ b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/JsonUtilsSpec.groovy
@@ -0,0 +1,51 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.cps.ncmp.api.impl
+
+import spock.lang.Specification
+
+class JsonUtilsSpec extends Specification {
+ def 'Remove redundant escape characters.'() {
+ expect: 'removing redundant escape characters returns the correct output for #scenario'
+ JsonUtils.removeRedundantEscapeCharacters(input) == expectedOutput
+ where: 'the following input is used'
+ scenario | input || expectedOutput
+ 'two lines' | 'line1\\nline2' || 'line1\nline2'
+ 'a string inside quotes' | 'a \\"word in quotes\\"' || 'a "word in quotes"'
+ 'quotes inside quotes (double escape)' | '\\"quotes \\\\\\"inside\\\\\\" quotes\\"' || '"quotes \\"inside\\" quotes"' // human readable: "quotes \"inside\" quotes"
+ }
+ def 'Remove wrapping tokens.'() {
+ expect: 'removing wrapping tokens returns the correct output for #scenario'
+ JsonUtils.removeWrappingTokens(input) == expectedOutput
+ where: 'the following input is used'
+ scenario | input || expectedOutput
+ 'a string in quotes' | '"abc"' || 'abc'
+ 'a string in apostrophes' | "'abc'" || 'abc'
+ 'a string inside any other tokens' | 'abcde' || 'bcd'
+ }
+
+ def 'Cannot use constructor.'() {
+ when: 'attempt to construct object'
+ new JsonUtils()
+ then: 'an exception is thrown'
+ thrown(IllegalStateException)
+ }
+}
+
diff --git a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplSpec.groovy b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplSpec.groovy
index b42db57233..8739355c8b 100644
--- a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplSpec.groovy
+++ b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplSpec.groovy
@@ -36,6 +36,8 @@ import org.onap.cps.ncmp.api.models.DmiPluginRegistration
import org.onap.cps.ncmp.api.models.PersistenceCmHandle
import org.onap.cps.ncmp.utils.TestUtils
import org.onap.cps.spi.FetchDescendantsOption
+import org.onap.cps.spi.exceptions.DataNodeNotFoundException
+import org.onap.cps.spi.exceptions.DataValidationException
import org.onap.cps.spi.model.DataNode
import org.onap.cps.spi.model.ModuleReference
import org.springframework.http.HttpStatus
@@ -56,16 +58,15 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
def mockCpsModuleService = Mock(CpsModuleService)
def mockCpsAdminService = Mock(CpsAdminService)
def mockDmiProperties = Mock(NcmpConfiguration.DmiProperties)
+ def spyObjectMapper = Spy(ObjectMapper)
def objectUnderTest = new NetworkCmProxyDataServiceImpl(mockDmiOperations, mockCpsModuleService,
- mockCpsDataService, mockCpsQueryService, mockCpsAdminService, new ObjectMapper())
+ mockCpsDataService, mockCpsQueryService, mockCpsAdminService, spyObjectMapper)
def cmHandle = 'some handle'
def noTimestamp = null
def cmHandleXPath = "/dmi-registry/cm-handles[@id='testCmHandle']"
def cmHandleForModelSync = new PersistenceCmHandle(id:'some cm handle', dmiServiceName: 'some service name')
- def expectedDataspaceNameForModleSync = 'NCMP-Admin'
- def NO_NAMESPACE = null
def expectedDataspaceName = 'NFP-Operational'
def 'Query data nodes by cps path with #fetchDescendantsOption.'() {
@@ -156,12 +157,12 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
'ncmp-dmi-registry', "/dmi-registry/cm-handles[@id='cmHandle001']", noTimestamp)
where:
- scenario | createdCmHandles | updatedCmHandles | removedCmHandles || expectedCallsToSaveNode | expectedCallsToUpdateNode | expectedCallsToDeleteListDataNode
- 'create' | [persistenceCmHandle ] | [] | [] || 1 | 0 | 0
- 'update' | [] | [persistenceCmHandle ] | [] || 0 | 1 | 0
- 'delete' | [] | [] | cmHandlesArray || 0 | 0 | 1
- 'create, update and delete' | [persistenceCmHandle ] | [persistenceCmHandle ] | cmHandlesArray || 1 | 1 | 1
-
+ scenario | createdCmHandles | updatedCmHandles | removedCmHandles || expectedCallsToSaveNode | expectedCallsToUpdateNode | expectedCallsToDeleteListDataNode
+ 'create' | [persistenceCmHandle] | [] | [] || 1 | 0 | 0
+ 'update' | [] | [persistenceCmHandle] | [] || 0 | 1 | 0
+ 'delete' | [] | [] | cmHandlesArray || 0 | 0 | 1
+ 'create, update and delete' | [persistenceCmHandle] | [persistenceCmHandle] | cmHandlesArray || 1 | 1 | 1
+ 'no valid data' | null | null | null || 0 | 0 | 0
}
def 'Register a DMI Plugin for the given cmHandle without additional properties.'() {
@@ -171,7 +172,7 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
dmiPluginRegistration.dmiPlugin = 'my-server'
persistenceCmHandle.cmHandleID = '123'
persistenceCmHandle.cmHandleProperties = null
- dmiPluginRegistration.createdCmHandles = [persistenceCmHandle ]
+ dmiPluginRegistration.createdCmHandles = [persistenceCmHandle]
def expectedJsonData = '{"cm-handles":[{"id":"123","dmi-service-name":"my-server","additional-properties":[]}]}'
when: 'registration is updated'
objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
@@ -180,28 +181,58 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
'/dmi-registry', expectedJsonData, noTimestamp)
}
+ def 'Register a DMI Plugin with JSON processing errors during #scenario.'() {
+ given: 'a registration without cmHandle properties '
+ NetworkCmProxyDataServiceImpl objectUnderTest = getObjectUnderTestWithModelSyncDisabled()
+ def dmiPluginRegistration = new DmiPluginRegistration()
+ dmiPluginRegistration.createdCmHandles = createdCmHandles
+ dmiPluginRegistration.updatedCmHandles = updatedCmHandles
+ and: 'an JSON processing exception occurs'
+ spyObjectMapper.writeValueAsString(_) >> { throw (new JsonProcessingException('')) }
+ when: 'registration is updated'
+ objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
+ then: 'a data validation exception is thrown'
+ thrown(DataValidationException)
+ where:
+ scenario | createdCmHandles | updatedCmHandles
+ 'create' | [persistenceCmHandle] | []
+ 'update' | [] | [persistenceCmHandle]
+ }
+
+ def 'Register a DMI Plugin with no data found during delete.'() {
+ given: 'a registration without cmHandle properties '
+ NetworkCmProxyDataServiceImpl objectUnderTest = getObjectUnderTestWithModelSyncDisabled()
+ def dmiPluginRegistration = new DmiPluginRegistration()
+ dmiPluginRegistration.removedCmHandles = ['some cm handle']
+ and: 'an JSON processing exception occurs'
+ mockCpsDataService.deleteListNodeData(*_) >> { throw (new DataNodeNotFoundException('','')) }
+ when: 'registration is updated'
+ objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
+ then: 'no exception is thrown'
+ noExceptionThrown()
+ }
+
def 'Get resource data for pass-through operational from dmi.'() {
given: 'data node representing cmHandle and its properties'
def cmHandleDataNode = getCmHandleDataNodeForTest()
+ and: 'data node is got from data service'
+ mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
+ cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNode
+ and: 'resource data is got from DMI'
+ mockDmiOperations.getResourceDataOperationalFromDmi('testDmiService',
+ 'testCmHandle',
+ 'testResourceId',
+ 'testFieldQuery',
+ 5,
+ 'testAcceptParam',
+ '{"operation":"read","cmHandleProperties":{"testName":"testValue"}}') >> new ResponseEntity<>('result-json', HttpStatus.OK)
when: 'get resource data is called'
def response = objectUnderTest.getResourceDataOperationalForCmHandle('testCmHandle',
'testResourceId',
'testAcceptParam',
'testFieldQuery',
5)
- then: 'cps data service is being called once to get data node'
- 1 * mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
- cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNode
- and: 'dmi operation is being called to get resource data'
- 1 * mockDmiOperations.getResourceDataOperationalFromDmi('testDmiService',
- 'testCmHandle',
- 'testResourceId',
- 'testFieldQuery',
- 5,
- 'testAcceptParam',
- '{"operation":"read","cmHandleProperties":{"testName":"testValue"}}') >>
- new ResponseEntity<>('result-json', HttpStatus.OK)
- and: 'dmi returns ok response'
+ then: 'dmi returns ok response'
response == 'result-json'
}
@@ -214,15 +245,16 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
and: 'objectMapper not able to parse object'
def mockObjectMapper = Mock(ObjectMapper)
objectUnderTest.objectMapper = mockObjectMapper
- mockObjectMapper.writeValueAsString(_) >> { throw new JsonProcessingException("testException") }
+ mockObjectMapper.writeValueAsString(_) >> { throw new JsonProcessingException('testException') }
when: 'get resource data is called'
def response = objectUnderTest.getResourceDataOperationalForCmHandle('testCmHandle',
'testResourceId',
'testAcceptParam',
'testFieldQuery',
5)
- then: 'exception is thrown'
- thrown(NcmpException.class)
+ then: 'exception is thrown with the expected details'
+ def exceptionThrown = thrown(NcmpException.class)
+ exceptionThrown.details == 'testException'
}
def 'Get resource data for pass-through operational from dmi return NOK response.'() {
@@ -247,7 +279,9 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
'testFieldQuery',
5)
then: 'exception is thrown'
- thrown(NcmpException.class)
+ def exceptionThrown = thrown(NcmpException.class)
+ and: 'details contains the original response'
+ exceptionThrown.details.contains('NOK-json')
}
def 'Get resource data for pass-through running from dmi.'() {
@@ -283,15 +317,16 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
and: 'objectMapper not able to parse object'
def mockObjectMapper = Mock(ObjectMapper)
objectUnderTest.objectMapper = mockObjectMapper
- mockObjectMapper.writeValueAsString(_) >> { throw new JsonProcessingException("testException") }
+ mockObjectMapper.writeValueAsString(_) >> { throw new JsonProcessingException('testException') }
when: 'get resource data is called'
def response = objectUnderTest.getResourceDataPassThroughRunningForCmHandle('testCmHandle',
'testResourceId',
'testAcceptParam',
'testFieldQuery',
5)
- then: 'exception is thrown'
- thrown(NcmpException.class)
+ then: 'exception is thrown with the expected details'
+ def exceptionThrown = thrown(NcmpException.class)
+ exceptionThrown.details == 'testException'
}
def 'Get resource data for pass-through running from dmi return NOK response.'() {
@@ -316,13 +351,15 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
'testFieldQuery',
5)
then: 'exception is thrown'
- thrown(NcmpException.class)
+ def exceptionThrown = thrown(NcmpException.class)
+ and: 'details contains the original response'
+ exceptionThrown.details.contains('NOK-json')
}
def 'Write resource data for pass-through running from dmi using POST.'() {
given: 'data node representing cmHandle and its properties'
def cmHandleDataNode = getCmHandleDataNodeForTest()
- and: 'cpsDataService returns valid dataNode'
+ and: 'cpsDataService returns valid cm-handle datanode'
mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNode
when: 'get resource data is called'
@@ -334,7 +371,7 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
'testCmHandle',
'testResourceId',
'{"operation":"create","dataType":"application/json","data":"{some-json}","cmHandleProperties":{"testName":"testValue"}}')
- >> { new ResponseEntity<>(HttpStatus.CREATED) }
+ >> { new ResponseEntity<>(HttpStatus.OK) }
}
def 'Write resource data for pass-through running from dmi using POST "not found" response (from DMI).'() {
@@ -344,36 +381,45 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNode
and: 'dmi throws exception'
- 1 * mockDmiOperations.createResourceDataPassThroughRunningFromDmi(_ as String, _ as String, _ as String, _ as String)
+ mockDmiOperations.createResourceDataPassThroughRunningFromDmi(_ as String, _ as String, _ as String, _ as String)
>> { new ResponseEntity<>(HttpStatus.NOT_FOUND) }
when: 'get resource data is called'
objectUnderTest.createResourceDataPassThroughRunningForCmHandle('testCmHandle',
'testResourceId',
'{some-json}', 'application/json')
then: 'exception is thrown'
- thrown(NcmpException.class)
+ def exceptionThrown = thrown(NcmpException.class)
+ and: 'details contains (not found) error code: 404'
+ exceptionThrown.details.contains('404')
}
def 'Sync model for a (new) cm handle with #scenario'() {
given: 'DMI PLug-in returns a list of module references'
getModulesForCmHandle()
- def knownModule1 = new ModuleReference('module1', NO_NAMESPACE, '1')
- def knownOtherModule = new ModuleReference('some other module', NO_NAMESPACE, 'some revision')
+ def knownModule1 = new ModuleReference('module1', '1')
+ def knownOtherModule = new ModuleReference('some other module', 'some revision')
and: 'CPS-Core returns list of known modules'
- mockCpsModuleService.getAllYangResourcesModuleReferences() >> [knownModule1, knownOtherModule]
+ mockCpsModuleService.getYangResourceModuleReferences(_) >> [knownModule1, knownOtherModule]
and: 'DMI-Plugin returns resource(s) for "new" module(s)'
def moduleResources = new ResponseEntity<String>(sdncReponseBody, HttpStatus.OK)
- mockDmiOperations.getResourceFromDmi(_, cmHandleForModelSync.getId(), 'moduleResources') >> moduleResources
+ mockDmiOperations.getResourceFromDmiWithJsonData(_, _, _, 'moduleResources') >> moduleResources
when: 'module Sync is triggered'
objectUnderTest.createAnchorAndSyncModel(cmHandleForModelSync)
then: 'the CPS module service is called once with the correct parameters'
- 1 * mockCpsModuleService.createSchemaSetFromModules(expectedDataspaceNameForModleSync, cmHandleForModelSync.getId(), expectedYangResourceToContentMap , [knownModule1])
+ 1 * mockCpsModuleService.createSchemaSetFromModules(expectedDataspaceName, cmHandleForModelSync.getId(), expectedYangResourceToContentMap, [knownModule1])
and: 'admin service create anchor method has been called with correct parameters'
- 1 * mockCpsAdminService.createAnchor(expectedDataspaceNameForModleSync, cmHandleForModelSync.getId(), cmHandleForModelSync.getId())
+ 1 * mockCpsAdminService.createAnchor(expectedDataspaceName, cmHandleForModelSync.getId(), cmHandleForModelSync.getId())
where: 'the following responses are recieved from SDNC'
- scenario | sdncReponseBody || expectedYangResourceToContentMap
- 'one unknown module' | '[{"moduleName" : "someModule", "revision" : "1","yangSource": "someResource"}]' || [someModule: 'someResource']
- 'no unknown module' | '[]' || [:]
+ scenario | sdncReponseBody || expectedYangResourceToContentMap
+ 'one unknown module' | '[{"moduleName" : "someModule", "revision" : "1","yangSource": "[some yang source]"}]' || [someModule: 'some yang source']
+ 'no unknown module' | '[]' || [:]
+ }
+
+ def 'Getting Yang Resources.'() {
+ when: 'yang resources is called'
+ objectUnderTest.getYangResourcesModuleReferences('some cm handle')
+ then: 'CPS module services is invoked for the correct dataspace and cm handle'
+ 1 * mockCpsModuleService.getYangResourcesModuleReferences('NFP-Operational','some cm handle')
}
def getModulesForCmHandle() {
@@ -387,7 +433,7 @@ class NetworkCmProxyDataServiceImplSpec extends Specification {
def getObjectUnderTestWithModelSyncDisabled() {
def objectUnderTest = Spy(new NetworkCmProxyDataServiceImpl(mockDmiOperations, mockCpsModuleService,
- mockCpsDataService, mockCpsQueryService, mockCpsAdminService, new ObjectMapper()))
+ mockCpsDataService, mockCpsQueryService, mockCpsAdminService, spyObjectMapper))
objectUnderTest.createAnchorAndSyncModel(_) >> null
return objectUnderTest
}
diff --git a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/client/DmiRestClientSpec.groovy b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/client/DmiRestClientSpec.groovy
index 879c73c27e..bf6179ba1b 100644
--- a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/client/DmiRestClientSpec.groovy
+++ b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/client/DmiRestClientSpec.groovy
@@ -21,24 +21,30 @@
package org.onap.cps.ncmp.api.impl.client
import org.onap.cps.ncmp.api.impl.config.NcmpConfiguration
+import org.spockframework.spring.SpringBean
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
+import org.springframework.http.HttpMethod
import org.springframework.http.ResponseEntity
+import org.springframework.test.context.ContextConfiguration
import org.springframework.web.client.RestTemplate
import spock.lang.Specification
-import org.springframework.http.HttpMethod
+@SpringBootTest
+@ContextConfiguration(classes = [NcmpConfiguration.DmiProperties, DmiRestClient])
class DmiRestClientSpec extends Specification {
- def mockDmiProperties = Mock(NcmpConfiguration.DmiProperties)
- def mockRestTemplate = Mock(RestTemplate)
- def objectUnderTest = new DmiRestClient(mockRestTemplate, mockDmiProperties)
+ @SpringBean
+ RestTemplate mockRestTemplate = Mock(RestTemplate)
+
+ @Autowired
+ DmiRestClient objectUnderTest
def 'DMI PUT operation.'() {
given: 'a PUT url'
def getResourceDataUrl = 'http://some-uri/getResourceDataUrl'
- and: 'dmi properties'
- setupTestConfigurationData()
and: 'the rest template returns a valid response entity'
def mockResponseEntity = Mock(ResponseEntity)
mockRestTemplate.exchange(getResourceDataUrl, HttpMethod.PUT, _ as HttpEntity, Object.class) >> mockResponseEntity
@@ -51,19 +57,13 @@ class DmiRestClientSpec extends Specification {
def 'DMI POST operation.'() {
given: 'a POST url'
def getResourceDataUrl = 'http://some-uri/createResourceDataUrl'
- and: 'dmi properties'
- setupTestConfigurationData()
and: 'the rest template returns a valid response entity'
def mockResponseEntity = Mock(ResponseEntity)
- mockRestTemplate.postForEntity(getResourceDataUrl, _ as HttpEntity, Void.class) >> mockResponseEntity
+ mockRestTemplate.postForEntity(getResourceDataUrl, _ as HttpEntity, String.class) >> mockResponseEntity
when: 'POST operation is invoked'
def result = objectUnderTest.postOperationWithJsonData(getResourceDataUrl, 'json-data', new HttpHeaders())
then: 'the output of the method is equal to the output from the test template'
result == mockResponseEntity
}
- def setupTestConfigurationData() {
- mockDmiProperties.authUsername >> 'some-username'
- mockDmiProperties.authPassword >> 'some-password'
- }
-} \ No newline at end of file
+}
diff --git a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/config/NcmpConfigurationSpec.groovy b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/config/NcmpConfigurationSpec.groovy
new file mode 100644
index 0000000000..dd4c1375b0
--- /dev/null
+++ b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/config/NcmpConfigurationSpec.groovy
@@ -0,0 +1,52 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.cps.ncmp.api.impl.config
+
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.boot.test.context.SpringBootTest
+import org.springframework.boot.web.client.RestTemplateBuilder
+import org.springframework.test.context.ContextConfiguration
+import org.springframework.web.client.RestTemplate
+import spock.lang.Specification
+
+@SpringBootTest
+@ContextConfiguration(classes = [NcmpConfiguration.DmiProperties])
+class NcmpConfigurationSpec extends Specification{
+
+ @Autowired
+ NcmpConfiguration.DmiProperties dmiProperties
+
+ def 'DMI Properties.'() {
+ expect: 'properties are set to values in test configuration yaml file'
+ dmiProperties.authUsername == 'some-user'
+ dmiProperties.authPassword == 'some-password'
+ }
+
+ def 'Rest Template creation.'() {
+ given: 'a rest template builder'
+ def mockRestTemplateBuilder = Mock(RestTemplateBuilder)
+ def expectedRestTemplate = Mock(RestTemplate)
+ mockRestTemplateBuilder.build() >> expectedRestTemplate
+ when: 'a rest template is created'
+ def result = NcmpConfiguration.restTemplate(mockRestTemplateBuilder)
+ then: 'the rest template from the builder is returned'
+ assert result == expectedRestTemplate
+ }
+}
diff --git a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/operation/DmiOperationsSpec.groovy b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/operation/DmiOperationsSpec.groovy
index 987ab2bca1..6a1ce1a18b 100644
--- a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/operation/DmiOperationsSpec.groovy
+++ b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/operation/DmiOperationsSpec.groovy
@@ -92,4 +92,18 @@ class DmiOperationsSpec extends Specification {
then: 'the post operation is executed with the correct URL'
1 * mockDmiRestClient.postOperation(expectedUrl, _ as HttpHeaders)
}
+
+ def 'Call get resource from dmi with json data.'() {
+ given: 'expected url & json data'
+ def requestBody = 'some json'
+ def expectedUrl = 'testDmiBasePath/dmi/v1/ch/testCmHandle/modules'
+ def expectedHttpHeaders = new HttpHeaders()
+ when: 'get resource data is called to dmi'
+ objectUnderTest.getResourceFromDmiWithJsonData('testDmiBasePath',
+ requestBody,
+ 'testCmHandle',
+ 'modules')
+ then: 'the post operation is executed with the correct URL and json data'
+ 1 * mockDmiRestClient.postOperationWithJsonData(expectedUrl, requestBody, expectedHttpHeaders)
+ }
} \ No newline at end of file
diff --git a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/models/PersistenceCmHandleSpec.groovy b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/models/PersistenceCmHandleSpec.groovy
new file mode 100644
index 0000000000..bfed795f76
--- /dev/null
+++ b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/models/PersistenceCmHandleSpec.groovy
@@ -0,0 +1,42 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.cps.ncmp.api.models
+
+import spock.lang.Specification
+
+class PersistenceCmHandleSpec extends Specification {
+
+ def objectUnderTest = new PersistenceCmHandle()
+
+ def 'Setting and getting additional properties.'() {
+ given: 'a map of one property is added'
+ objectUnderTest.setAdditionalProperties([myProperty: 'some value'])
+ when: 'the additional properties are retrieved'
+ def result = objectUnderTest.getAdditionalProperties()
+ then: 'the result has the right size'
+ assert result.size() == 1
+ and: 'the property in the result has the correct name and value'
+ def actualAdditionalProperty = result.get(0)
+ def expectedAdditionalProperty = new PersistenceCmHandle.AdditionalProperty('myProperty','some value')
+ assert actualAdditionalProperty.name == expectedAdditionalProperty.name
+ assert actualAdditionalProperty.value == expectedAdditionalProperty.value
+ }
+
+}
diff --git a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/models/moduleReferenceSpec.groovy b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/models/moduleReferenceSpec.groovy
index d6cb4635d8..444a25804b 100644
--- a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/models/moduleReferenceSpec.groovy
+++ b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/models/moduleReferenceSpec.groovy
@@ -1,14 +1,33 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
package org.onap.cps.ncmp.api.models
-import org.onap.cps.spi.model.ModuleReference
+import org.onap.cps.spi.model.ExtendedModuleReference
import spock.lang.Specification
class moduleReferenceSpec extends Specification {
def 'lombok data annotation correctly implements toString() and hashCode() methods'() {
given: 'two moduleReference objects'
- def moduleReference1 = new ModuleReference('module1', "some namespace", '1')
- def moduleReference2 = new ModuleReference('module1', "some namespace", '1')
+ def moduleReference1 = new ExtendedModuleReference('module1', "some namespace", '1')
+ def moduleReference2 = new ExtendedModuleReference('module1', "some namespace", '1')
when: 'lombok generated methods are called'
then: 'the methods exist and behaviour is accurate'
assert moduleReference1.toString() == moduleReference2.toString()
diff --git a/cps-ncmp-service/src/test/resources/application.yml b/cps-ncmp-service/src/test/resources/application.yml
new file mode 100644
index 0000000000..71ac2c9a03
--- /dev/null
+++ b/cps-ncmp-service/src/test/resources/application.yml
@@ -0,0 +1,23 @@
+# ============LICENSE_START=======================================================
+# Copyright (C) 2021 Nordix Foundation
+# ================================================================================
+# 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.
+#
+# SPDX-License-Identifier: Apache-2.0
+# ============LICENSE_END=========================================================
+
+dmi:
+ auth:
+ username: some-user
+ password: some-password
+