aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/so-bpmn-infrastructure-common
diff options
context:
space:
mode:
Diffstat (limited to 'bpmn/so-bpmn-infrastructure-common')
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/HandleOrchestrationTask.groovy127
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceService.groovy7
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationService.groovy65
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceService.groovy58
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSIandNSSI.groovy338
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSSI.groovy771
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceInstance.groovy232
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceOption.groovy524
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy23
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceService.groovy6
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoSendCommandToNSSMF.groovy463
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ExecutionVariableNames.java2
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcher.java9
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationServiceTest.groovy224
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationServiceTest.groovy308
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceServiceTest.groovy171
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSITest.groovy258
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceServiceTest.groovy460
18 files changed, 3972 insertions, 74 deletions
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/HandleOrchestrationTask.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/HandleOrchestrationTask.groovy
new file mode 100644
index 0000000000..89490ff620
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/HandleOrchestrationTask.groovy
@@ -0,0 +1,127 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.infrastructure.scripts
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.onap.so.db.request.beans.OrchestrationTask
+
+import static org.apache.commons.lang3.StringUtils.*
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+class HandleOrchestrationTask extends AbstractServiceTaskProcessor {
+ private static final Logger logger = LoggerFactory.getLogger(HandleOrchestrationTask.class)
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ def supportedMethod = ["GET", "POST", "PUT"]
+ def validStatus = [200, 201]
+
+ @Override
+ public void preProcessRequest(DelegateExecution execution) {
+ logger.debug("Start preProcessRequest")
+ String method = execution.getVariable("method")
+ if (!supportedMethod.contains(method)) {
+ String msg = "Method: " + method + " is not supported"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ String taskId = execution.getVariable("taskId")
+ if (isBlank(taskId)) {
+ String msg = "taskId is empty"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.requestDb.endpoint",execution)
+ def orchestrationTaskEndpoint = dbAdapterEndpoint + "/orchestrationTask/"
+ if (!"POST".equals(method)) {
+ orchestrationTaskEndpoint = orchestrationTaskEndpoint + taskId
+ }
+ execution.setVariable("url", orchestrationTaskEndpoint)
+ logger.debug("DB Adapter Endpoint is: " + orchestrationTaskEndpoint)
+ def dbAdapterAuth = UrnPropertiesReader.getVariable("mso.adapters.requestDb.auth")
+ Map<String, String> headerMap = [:]
+ headerMap.put("content-type", "application/json")
+ headerMap.put("Authorization", dbAdapterAuth)
+ execution.setVariable("headerMap", headerMap)
+ logger.debug("DB Adapter Header is: " + headerMap)
+
+ String requestId = execution.getVariable("requestId")
+ if (("POST".equals(method) || "PUT".equals(method)) && isBlank(requestId)) {
+ String msg = "requestId is empty"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ String taskName = execution.getVariable("taskName")
+ if (("POST".equals(method) || "PUT".equals(method)) && isBlank(taskName)) {
+ String msg = "task name is empty"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ String taskStatus = execution.getVariable("taskStatus")
+ if (("POST".equals(method) || "PUT".equals(method)) && isBlank(taskStatus)) {
+ String msg = "task status is empty"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ String isManual = execution.getVariable("isManual")
+ if (("POST".equals(method) || "PUT".equals(method)) && isBlank(isManual)) {
+ String msg = "isManual is empty"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ String paramJson = execution.getVariable("paramJson")
+
+ String payload = ""
+ if ("POST".equals(method) || "PUT".equals(method)) {
+ OrchestrationTask task = new OrchestrationTask()
+ task.setTaskId(taskId)
+ task.setRequestId(requestId)
+ task.setName(taskName)
+ task.setStatus(taskStatus)
+ task.setIsManual(isManual)
+ task.setParams(paramJson)
+ ObjectMapper objectMapper = new ObjectMapper()
+ payload = objectMapper.writeValueAsString(task)
+ logger.debug("Outgoing payload is \n" + payload)
+ }
+ execution.setVariable("payload", payload)
+ logger.debug("End preProcessRequest")
+ }
+
+ public void postProcess(DelegateExecution execution) {
+ Integer statusCode = execution.getVariable("statusCode")
+ logger.debug("statusCode: " + statusCode)
+ String response = execution.getVariable("response")
+ logger.debug("response: " + response)
+ if (!validStatus.contains(statusCode)) {
+ String msg = "Error in sending orchestrationTask request. \nstatusCode: " + statusCode + "\nresponse: " + response
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+}
+
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceService.groovy
index 7cc1a559c3..c3f36ef545 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceService.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceService.groovy
@@ -273,7 +273,6 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
execution.setVariable("orchestrationTaskId", taskId)
logger.debug("BusinessKey: " + taskId)
String serviceInstanceId = execution.getVariable("serviceInstanceId")
- String operationId = execution.getVariable("operationId")
String serviceInstanceName = execution.getVariable("serviceInstanceName")
String taskName = "SliceServiceTask"
String taskStatus = "Planning"
@@ -286,17 +285,11 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
execution.setVariable("CSSOT_requestMethod", requestMethod)
Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
- Map<String, Object> sliceProfileTn = execution.getVariable("sliceProfileTn")
- Map<String, Object> sliceProfileCn = execution.getVariable("sliceProfileCn")
- Map<String, Object> sliceProfileAn = execution.getVariable("sliceProfileAn")
SliceTaskParams sliceTaskParams = new SliceTaskParams()
sliceTaskParams.setServiceId(serviceInstanceId)
sliceTaskParams.setServiceName(serviceInstanceName)
sliceTaskParams.setServiceProfile(serviceProfile)
- sliceTaskParams.setSliceProfileTn(sliceProfileTn)
- sliceTaskParams.setSliceProfileCn(sliceProfileCn)
- sliceTaskParams.setSliceProfileAn(sliceProfileAn)
execution.setVariable("sliceTaskParams", sliceTaskParams)
String paramJson = sliceTaskParams.convertToJson()
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationService.groovy
index 00b0b37b18..b121083954 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationService.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationService.groovy
@@ -141,7 +141,7 @@ class DeleteCommunicationService extends AbstractServiceTaskProcessor {
* save e2eslice-service instance id and service name
* @param execution
*/
- private void queryCommunicationSeriveFromAAI(DelegateExecution execution)
+ void queryCommunicationSeriveFromAAI(DelegateExecution execution)
{
LOGGER.trace(" ***** begin queryCommunicationSeriveFromAAI *****")
String serviceInstanceId = execution.getVariable("serviceInstanceId")
@@ -186,12 +186,11 @@ class DeleteCommunicationService extends AbstractServiceTaskProcessor {
String globalSubscriberId = execution.getVariable("globalSubscriberId")
String serviceType = execution.getVariable("serviceType")
- AAIResourcesClient resourceClient = new AAIResourcesClient()
AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(aaiObjectType, globalSubscriberId, serviceType, instanceId)
- if (!resourceClient.exists(resourceUri)) {
+ if (!getAAIClient().exists(resourceUri)) {
exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMsg)
}
- AAIResultWrapper wrapper = resourceClient.get(resourceUri, NotFoundException.class)
+ AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
return wrapper
}
@@ -215,7 +214,7 @@ class DeleteCommunicationService extends AbstractServiceTaskProcessor {
requestBody.replaceAll("\\s+", "")
String basicAuthValue = UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
- HttpClient httpClient = new HttpClientFactory().newJsonClient(new URL(url), ONAPComponents.SO)
+ HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.SO)
httpClient.addAdditionalHeader("Authorization", basicAuthValue)
httpClient.addAdditionalHeader("Accept", "application/json")
Response httpResponse = httpClient.delete(requestBody)
@@ -233,6 +232,41 @@ class DeleteCommunicationService extends AbstractServiceTaskProcessor {
}
/**
+ * prepare update operation status
+ * @param execution
+ */
+ private void handleNSSMFWFResponse(Response httpResponse, DelegateExecution execution){
+ LOGGER.debug(" ======== STARTED prepareUpdateOperationStatus Process ======== ")
+
+ int nsmfResponseCode = httpResponse.getStatus()
+ LOGGER.debug("nsmfResponseCode${nsmfResponseCode}")
+
+ if (nsmfResponseCode >= 200 && nsmfResponseCode < 204 && httpResponse.hasEntity()) {
+ String nsmfResponse = httpResponse.readEntity(String.class)
+ def e2eOperationId = jsonUtil.getJsonValue(nsmfResponse, "operationId")
+ execution.setVariable("e2eOperationId", e2eOperationId)
+ execution.setVariable("progress","20")
+ execution.setVariable("operationContent","waiting nsmf service delete finished")
+
+ execution.setVariable("currentCycle",0)
+ execution.setVariable("isNSMFTimeOut", "no")
+ execution.setVariable("isNSMFWFRspSucceed","yes")
+ }
+ else
+ {
+ String serviceName = execution.getVariable("serviceInstanceName")
+ execution.setVariable("progress", "100")
+ execution.setVariable("result", "error")
+ execution.setVariable("operationContent", "terminate service failure.")
+ execution.setVariable("reason","NSMF WF asynchronous response failed, status Code:${nsmfResponseCode}")
+ execution.setVariable("isNSMFWFRspSucceed","no")
+ LOGGER.error("nsmf async response error,nsmfResponseCode:${nsmfResponseCode},serivceName:${serviceName}")
+ }
+ setOperationStatus(execution)
+ LOGGER.debug("======== COMPLETED prepareUpdateOperationStatus Process ======== ")
+ }
+
+ /**
* prepare to call sub process
* @param execution
*/
@@ -272,22 +306,20 @@ class DeleteCommunicationService extends AbstractServiceTaskProcessor {
String profileId
try
{
- AAIResourcesClient resourceClient = new AAIResourcesClient()
AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.COMMUNICATION_PROFILE_ALL, globalSubscriberId, serviceType, serviceInstanceId)
- AAIResultWrapper wrapper = resourceClient.get(resourceUri, NotFoundException.class)
+ AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
Optional<CommunicationServiceProfiles> csProfilesOpt = wrapper.asBean(CommunicationServiceProfiles.class)
if(csProfilesOpt.isPresent()){
- CommunicationServiceProfiles csProf
- iles = csProfilesOpt.get()
+ CommunicationServiceProfiles csProfiles = csProfilesOpt.get()
CommunicationServiceProfile csProfile = csProfiles.getCommunicationServiceProfile().get(0)
profileId = csProfile ? csProfile.getProfileId() : ""
}
resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.COMMUNICATION_SERVICE_PROFILE, globalSubscriberId, serviceType, serviceInstanceId, profileId)
- if (!resourceClient.exists(resourceUri)) {
+ if (!getAAIClient().exists(resourceUri)) {
exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "communication service profile was not found in aai")
}
-
- resourceClient.delete(resourceUri)
+
+ getAAIClient().delete(resourceUri)
LOGGER.debug("end delete communication service profile from AAI")
}
catch (any)
@@ -308,9 +340,8 @@ class DeleteCommunicationService extends AbstractServiceTaskProcessor {
try
{
LOGGER.debug("start delete communication service from AAI")
- AAIResourcesClient resourceClient = new AAIResourcesClient()
AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), execution.getVariable("serviceInstanceId"))
- resourceClient.delete(serviceInstanceUri)
+ getAAIClient().delete(serviceInstanceUri)
execution.setVariable("progress", "100")
execution.setVariable("result", "finished")
@@ -330,12 +361,10 @@ class DeleteCommunicationService extends AbstractServiceTaskProcessor {
LOGGER.debug("Starting sendSyncError")
try {
- String errorMessage
+ String errorMessage = "Sending Sync Error."
if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
WorkflowException wfe = execution.getVariable("WorkflowException")
errorMessage = wfe.getErrorMessage()
- } else {
- errorMessage = "Sending Sync Error."
}
String buildworkflowException =
@@ -397,6 +426,7 @@ class DeleteCommunicationService extends AbstractServiceTaskProcessor {
void prepareFailureStatus(DelegateExecution execution)
{
+ execution.setVariable("result", "finished")
execution.setVariable("progress", "100")
execution.setVariable("operationContent", "terminate service failure.")
setOperationStatus(execution)
@@ -426,4 +456,5 @@ class DeleteCommunicationService extends AbstractServiceTaskProcessor {
execution.setVariable(paraName, paramValue)
}
}
+
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceService.groovy
index f0d43cf8d7..d8160a97bc 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceService.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceService.groovy
@@ -45,19 +45,19 @@ import static org.apache.commons.lang3.StringUtils.isBlank
class DeleteSliceService extends AbstractServiceTaskProcessor {
- String Prefix="DELSS_"
+ private final String PREFIX ="DeleteSliceService"
ExceptionUtil exceptionUtil = new ExceptionUtil()
JsonUtils jsonUtil = new JsonUtils()
private RequestDBUtil requestDBUtil = new RequestDBUtil()
- private static final Logger logger = LoggerFactory.getLogger( DeleteSliceService.class)
+ private static final Logger LOGGER = LoggerFactory.getLogger( DeleteSliceService.class)
@Override
void preProcessRequest(DelegateExecution execution) {
- execution.setVariable("prefix", Prefix)
+ execution.setVariable("prefix", PREFIX)
String msg = ""
- logger.trace("Starting preProcessRequest")
+ LOGGER.debug("*****${PREFIX} preProcessRequest *****")
try {
// check for incoming json message/input
@@ -71,7 +71,7 @@ class DeleteSliceService extends AbstractServiceTaskProcessor {
msg = "e2eslice-service id is null"
exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
}
- logger.info("Input Request: ${siRequest}, reqId: ${requestId}, e2eslice-service: ${serviceInstanceId}")
+ LOGGER.info("Input Request: ${siRequest}, reqId: ${requestId}, e2eslice-service: ${serviceInstanceId}")
//subscriberInfo
checkAndSetRequestParam(siRequest,"globalSubscriberId",false, execution)
@@ -82,17 +82,17 @@ class DeleteSliceService extends AbstractServiceTaskProcessor {
execution.setVariable("progress", "0")
execution.setVariable("result", "processing")
execution.setVariable("operationType", "DELETE")
- execution.setVariable("operationContent", "Prepare init service")
+ execution.setVariable("operationContent", "Delete Slice service operation start")
updateServiceOperationStatus(execution)
} catch (BpmnError e) {
throw e
} catch (Exception ex) {
msg = "Exception in preProcessRequest " + ex.getMessage()
- logger.debug(msg)
+ LOGGER.debug(msg)
exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
}
- logger.trace("Exit preProcessRequest")
+ LOGGER.debug("*****${PREFIX} Exit preProcessRequest *****")
}
/**
@@ -100,40 +100,39 @@ class DeleteSliceService extends AbstractServiceTaskProcessor {
* @param execution
*/
void sendAsyncResponse(DelegateExecution execution) {
- logger.trace("Staring sendSyncResponse")
+ LOGGER.trace("${PREFIX} Start sendSyncResponse ")
try {
String operationId = execution.getVariable("operationId")
String syncResponse = """{"operationId":"${operationId}"}""".trim()
- logger.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
+ LOGGER.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
sendWorkflowResponse(execution, 202, syncResponse)
} catch (Exception ex) {
String msg = "Exception in sendSyncResponse: " + ex.getMessage()
exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
}
- logger.trace("Exit sendSyncResponse")
+ LOGGER.trace("${PREFIX} Exit sendSyncResponse")
}
/**
* Deletes the slice service instance in aai
*/
void deleteSliceServiceInstance(DelegateExecution execution) {
- logger.trace("Entered deleteSliceServiceInstance")
+ LOGGER.trace("${PREFIX} Start deleteSliceServiceInstance")
try {
- AAIResourcesClient resourceClient = new AAIResourcesClient()
AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), execution.getVariable("serviceInstanceId"))
- resourceClient.delete(serviceInstanceUri)
+ getAAIClient().delete(serviceInstanceUri)
execution.setVariable("progress", "100")
execution.setVariable("result", "finished")
execution.setVariable("operationContent", "NSMF completes slicing service termination.")
updateServiceOperationStatus(execution)
- logger.trace("Exited deleteSliceServiceInstance")
+ LOGGER.trace("${PREFIX} Exited deleteSliceServiceInstance")
}catch(Exception e){
- logger.debug("Error occured within deleteSliceServiceInstance method: " + e)
+ LOGGER.debug("Error occured within deleteSliceServiceInstance method: " + e)
exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteSliceServiceInstance from aai")
}
}
@@ -161,7 +160,7 @@ class DeleteSliceService extends AbstractServiceTaskProcessor {
* delete service profile from aai
* @param execution
*/
- private void delServiceProfileFromAAI(DelegateExecution execution)
+ void delServiceProfileFromAAI(DelegateExecution execution)
{
String globalSubscriberId = execution.getVariable("globalSubscriberId")
String serviceType = execution.getVariable("serviceType")
@@ -170,9 +169,8 @@ class DeleteSliceService extends AbstractServiceTaskProcessor {
try
{
- AAIResourcesClient resourceClient = new AAIResourcesClient()
AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE_ALL, globalSubscriberId, serviceType, serviceInstanceId)
- AAIResultWrapper wrapper = resourceClient.get(resourceUri, NotFoundException.class)
+ AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
Optional<ServiceProfiles> serviceProfilesOpt =wrapper.asBean(ServiceProfiles.class)
if(serviceProfilesOpt.isPresent()){
ServiceProfiles serviceProfiles = serviceProfilesOpt.get()
@@ -180,29 +178,27 @@ class DeleteSliceService extends AbstractServiceTaskProcessor {
profileId = serviceProfile ? serviceProfile.getProfileId() : ""
}
resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE, globalSubscriberId, serviceType, serviceInstanceId, profileId)
- if (!resourceClient.exists(resourceUri)) {
+ if (!getAAIClient().exists(resourceUri)) {
exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
}
- resourceClient.delete(resourceUri)
+ getAAIClient().delete(resourceUri)
}
catch (any)
{
String msg = "delete service profile from aai failed! cause-"+any.getCause()
- logger.error(any.printStackTrace())
+ LOGGER.error(any.printStackTrace())
exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
}
}
void sendSyncError(DelegateExecution execution) {
- logger.info("Starting sendSyncError")
+ LOGGER.debug("${PREFIX} Start sendSyncError")
try {
- String errorMessage
+ String errorMessage = "Sending Sync Error."
if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
WorkflowException wfe = execution.getVariable("WorkflowException")
errorMessage = wfe.getErrorMessage()
- } else {
- errorMessage = "Sending Sync Error."
}
String buildworkflowException =
@@ -211,17 +207,17 @@ class DeleteSliceService extends AbstractServiceTaskProcessor {
<aetgt:ErrorCode>7000</aetgt:ErrorCode>
</aetgt:WorkflowException>"""
- logger.debug(buildworkflowException)
+ LOGGER.debug(buildworkflowException)
sendWorkflowResponse(execution, 500, buildworkflowException)
} catch (Exception ex) {
- logger.error("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
+ LOGGER.error("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
}
}
void prepareEndOperationStatus(DelegateExecution execution){
- logger.debug(" ======== STARTED prepareEndOperationStatus Process ======== ")
+ LOGGER.debug(" ======== ${PREFIX} STARTED prepareEndOperationStatus Process ======== ")
execution.setVariable("progress", "100")
execution.setVariable("result", "error")
@@ -233,7 +229,7 @@ class DeleteSliceService extends AbstractServiceTaskProcessor {
execution.setVariable("reason",errorMessage)
updateServiceOperationStatus(execution)
- logger.debug("======== COMPLETED prepareEndOperationStatus Process ======== ")
+ LOGGER.debug("======== ${PREFIX} COMPLETED prepareEndOperationStatus Process ======== ")
}
/**
@@ -250,7 +246,7 @@ class DeleteSliceService extends AbstractServiceTaskProcessor {
String paramValue = jsonUtil.getJsonValue(siRequest, paraName)
if (isBlank(paramValue)) {
msg = "Input ${paraName} is null"
- logger.error(msg)
+ LOGGER.error(msg)
if(isErrorException)
{
exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSIandNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSIandNSSI.groovy
new file mode 100644
index 0000000000..d5b554d841
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSIandNSSI.groovy
@@ -0,0 +1,338 @@
+package org.onap.so.bpmn.infrastructure.scripts
+
+import com.google.common.reflect.TypeToken
+import com.google.gson.Gson
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.AllottedResource
+import org.onap.aai.domain.yang.Relationship
+import org.onap.aai.domain.yang.RelationshipList
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.so.beans.nsmf.SliceTaskParams
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.domain.ServiceProxy
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.AAIResourcesClient
+import org.onap.so.client.aai.entities.AAIEdgeLabel
+import org.onap.so.client.aai.entities.AAIResultWrapper
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.db.request.client.RequestsDbClient
+import org.onap.so.db.request.beans.OrchestrationTask
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import javax.ws.rs.NotFoundException
+import javax.ws.rs.core.UriBuilder
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class DoAllocateNSIandNSSI extends org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor{
+
+ private static final Logger logger = LoggerFactory.getLogger( DoAllocateNSIandNSSI.class);
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ JsonUtils jsonUtil = new JsonUtils()
+ RequestsDbClient requestsDbClient = new RequestsDbClient()
+
+ /**
+ * Pre Process the BPMN Flow Request
+ * Inclouds:
+ * generate the nsOperationKey
+ * generate the nsParameters
+ */
+
+ void preProcessRequest (DelegateExecution execution) {
+ String msg = ""
+ logger.trace("Enter preProcessRequest()")
+ Map<String, Object> nssiMap = new HashMap<>()
+ execution.setVariable("nssiMap", nssiMap)
+ boolean isMoreNSSTtoProcess = true
+ execution.setVariable("isMoreNSSTtoProcess", isMoreNSSTtoProcess)
+ List<String> nsstSequence = new ArrayList<>(Arrays.asList("cn"))
+ execution.setVariable("nsstSequence", nsstSequence)
+ logger.trace("Exit preProcessRequest")
+ }
+
+ void retriveSliceOption(DelegateExecution execution) {
+ logger.trace("Enter retriveSliceOption() of DoAllocateNSIandNSSI")
+ String uuiRequest = execution.getVariable("uuiRequest")
+ boolean isNSIOptionAvailable = false
+ List<String> nssiAssociated = new ArrayList<>()
+ SliceTaskParams sliceParams = execution.getVariable("sliceTaskParams")
+ try
+ {
+ String modelUuid = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.nstar0_allottedresource0_providing_service_uuid")
+ String modelInvariantUuid = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.nstar0_allottedresource0_providing_service_invariant_uuid")
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ //Params sliceParams = new Gson().fromJson(params, new TypeToken<Params>() {}.getType());
+ execution.setVariable("sliceParams", sliceParams)
+ }catch (Exception ex) {
+ logger.debug( "Unable to get the task information from request DB: " + ex)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Unable to get task information from request DB.")
+ }
+
+ if(isBlank(sliceParams.getSuggestNsiId()))
+ {
+ isNSIOptionAvailable=false
+ }
+ else
+ {
+ isNSIOptionAvailable=true
+ execution.setVariable('nsiServiceInstanceId',sliceParams.getSuggestNsiId())
+ execution.setVariable('nsiServiceInstanceName',sliceParams.getSuggestNsiName())
+ }
+ execution.setVariable("isNSIOptionAvailable",isNSIOptionAvailable)
+ logger.trace("Exit retriveSliceOption() of DoAllocateNSIandNSSI")
+ }
+
+ void updateRelationship(DelegateExecution execution) {
+ logger.trace("Enter update relationship in DoAllocateNSIandNSSI()")
+ String nsiServiceInstanceId = execution.getVariable("nsiServiceInstanceId")
+ String allottedResourceId = execution.getVariable("allottedResourceId")
+ //Need to check whether nsi exist : Begin
+ org.onap.aai.domain.yang.ServiceInstance nsiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance()
+ SliceTaskParams sliceParams = execution.getVariable("sliceParams")
+
+ String nsiServiceInstanceID = sliceParams.getSuggestNsiId()
+
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri nsiServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), nsiServiceInstanceID)
+ //AAIResourceUri nsiServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.QUERY_ALLOTTED_RESOURCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), nsiServiceInstanceID)
+
+ try {
+ AAIResultWrapper wrapper = resourceClient.get(nsiServiceuri, NotFoundException.class)
+ Optional<org.onap.aai.domain.yang.ServiceInstance> si = wrapper.asBean(org.onap.aai.domain.yang.ServiceInstance.class)
+ nsiServiceInstance = si.get()
+ //allottedResourceId=nsiServiceInstance.getAllottedResources().getAllottedResource().get(0).getId()
+
+// if(resourceClient.exists(nsiServiceuri)){
+// execution.setVariable("nsi_resourceLink", nsiServiceuri.build().toString())
+// }else{
+// exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai to " +
+// "associate for service :"+serviceInstanceId)
+// }
+ }catch(BpmnError e) {
+ throw e;
+ }catch (Exception ex){
+ String msg = "NSI suggested in the option doesn't exist. " + nsiServiceInstanceID
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), nsiServiceInstanceId, allottedResourceId)
+ getAAIClient().connect(allottedResourceUri,nsiServiceuri)
+
+ List<String> nssiAssociated = new ArrayList<>()
+ RelationshipList relationshipList = nsiServiceInstance.getRelationshipList()
+ List<Relationship> relationships = relationshipList.getRelationship()
+ for(Relationship relationship in relationships)
+ {
+ if(relationship.getRelatedTo().equalsIgnoreCase("service-instance"))
+ {
+ String NSSIassociated = relationship.getRelatedLink().substring(relationship.getRelatedLink().lastIndexOf("/") + 1);
+ if(!NSSIassociated.equals(nsiServiceInstanceID))
+ nssiAssociated.add(NSSIassociated)
+ }
+ }
+ execution.setVariable("nssiAssociated",nssiAssociated)
+ execution.setVariable("nsiServiceInstanceName",nsiServiceInstance.getServiceInstanceName())
+ logger.trace("Exit update relationship in DoAllocateNSIandNSSI()")
+ }
+
+ void prepareNssiModelInfo(DelegateExecution execution){
+ logger.trace("Enter prepareNssiModelInfo in DoAllocateNSIandNSSI()")
+ List<String> nssiAssociated = new ArrayList<>()
+ Map<String, Object> nssiMap = new HashMap<>()
+ nssiAssociated=execution.getVariable("nssiAssociated")
+ for(String nssiID in nssiAssociated)
+ {
+ try {
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), nssiID)
+ AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class)
+ Optional<org.onap.aai.domain.yang.ServiceInstance> si = wrapper.asBean(org.onap.aai.domain.yang.ServiceInstance.class)
+ org.onap.aai.domain.yang.ServiceInstance nssi = si.get()
+ nssiMap.put(nssi.getEnvironmentContext(),"""{
+ "serviceInstanceId":"${nssi.getServiceInstanceId()}",
+ "modelUuid":"${nssi.getModelVersionId()}"
+ }""")
+
+ }catch(NotFoundException e)
+ {
+ logger.debug("NSSI Service Instance not found in AAI: " + nssiID)
+ }catch(Exception e)
+ {
+ logger.debug("NSSI Service Instance not found in AAI: " + nssiID)
+ }
+ execution.setVariable("nssiMap",nssiMap)
+
+ }
+ logger.trace("Exit prepareNssiModelInfo in DoAllocateNSIandNSSI()")
+ }
+
+ void createNSIinAAI(DelegateExecution execution) {
+ logger.trace("Enter CreateNSIinAAI in DoAllocateNSIandNSSI()")
+ ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
+ org.onap.aai.domain.yang.ServiceInstance nsi = new ServiceInstance();
+ String sliceInstanceId = UUID.randomUUID().toString()
+ execution.setVariable("sliceInstanceId",sliceInstanceId)
+ nsi.setServiceInstanceId(sliceInstanceId)
+ String sliceInstanceName = "nsi_"+execution.getVariable("serviceInstanceName")
+ nsi.setServiceInstanceName(sliceInstanceName)
+ String serviceType = execution.getVariable("serviceType")
+ nsi.setServiceType(serviceType)
+ String serviceStatus = "deactivated"
+ nsi.setOrchestrationStatus(serviceStatus)
+ String modelInvariantUuid = serviceDecomposition.getModelInfo().getModelInvariantUuid()
+ String modelUuid = serviceDecomposition.getModelInfo().getModelUuid()
+ nsi.setModelInvariantId(modelInvariantUuid)
+ nsi.setModelVersionId(modelUuid)
+ String uuiRequest = execution.getVariable("uuiRequest")
+ String serviceInstanceLocationid = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.plmnIdList")
+ nsi.setServiceInstanceLocationId(serviceInstanceLocationid)
+ //String snssai = jsonUtil.getJsonValue(uuiRequest, "service.requestInputs.snssai")
+ //nsi.setEnvironmentContext(snssai)
+ String serviceRole = "nsi"
+ nsi.setServiceRole(serviceRole)
+ try {
+
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), sliceInstanceId)
+ client.create(uri, nsi)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ Map<String, Object> nssiMap = new HashMap<>()
+ List<ServiceProxy> serviceProxyList = serviceDecomposition.getServiceProxy()
+ List<String> nsstModelInfoList = new ArrayList<>()
+ for(ServiceProxy serviceProxy : serviceProxyList)
+ {
+ //String nsstModelUuid = serviceProxy.getModelInfo().getModelUuid()
+ String nsstModelUuid = serviceProxy.getSourceModelUuid()
+ //String nsstModelInvariantUuid = serviceProxy.getModelInfo().getModelInvariantUuid()
+ String nsstServiceModelInfo = """{
+ "modelInvariantUuid":"",
+ "modelUuid":"${nsstModelUuid}",
+ "modelVersion":""
+ }"""
+ nsstModelInfoList.add(nsstServiceModelInfo)
+ }
+ int currentIndex=0
+ int maxIndex=nsstModelInfoList.size()
+ if(maxIndex < 1)
+ {
+ msg = "Exception in DoAllocateNSIandNSSI. There is no NSST associated with NST "
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ execution.setVariable("nsstModelInfoList",nsstModelInfoList)
+ execution.setVariable("currentIndex",currentIndex)
+ execution.setVariable("maxIndex",maxIndex)
+ execution.setVariable('nsiServiceInstanceId',sliceInstanceId)
+ execution.setVariable("nsiServiceInstanceName",sliceInstanceName)
+ logger.trace("Exit CreateNSIinAAI in DoAllocateNSIandNSSI()")
+ }
+
+ void getOneNsstInfo(DelegateExecution execution){
+ List<String> nsstModelInfoList = new ArrayList<>()
+ nsstModelInfoList = execution.getVariable("nsstModelInfoList")
+ int currentIndex = execution.getVariable("currentIndex")
+ int maxIndex = execution.getVariable("maxIndex")
+ boolean isMoreNSSTtoProcess = true
+ String nsstServiceModelInfo = nsstModelInfoList.get(currentIndex)
+ execution.setVariable("serviceModelInfo", nsstServiceModelInfo)
+ execution.setVariable("currentIndex", currentIndex)
+ currentIndex = currentIndex+1
+ if(currentIndex <= maxIndex )
+ isMoreNSSTtoProcess = false
+ execution.setVariable("isMoreNSSTtoProcess", isMoreNSSTtoProcess)
+ }
+
+ void createNSSTMap(DelegateExecution execution){
+ ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
+ String modelUuid= serviceDecomposition.getModelInfo().getModelUuid()
+ String content = serviceDecomposition.getServiceInfo().getServiceArtifact().get(0).getContent()
+ //String nsstID = jsonUtil.getJsonValue(content, "metadata.id")
+ //String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
+ //String type = jsonUtil.getJsonValue(content, "metadata.type")
+ String domain = jsonUtil.getJsonValue(content, "metadata.domainType")
+
+ Map<String, Object> nssiMap = execution.getVariable("nssiMap")
+ String servicename = execution.getVariable("serviceInstanceName")
+ String nsiname = "nsi_"+servicename
+ nssiMap.put(domain,"""{
+ "serviceInstanceId":"",
+ "modelUuid":"${modelUuid}"
+ }""")
+ execution.setVariable("nssiMap",nssiMap)
+ }
+
+ void prepareNSSIList(DelegateExecution execution){
+ logger.trace("Enter prepareNSSIList in DoAllocateNSIandNSSI()")
+ Map<String, Object> nssiMap = new HashMap<>()
+ Boolean isMoreNSSI = false
+ nssiMap = execution.getVariable("nssiMap")
+ List<String> keys=new ArrayList<String>(nssiMap.values())
+ List<String> nsstSequence = execution.getVariable("nsstSequence")
+ Integer currentIndex=0;
+ execution.setVariable("currentNssiIndex",currentIndex)
+ Integer maxIndex=keys.size()
+ execution.setVariable("maxIndex",maxIndex)
+ if(maxIndex>0)
+ isMoreNSSI=true
+ execution.setVariable("isMoreNSSI",isMoreNSSI)
+ logger.trace("Exit prepareNSSIList in DoAllocateNSIandNSSI()")
+ }
+
+
+ void getOneNSSIInfo(DelegateExecution execution){
+ logger.trace("Enter getOneNSSIInfo in DoAllocateNSIandNSSI()")
+
+ //ServiceDecomposition serviceDecompositionObj = execution.getVariable("serviceDecompositionObj")
+ Map<String, Object> nssiMap=execution.getVariable("nssiMap")
+ List<String> nsstSequence = execution.getVariable("nsstSequence")
+ String currentNSST= nsstSequence.get(execution.getVariable("currentNssiIndex"))
+ boolean isNSSIOptionAvailable = false
+ String nsstInput=nssiMap.get(currentNSST)
+ execution.setVariable("nsstInput",nsstInput)
+ String modelUuid = jsonUtil.getJsonValue(nsstInput, "modelUuid")
+ String nssiInstanceId = jsonUtil.getJsonValue(nsstInput, "serviceInstanceId")
+ String nssiserviceModelInfo = """{
+ "modelInvariantUuid":"",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ Integer currentIndex = execution.getVariable("currentNssiIndex")
+ currentIndex=currentIndex+1;
+ execution.setVariable("currentNssiIndex",currentIndex)
+ execution.setVariable("nssiserviceModelInfo",nssiserviceModelInfo)
+ execution.setVariable("nssiInstanceId",nssiInstanceId)
+ logger.trace("Exit getOneNSSIInfo in DoAllocateNSIandNSSI()")
+ }
+
+ void updateCurrentIndex(DelegateExecution execution){
+
+ logger.trace("Enter updateCurrentIndex in DoAllocateNSIandNSSI()")
+ Integer currentIndex = execution.getVariable("currentNssiIndex")
+ Integer maxIndex = execution.getVariable("maxIndex")
+ if(currentIndex>=maxIndex)
+ {
+ Boolean isMoreNSSI=false
+ execution.setVariable("isMoreNSSI",isMoreNSSI)
+ }
+ logger.trace("Exit updateCurrentIndex in DoAllocateNSIandNSSI()")
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSSI.groovy
new file mode 100644
index 0000000000..d786cb0ba1
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSSI.groovy
@@ -0,0 +1,771 @@
+package org.onap.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aai.domain.yang.SliceProfile
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.beans.nsmf.AllocateAnNssi
+import org.onap.so.beans.nsmf.AllocateCnNssi
+import org.onap.so.beans.nsmf.AllocateTnNssi
+import org.onap.so.beans.nsmf.AnSliceProfile
+import org.onap.so.beans.nsmf.CnSliceProfile
+import org.onap.so.beans.nsmf.EsrInfo
+import org.onap.so.beans.nsmf.JobStatusRequest
+import org.onap.so.beans.nsmf.NetworkType
+import org.onap.so.beans.nsmf.NsiInfo
+import org.onap.so.beans.nsmf.NssiAllocateRequest
+import org.onap.so.beans.nsmf.PerfReq
+import org.onap.so.beans.nsmf.PerfReqEmbbList
+import org.onap.so.beans.nsmf.PerfReqUrllcList
+import org.onap.so.beans.nsmf.ResourceSharingLevel
+import org.onap.so.beans.nsmf.ServiceProfile
+import org.onap.so.beans.nsmf.SliceTaskParams
+import org.onap.so.beans.nsmf.TnSliceProfile
+import org.onap.so.beans.nsmf.UeMobilityLevel
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.core.RollbackData
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.domain.ModelInfo
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.AAIResourcesClient
+import org.onap.so.client.aai.entities.AAIEdgeLabel
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import com.fasterxml.jackson.databind.ObjectMapper;
+import javax.ws.rs.core.Response
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+
+class DoAllocateNSSI extends org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor{
+
+ private static final Logger logger = LoggerFactory.getLogger( DoAllocateNSSI.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ JsonUtils jsonUtil = new JsonUtils()
+
+ /**
+ * Pre Process the BPMN Flow Request
+ * Inclouds:
+ * generate the nsOperationKey
+ * generate the nsParameters
+ */
+ void preProcessRequest (DelegateExecution execution) {
+ logger.trace("Enter preProcessRequest()")
+ String msg = ""
+ String nssmfOperation = ""
+ String msoRequestId = execution.getVariable("msoRequestId")
+ String nsstInput = execution.getVariable("nsstInput")
+ String modelUuid = jsonUtil.getJsonValue(nsstInput, "modelUuid")
+ //modelUuid="2763777c-27bd-4df7-93b8-c690e23f4d3f"
+ String nssiInstanceId = jsonUtil.getJsonValue(nsstInput, "serviceInstanceId")
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo",serviceModelInfo)
+ execution.setVariable("nssiInstanceId",nssiInstanceId)
+ String nssiProfileID = UUID.randomUUID().toString()
+ execution.setVariable("nssiProfileID",nssiProfileID)
+ if(isBlank(nssiInstanceId))
+ {
+ nssmfOperation="create"
+ nssiInstanceId = UUID.randomUUID().toString()
+ }else {
+ nssmfOperation = "update"
+ }
+ execution.setVariable("nssmfOperation",nssmfOperation)
+ execution.setVariable("nssiInstanceId",nssiInstanceId)
+
+ def isDebugLogEnabled ="false"
+ def isNSSICreated = false
+ execution.setVariable("isNSSICreated",isNSSICreated)
+
+ int currentCycle = 0
+ execution.setVariable("currentCycle", currentCycle)
+
+ logger.trace("Exit preProcessRequest")
+ }
+
+
+ void getNSSTInfo(DelegateExecution execution){
+ logger.trace("Enter getNSSTInfo in DoAllocateNSSI()")
+ ServiceDecomposition serviceDecomposition= execution.getVariable("serviceDecomposition")
+ ModelInfo modelInfo = serviceDecomposition.getModelInfo()
+ String serviceRole = "nssi"
+ String nssiServiceInvariantUuid = serviceDecomposition.modelInfo.getModelInvariantUuid()
+ String nssiServiceUuid = serviceDecomposition.modelInfo.getModelUuid()
+ String nssiServiceType = serviceDecomposition.getServiceType()
+ String uuiRequest = execution.getVariable("uuiRequest")
+ String nssiServiceName = "nssi_"+jsonUtil.getJsonValue(uuiRequest, "service.name")
+ execution.setVariable("nssiServiceName",nssiServiceName)
+ execution.setVariable("nssiServiceType",nssiServiceType)
+ execution.setVariable("nssiServiceInvariantUuid",nssiServiceInvariantUuid)
+ execution.setVariable("nssiServiceUuid",nssiServiceUuid)
+ execution.setVariable("serviceRole",serviceRole)
+
+ String content = serviceDecomposition.getServiceInfo().getServiceArtifact().get(0).getContent()
+ String nsstID = jsonUtil.getJsonValue(content, "metadata.id")
+ String nsstVendor = jsonUtil.getJsonValue(content, "metadata.vendor")
+ String nsstDomain = jsonUtil.getJsonValue(content, "metadata.domainType")
+ String nsstType = jsonUtil.getJsonValue(content, "metadata.type")
+
+ execution.setVariable("nsstID",nsstID)
+ execution.setVariable("nsstVendor",nsstVendor)
+ execution.setVariable("nsstDomain",nsstDomain)
+ execution.setVariable("nssiServiceUuid",nssiServiceUuid)
+ execution.setVariable("nsstType",nsstType)
+
+ String nsstContentInfo = """{
+ "NsstID":"${nsstID}",
+ "Vendor":"${nsstVendor}",
+ "type":"${nsstType}"
+ }"""
+
+ logger.trace("Exit getNSSTInfo in DoAllocateNSSI()")
+ }
+
+ void timeDelay(DelegateExecution execution) {
+ logger.trace("Enter timeDelay in DoAllocateNSSI()")
+ try {
+ Thread.sleep(60000);
+ int currentCycle = execution.getVariable("currentCycle")
+ currentCycle=currentCycle+1
+ if(currentCycle>60)
+ {
+ logger.trace("Completed all the retry times... but still nssmf havent completed the creation process...")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "NSSMF creation didnt complete by time...")
+ }
+ execution.setVariable("currentCycle",currentCycle)
+ } catch(InterruptedException e) {
+ logger.info("Time Delay exception" + e)
+ }
+ logger.trace("Exit timeDelay in DoAllocateNSSI()")
+ }
+
+
+ void sendUpdateRequestNSSMF(DelegateExecution execution) {
+ logger.trace("Enter sendUpdateRequestNSSMF in DoAllocateNSSI()")
+ String urlString = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
+ logger.debug( "get NSSMF: " + urlString)
+
+ //Prepare auth for NSSMF - Begin
+ def authHeader = ""
+ String basicAuth = UrnPropertiesReader.getVariable("mso.nssmf.auth", execution)
+ String domain = execution.getVariable("nsstDomain")
+ String nssmfRequest = buildUpdateNSSMFRequest(execution, domain.toUpperCase())
+
+ //send request to update NSSI option - Begin
+ URL url = new URL(urlString+"/api/rest/provMns/v1/NSS/SliceProfiles")
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
+ Response httpResponse = httpClient.post(nssmfRequest)
+
+ int responseCode = httpResponse.getStatus()
+ logger.debug("NSSMF sync response code is: " + responseCode)
+
+ if(responseCode < 199 && responseCode > 299){
+ String nssmfResponse ="NSSMF response have nobody"
+ if(httpResponse.hasEntity())
+ nssmfResponse = httpResponse.readEntity(String.class)
+ logger.trace("received error message from NSSMF : "+nssmfResponse)
+ logger.trace("Exit sendCreateRequestNSSMF in DoAllocateNSSI()")
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from NSSMF.")
+ }
+
+ if(httpResponse.hasEntity()){
+ String nssmfResponse = httpResponse.readEntity(String.class)
+ execution.setVariable("nssmfResponse", nssmfResponse)
+ String nssiId = jsonUtil.getJsonValue(nssmfResponse, "nssiId")
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("nssiId",nssiId)
+ execution.setVariable("jobId",jobId)
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from NSSMF.")
+ }
+ logger.trace("Exit sendUpdateRequestNSSMF in DoAllocateNSSI()")
+ }
+
+ void sendCreateRequestNSSMF(DelegateExecution execution) {
+ logger.trace("Enter sendCreateRequestNSSMF in DoAllocateNSSI()")
+ String urlString = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
+ logger.debug( "get NSSMF: " + urlString)
+
+ //Prepare auth for NSSMF - Begin
+ String domain = execution.getVariable("nsstDomain")
+ String nssmfRequest = buildCreateNSSMFRequest(execution, domain.toUpperCase())
+
+ //send request to get NSI option - Begin
+ URL url = new URL(urlString+"/api/rest/provMns/v1/NSS/SliceProfiles")
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
+ Response httpResponse = httpClient.post(nssmfRequest)
+
+ int responseCode = httpResponse.getStatus()
+ logger.debug("NSSMF sync response code is: " + responseCode)
+
+ if(responseCode < 199 || responseCode > 299 ){
+ String nssmfResponse ="NSSMF response have nobody"
+ if(httpResponse.hasEntity())
+ nssmfResponse = httpResponse.readEntity(String.class)
+ logger.trace("received error message from NSSMF : "+nssmfResponse)
+ logger.trace("Exit sendCreateRequestNSSMF in DoAllocateNSSI()")
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from NSSMF.")
+ }
+
+ if(httpResponse.hasEntity()){
+ String nssmfResponse = httpResponse.readEntity(String.class)
+ execution.setVariable("nssmfResponse", nssmfResponse)
+ String nssiId = jsonUtil.getJsonValue(nssmfResponse, "nssiId")
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("nssiId",nssiId)
+ execution.setVariable("jobId",jobId)
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from NSSMF.")
+ }
+ logger.trace("Exit sendCreateRequestNSSMF in DoAllocateNSSI()")
+
+ }
+
+ void getNSSMFProgresss(DelegateExecution execution) {
+ logger.trace("Enter getNSSMFProgresss in DoAllocateNSSI()")
+
+ String endpoint = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
+ logger.debug( "get NSSMF: " + endpoint)
+
+ //Prepare auth for NSSMF - Begin
+ def authHeader = ""
+ String basicAuth = UrnPropertiesReader.getVariable("mso.nssmf.auth", execution)
+
+ String nssmfRequest = buildNSSMFProgressRequest(execution)
+ String strUrl="/api/rest/provMns/v1/NSS/jobs/"+execution.getVariable("jobId")
+ //send request to update NSSI option - Begin
+ URL url = new URL(endpoint+strUrl)
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
+ Response httpResponse = httpClient.post(nssmfRequest)
+
+ int responseCode = httpResponse.getStatus()
+ logger.debug("NSSMF sync response code is: " + responseCode)
+
+ if(responseCode < 199 || responseCode > 299){
+ String nssmfResponse ="NSSMF response have nobody"
+ if(httpResponse.hasEntity())
+ nssmfResponse = httpResponse.readEntity(String.class)
+ logger.trace("received error message from NSSMF : "+nssmfResponse)
+ logger.trace("Exit sendCreateRequestNSSMF in DoAllocateNSSI()")
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from NSSMF.")
+ }
+
+ if(httpResponse.hasEntity()){
+ String nssmfResponse = httpResponse.readEntity(String.class)
+ Boolean isNSSICreated = false
+ execution.setVariable("nssmfResponse", nssmfResponse)
+ Integer progress = java.lang.Integer.parseInt(jsonUtil.getJsonValue(nssmfResponse, "responseDescriptor.progress"))
+ String status = jsonUtil.getJsonValue(nssmfResponse, "responseDescriptor.status")
+ String statusDescription = jsonUtil.getJsonValue(nssmfResponse, "responseDescriptor.statusDescription")
+ execution.setVariable("nssmfProgress",progress)
+ execution.setVariable("nssmfStatus",status)
+ execution.setVariable("nddmfStatusDescription",statusDescription)
+ if(progress>99)
+ isNSSICreated = true
+ execution.setVariable("isNSSICreated",isNSSICreated)
+
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from NSSMF.")
+ }
+ logger.trace("Exit getNSSMFProgresss in DoAllocateNSSI()")
+
+ }
+
+ void updateRelationship(DelegateExecution execution) {
+ logger.trace("Enter updateRelationship in DoAllocateNSSI()")
+ String nssiInstanceId = execution.getVariable("nssiInstanceId")
+ String nsiInstanceId = execution.getVariable("nsiServiceInstanceId")
+ try{
+ AAIResourceUri nsiServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nsiInstanceId);
+ AAIResourceUri nssiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiInstanceId)
+ getAAIClient().connect(nsiServiceuri, nssiServiceUri, AAIEdgeLabel.COMPOSED_OF);
+ }catch(Exception ex) {
+ String msg = "Exception in DoAllocateNSSI InstantiateNSSI service while creating relationship " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.trace("Exit updateRelationship in DoAllocateNSSI()")
+ }
+
+
+ void instantiateNSSIService(DelegateExecution execution) {
+ logger.trace("Enter instantiateNSSIService in DoAllocateNSSI()")
+ //String nssiInstanceId = execution.getVariable("nssiInstanceId")
+ String nssiInstanceId = execution.getVariable("nssiId")
+ execution.setVariable("nssiInstanceId",nssiInstanceId)
+ String sliceInstanceId = execution.getVariable("nsiServiceInstanceId")
+ try {
+ org.onap.aai.domain.yang.ServiceInstance nssi = new ServiceInstance();
+ Map<String, Object> serviceProfileMap = execution.getVariable("serviceProfile")
+
+ nssi.setServiceInstanceId(nssiInstanceId)
+ nssi.setServiceInstanceName(execution.getVariable("nssiServiceName"))
+ //nssi.setServiceType(execution.getVariable("nssiServiceType"))
+ nssi.setServiceType(serviceProfileMap.get("sST").toString())
+ String serviceStatus = "deactivated"
+ nssi.setOrchestrationStatus(serviceStatus)
+ String modelInvariantUuid = execution.getVariable("nssiServiceInvariantUuid")
+ String modelUuid = execution.getVariable("nssiServiceUuid")
+ nssi.setModelInvariantId(modelInvariantUuid)
+ nssi.setModelVersionId(modelUuid)
+ String uuiRequest = execution.getVariable("uuiRequest")
+ String serviceInstanceLocationid = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.plmnIdList")
+ nssi.setServiceInstanceLocationId(serviceInstanceLocationid)
+ //String snssai = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.sNSSAI")
+ String envContext=execution.getVariable("nsstDomain")
+ nssi.setEnvironmentContext(envContext)
+ nssi.setServiceRole(execution.getVariable("serviceRole"))
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), nssiInstanceId)
+ client.create(uri, nssi)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ try{
+ AAIResourceUri nsiServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, sliceInstanceId);
+ AAIResourceUri nssiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiInstanceId)
+ getAAIClient().connect(nsiServiceuri, nssiServiceUri, AAIEdgeLabel.COMPOSED_OF);
+ }catch(Exception ex) {
+ String msg = "Exception in DoAllocateNSSI InstantiateNSSI service while creating relationship " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+
+
+ def rollbackData = execution.getVariable("RollbackData")
+ if (rollbackData == null) {
+ rollbackData = new RollbackData();
+ }
+ //rollbackData.put("SERVICEINSTANCE", "disableRollback", idisableRollback.toStrng())
+ rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true")
+ rollbackData.put("SERVICEINSTANCE", "serviceInstanceId", nssiInstanceId)
+ rollbackData.put("SERVICEINSTANCE", "subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
+ rollbackData.put("SERVICEINSTANCE", "globalSubscriberId", execution.getVariable("globalSubscriberId"))
+ execution.setVariable("rollbackData", rollbackData)
+ execution.setVariable("RollbackData", rollbackData)
+ logger.debug("RollbackData:" + rollbackData)
+ logger.trace("Exit instantiateNSSIService in DoAllocateNSSI()")
+ }
+
+
+ void createSliceProfile(DelegateExecution execution) {
+ logger.trace("Enter createSliceProfile in DoAllocateNSSI()")
+ String sliceserviceInstanceId = execution.getVariable("nssiInstanceId")
+ String nssiProfileID = execution.getVariable("nssiProfileID")
+ Map<String, Object> sliceProfileMap = execution.getVariable("sliceProfileCn")
+ Map<String, Object> serviceProfileMap = execution.getVariable("serviceProfile")
+ SliceProfile sliceProfile = new SliceProfile()
+ sliceProfile.setServiceAreaDimension("")
+ sliceProfile.setPayloadSize(0)
+ sliceProfile.setJitter(0)
+ sliceProfile.setSurvivalTime(0)
+ //sliceProfile.setCsAvailability()
+ //sliceProfile.setReliability()
+ sliceProfile.setExpDataRate(0)
+ sliceProfile.setTrafficDensity(0)
+ sliceProfile.setConnDensity(0)
+ sliceProfile.setExpDataRateUL(Integer.parseInt(sliceProfileMap.get("expDataRateUL").toString()))
+ sliceProfile.setExpDataRateDL(Integer.parseInt(sliceProfileMap.get("expDataRateDL").toString()))
+ sliceProfile.setActivityFactor(Integer.parseInt(sliceProfileMap.get("activityFactor").toString()))
+ sliceProfile.setResourceSharingLevel(sliceProfileMap.get("activityFactor").toString())
+ sliceProfile.setUeMobilityLevel(serviceProfileMap.get("uEMobilityLevel").toString())
+ sliceProfile.setCoverageAreaTAList(serviceProfileMap.get("coverageAreaTAList").toString())
+ sliceProfile.setMaxNumberOfUEs(Integer.parseInt(sliceProfileMap.get("activityFactor").toString()))
+ sliceProfile.setLatency(Integer.parseInt(sliceProfileMap.get("latency").toString()))
+ sliceProfile.setProfileId(nssiProfileID)
+ sliceProfile.setE2ELatency(0)
+
+ try {
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE,
+ execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), sliceserviceInstanceId, nssiProfileID)
+ client.create(uri, sliceProfile)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ def rollbackData = execution.getVariable("RollbackData")
+ if (rollbackData == null) {
+ rollbackData = new RollbackData();
+ }
+ //rollbackData.put("SERVICEINSTANCE", "disableRollback", disableRollback.toString())
+ rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true")
+ rollbackData.put("SERVICEINSTANCE", "serviceInstanceId", sliceserviceInstanceId)
+ rollbackData.put("SERVICEINSTANCE", "subscriptionServiceType", execution.getVariable("serviceType"))
+ rollbackData.put("SERVICEINSTANCE", "globalSubscriberId", execution.getVariable("globalSubscriberId"))
+ execution.setVariable("rollbackData", rollbackData)
+ execution.setVariable("RollbackData", rollbackData)
+ logger.debug("RollbackData:" + rollbackData)
+ logger.trace("Exit createSliceProfile in DoAllocateNSSI()")
+ }
+
+
+ String buildCreateNSSMFRequest(DelegateExecution execution, String domain) {
+
+ NssiAllocateRequest request = new NssiAllocateRequest()
+ String strRequest = ""
+ //String uuiRequest = execution.getVariable("uuiRequest")
+ SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
+
+ switch (domain) {
+ case "AN":
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType(execution.getVariable("networkType"))
+ esrInfo.setVendor(execution.getVariable("nsstVendor"))
+
+ NsiInfo nsiInfo = new NsiInfo()
+ nsiInfo.setNsiId(execution.getVariable("nsiInstanceID"))
+ nsiInfo.setNsiName(execution.getVariable("nsiInstanceName"))
+
+ AnSliceProfile anSliceProfile = new AnSliceProfile()
+ anSliceProfile.setLatency(execution.getVariable("latency"))
+ anSliceProfile.setCoverageAreaTAList(execution.getVariable("coverageAreaList"))
+ anSliceProfile.setQi(execution.getVariable("qi"))
+
+ AllocateAnNssi allocateAnNssi = new AllocateAnNssi()
+ allocateAnNssi.setNsstId(execution.getVariable("nsstId"))
+ allocateAnNssi.setNssiName(execution.getVariable("nssiName"))
+ allocateAnNssi.setNsiInfo(nsiInfo)
+ allocateAnNssi.setSliceProfile(anSliceProfile)
+ String anScriptName = sliceTaskParams.getAnScriptName()
+ allocateAnNssi.setScriptName(anScriptName)
+
+ request.setAllocateAnNssi(allocateAnNssi)
+ request.setEsrInfo(esrInfo)
+ break;
+ case "CN":
+ Map<String, Object> sliceProfileCn =execution.getVariable("sliceProfileCn")
+ Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
+ NsiInfo nsiInfo = new NsiInfo()
+ nsiInfo.setNsiId(execution.getVariable("nsiServiceInstanceId"))
+ nsiInfo.setNsiName(execution.getVariable("nsiServiceInstanceName"))
+
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType(NetworkType.fromString(domain))
+ esrInfo.setVendor(execution.getVariable("nsstVendor"))
+ execution.setVariable("esrInfo",esrInfo)
+
+
+ PerfReqEmbbList perfReqEmbb = new PerfReqEmbbList()
+ perfReqEmbb.setActivityFactor(sliceProfileCn.get("activityFactor"))
+ perfReqEmbb.setAreaTrafficCapDL(sliceProfileCn.get("areaTrafficCapDL"))
+ perfReqEmbb.setAreaTrafficCapUL(sliceProfileCn.get("areaTrafficCapUL"))
+ perfReqEmbb.setExpDataRateDL(sliceProfileCn.get("expDataRateDL"))
+ perfReqEmbb.setExpDataRateUL(sliceProfileCn.get("expDataRateUL"))
+
+ List<PerfReqEmbbList> listPerfReqEmbbList = new ArrayList<>()
+ listPerfReqEmbbList.add(perfReqEmbb)
+
+ PerfReq perfReq = new PerfReq()
+ perfReq.setPerfReqEmbbList(listPerfReqEmbbList)
+
+ PerfReqUrllcList perfReqUrllc = new PerfReqUrllcList()
+ perfReqUrllc.setConnDensity(0)
+ perfReqUrllc.setTrafficDensity(0)
+ perfReqUrllc.setExpDataRate(0)
+ perfReqUrllc.setReliability(0)
+ perfReqUrllc.setCsAvailability(0)
+ perfReqUrllc.setSurvivalTime(0)
+ perfReqUrllc.setJitter(0)
+ perfReqUrllc.setE2eLatency(0)
+ perfReqUrllc.setPayloadSize("0")
+ perfReqUrllc.setServiceAreaDimension("")
+
+ List<PerfReqUrllcList> perfReqUrllcList = new ArrayList<>()
+ perfReqUrllcList.add(perfReqUrllc)
+ perfReq.setPerfReqUrllcList(perfReqUrllcList)
+
+ CnSliceProfile cnSliceProfile = new CnSliceProfile()
+ cnSliceProfile.setSliceProfileId(execution.getVariable("nssiProfileID"))
+ String plmnStr = serviceProfile.get("plmnIdList")
+ List<String> plmnIdList=Arrays.asList(plmnStr.split("\\|"))
+ cnSliceProfile.setPlmnIdList(plmnIdList)
+
+ String resourceSharingLevel = serviceProfile.get("resourceSharingLevel").toString()
+ cnSliceProfile.setResourceSharingLevel(ResourceSharingLevel.fromString(resourceSharingLevel))
+
+ String coverageArea = serviceProfile.get("coverageAreaTAList")
+ List<String> coverageAreaList=Arrays.asList(coverageArea.split("\\|"))
+ cnSliceProfile.setCoverageAreaTAList(coverageAreaList)
+
+ String ueMobilityLevel = serviceProfile.get("uEMobilityLevel").toString()
+ cnSliceProfile.setUeMobilityLevel(UeMobilityLevel.fromString(ueMobilityLevel))
+
+ int latency = serviceProfile.get("latency")
+ cnSliceProfile.setLatency(latency)
+
+ int maxUE = serviceProfile.get("maxNumberofUEs")
+ cnSliceProfile.setMaxNumberofUEs(maxUE)
+
+ String snssai = serviceProfile.get("sNSSAI")
+ List<String> snssaiList = Arrays.asList(snssai.split("\\|"))
+ cnSliceProfile.setSnssaiList(snssaiList)
+
+ cnSliceProfile.setPerfReq(perfReq)
+
+ AllocateCnNssi allocateCnNssi = new AllocateCnNssi()
+ allocateCnNssi.setNsstId(execution.getVariable("nsstid"))
+ allocateCnNssi.setNssiName(execution.getVariable("nssiName"))
+ allocateCnNssi.setSliceProfile(cnSliceProfile)
+ allocateCnNssi.setNsiInfo(nsiInfo)
+ String cnScriptName = sliceTaskParams.getCnScriptName()
+ allocateCnNssi.setScriptName(cnScriptName)
+ request.setAllocateCnNssi(allocateCnNssi)
+ request.setEsrInfo(esrInfo)
+ break;
+ case "TN":
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType(execution.getVariable("networkType"))
+ esrInfo.setVendor(execution.getVariable("vendor"))
+
+ TnSliceProfile tnSliceProfile = new TnSliceProfile()
+ tnSliceProfile.setLatency(execution.getVariable("latency"))
+ tnSliceProfile.setBandwidth(execution.getVariable("bandWidth"))
+
+ NsiInfo nsiInfo = new NsiInfo()
+ nsiInfo.setNsiId(execution.getVariable("nsiInstanceID"))
+ nsiInfo.setNsiName(execution.getVariable("nsiInstanceName"))
+
+ AllocateTnNssi allocateTnNssi = new AllocateTnNssi()
+ allocateTnNssi.setSliceProfile(tnSliceProfile)
+ allocateTnNssi.setNsiInfo(nsiInfo)
+ allocateTnNssi.setNsstId(execution.getVariable("nsstid"))
+ String tnScriptName = sliceTaskParams.getTnScriptName()
+ allocateTnNssi.setScriptName(tnScriptName)
+
+ request.setAllocateTnNssi(allocateTnNssi)
+ request.setEsrInfo(esrInfo)
+ break;
+ default:
+ break;
+ }
+ try {
+ strRequest = MAPPER.writeValueAsString(request);
+ } catch (IOException e) {
+ logger.error("Invalid get progress request bean to convert as string");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Invalid get progress request bean to convert as string")
+ }
+ return strRequest
+ }
+
+
+ String buildUpdateNSSMFRequest(DelegateExecution execution, String domain) {
+ NssiAllocateRequest request = new NssiAllocateRequest()
+ String nsstInput = execution.getVariable("nsstInput")
+ String nssiId = jsonUtil.getJsonValue(nsstInput, "serviceInstanceId")
+ String strRequest = ""
+ SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
+ switch (domain) {
+ case "AN":
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType(execution.getVariable("nsstType"))
+ esrInfo.setVendor(execution.getVariable("vendor"))
+
+ NsiInfo nsiInfo = new NsiInfo()
+ nsiInfo.setNsiId(execution.getVariable("nsiInstanceID"))
+ nsiInfo.setNsiName(execution.getVariable("nsiInstanceName"))
+
+ AnSliceProfile anSliceProfile = new AnSliceProfile()
+ anSliceProfile.setLatency(execution.getVariable("latency"))
+ anSliceProfile.setCoverageAreaTAList(execution.getVariable("coverageAreaList"))
+ anSliceProfile.setQi(execution.getVariable("qi"))
+
+ AllocateAnNssi allocateAnNssi = new AllocateAnNssi()
+ allocateAnNssi.setNsstId(execution.getVariable("nsstId"))
+ allocateAnNssi.setNssiName(execution.getVariable("nssiName"))
+ allocateAnNssi.setNsiInfo(nsiInfo)
+ allocateAnNssi.setSliceProfile(anSliceProfile)
+ String anScriptName = sliceTaskParams.getAnScriptName()
+ allocateAnNssi.setScriptName(anScriptName)
+ request.setAllocateAnNssi(allocateAnNssi)
+ request.setEsrInfo(esrInfo)
+ break;
+ case "CN":
+ Map<String, Object> sliceProfileCn =execution.getVariable("sliceProfileCn")
+ Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
+ NsiInfo nsiInfo = new NsiInfo()
+ nsiInfo.setNsiId(execution.getVariable("nsiServiceInstanceId"))
+ nsiInfo.setNsiName(execution.getVariable("nsiServiceInstanceName"))
+
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType(NetworkType.fromString(domain))
+ esrInfo.setVendor(execution.getVariable("nsstVendor"))
+ execution.setVariable("esrInfo",esrInfo)
+
+
+ PerfReqEmbbList perfReqEmbb = new PerfReqEmbbList()
+ perfReqEmbb.setActivityFactor(sliceProfileCn.get("activityFactor"))
+ perfReqEmbb.setAreaTrafficCapDL(sliceProfileCn.get("areaTrafficCapDL"))
+ perfReqEmbb.setAreaTrafficCapUL(sliceProfileCn.get("areaTrafficCapUL"))
+ perfReqEmbb.setExpDataRateDL(sliceProfileCn.get("expDataRateDL"))
+ perfReqEmbb.setExpDataRateUL(sliceProfileCn.get("expDataRateUL"))
+
+ List<PerfReqEmbbList> listPerfReqEmbbList = new ArrayList<>()
+ listPerfReqEmbbList.add(perfReqEmbb)
+
+ PerfReq perfReq = new PerfReq()
+ perfReq.setPerfReqEmbbList(listPerfReqEmbbList)
+
+ PerfReqUrllcList perfReqUrllc = new PerfReqUrllcList()
+ perfReqUrllc.setConnDensity(0)
+ perfReqUrllc.setTrafficDensity(0)
+ perfReqUrllc.setExpDataRate(0)
+ perfReqUrllc.setReliability(0)
+ perfReqUrllc.setCsAvailability(0)
+ perfReqUrllc.setSurvivalTime(0)
+ perfReqUrllc.setJitter(0)
+ perfReqUrllc.setE2eLatency(0)
+ perfReqUrllc.setPayloadSize("0")
+ perfReqUrllc.setServiceAreaDimension("")
+
+ List<PerfReqUrllcList> perfReqUrllcList = new ArrayList<>()
+ perfReqUrllcList.add(perfReqUrllc)
+ perfReq.setPerfReqUrllcList(perfReqUrllcList)
+
+ CnSliceProfile cnSliceProfile = new CnSliceProfile()
+ cnSliceProfile.setSliceProfileId(execution.getVariable("nssiProfileID"))
+ String plmnStr = serviceProfile.get("plmnIdList")
+ List<String> plmnIdList=Arrays.asList(plmnStr.split("\\|"))
+ cnSliceProfile.setPlmnIdList(plmnIdList)
+
+ String resourceSharingLevel = serviceProfile.get("resourceSharingLevel").toString()
+ cnSliceProfile.setResourceSharingLevel(ResourceSharingLevel.fromString(resourceSharingLevel))
+
+ String coverageArea = serviceProfile.get("coverageAreaTAList")
+ List<String> coverageAreaList=Arrays.asList(coverageArea.split("\\|"))
+ cnSliceProfile.setCoverageAreaTAList(coverageAreaList)
+
+ String ueMobilityLevel = serviceProfile.get("uEMobilityLevel").toString()
+ cnSliceProfile.setUeMobilityLevel(UeMobilityLevel.fromString(ueMobilityLevel))
+
+ int latency = serviceProfile.get("latency")
+ cnSliceProfile.setLatency(latency)
+
+ int maxUE = serviceProfile.get("maxNumberofUEs")
+ cnSliceProfile.setMaxNumberofUEs(maxUE)
+
+ String snssai = serviceProfile.get("sNSSAI")
+ List<String> snssaiList = Arrays.asList(snssai.split("\\|"))
+ cnSliceProfile.setSnssaiList(snssaiList)
+
+ cnSliceProfile.setPerfReq(perfReq)
+
+ AllocateCnNssi allocateCnNssi = new AllocateCnNssi()
+ allocateCnNssi.setNsstId(execution.getVariable("nsstid"))
+ allocateCnNssi.setNssiName(execution.getVariable("nssiName"))
+ allocateCnNssi.setSliceProfile(cnSliceProfile)
+ allocateCnNssi.setNsiInfo(nsiInfo)
+ allocateCnNssi.setNssiId(nssiId) // need to check this
+ String cnScriptName = sliceTaskParams.getCnScriptName()
+ allocateCnNssi.setScriptName(cnScriptName)
+ request.setAllocateCnNssi(allocateCnNssi)
+ request.setEsrInfo(esrInfo)
+ break;
+ case "TN":
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType(execution.getVariable("networkType"))
+ esrInfo.setVendor(execution.getVariable("vendor"))
+
+ TnSliceProfile tnSliceProfile = new TnSliceProfile()
+ tnSliceProfile.setLatency(execution.getVariable("latency"))
+ tnSliceProfile.setBandwidth(execution.getVariable("bandWidth"))
+
+ NsiInfo nsiInfo = new NsiInfo()
+ nsiInfo.setNsiId(execution.getVariable("nsiInstanceID"))
+ nsiInfo.setNsiName(execution.getVariable("nsiInstanceName"))
+
+ AllocateTnNssi allocateTnNssi = new AllocateTnNssi()
+ allocateTnNssi.setSliceProfile(tnSliceProfile)
+ allocateTnNssi.setNsiInfo(nsiInfo)
+ allocateTnNssi.setNsstId(execution.getVariable("nsstid"))
+ String tnScriptName = sliceTaskParams.getTnScriptName()
+ allocateTnNssi.setScriptName(tnScriptName)
+ request.setAllocateTnNssi(allocateTnNssi)
+ request.setEsrInfo(esrInfo)
+ break;
+ default:
+ break;
+ }
+ try {
+ strRequest = MAPPER.writeValueAsString(request);
+ } catch (IOException e) {
+ logger.error("Invalid get progress request bean to convert as string");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Invalid get progress request bean to convert as string")
+ }
+ return strRequest
+ }
+
+ String buildNSSMFProgressRequest(DelegateExecution execution){
+ JobStatusRequest request = new JobStatusRequest()
+ String strRequest = ""
+ EsrInfo esrInfo = execution.getVariable("esrInfo")
+ request.setNsiId(execution.getVariable("nsiServiceInstanceId"))
+ request.setNssiId(execution.getVariable("nssiId"))
+ request.setEsrInfo(esrInfo)
+
+ try {
+ strRequest = MAPPER.writeValueAsString(request);
+ } catch (IOException e) {
+ logger.error("Invalid get progress request bean to convert as string");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Invalid get progress request bean to convert as string")
+ }
+ return strRequest
+ }
+
+ public void prepareUpdateOrchestrationTask(DelegateExecution execution) {
+ logger.debug("Start prepareUpdateOrchestrationTask progress")
+ String requestMethod = "PUT"
+ String progress = execution.getVariable("nssmfProgress")
+ String status = execution.getVariable("nssmfStatus")
+ String statusDescription=execution.getVariable("nddmfStatusDescription")
+ SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
+ String domain = execution.getVariable("nsstDomain")
+ switch (domain.toUpperCase()) {
+ case "AN":
+ sliceTaskParams.setAnProgress(progress)
+ sliceTaskParams.setAnStatus(status)
+ sliceTaskParams.setAnStatusDescription(statusDescription)
+ break;
+ case "CN":
+ sliceTaskParams.setCnProgress(progress)
+ sliceTaskParams.setCnStatus(status)
+ sliceTaskParams.setCnStatusDescription(statusDescription)
+ break;
+ case "TN":
+ sliceTaskParams.setTnProgress(progress)
+ sliceTaskParams.setTnStatus(status)
+ sliceTaskParams.setTnStatusDescription(statusDescription)
+ break;
+ default:
+ break;
+ }
+ String paramJson = sliceTaskParams.convertToJson()
+ execution.setVariable("CSSOT_paramJson", paramJson)
+ execution.setVariable("CSSOT_requestMethod", requestMethod)
+ logger.debug("Finish prepareUpdateOrchestrationTask progress")
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceInstance.groovy
new file mode 100644
index 0000000000..ae239d9e68
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceInstance.groovy
@@ -0,0 +1,232 @@
+package org.onap.so.bpmn.infrastructure.scripts
+
+
+import org.onap.so.bpmn.core.domain.AllottedResource
+import org.onap.aai.domain.yang.AllottedResource
+
+import static org.apache.commons.lang3.StringUtils.*;
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.OwningEntity
+import org.onap.aai.domain.yang.ServiceProfile;
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.CatalogDbUtils
+import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.MsoUtils
+import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
+import org.onap.so.bpmn.core.RollbackData
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.bpmn.core.domain.ModelInfo
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.domain.ServiceInstance
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.bpmn.infrastructure.aai.groovyflows.AAICreateResources
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.AAIResourcesClient
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+
+
+class DoCreateSliceServiceInstance extends AbstractServiceTaskProcessor{
+
+ private static final Logger logger = LoggerFactory.getLogger( DoCreateSliceServiceInstance.class);
+ JsonUtils jsonUtil = new JsonUtils()
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
+
+ /**
+ * Pre Process the BPMN Flow Request
+ * Inclouds:
+ * generate the nsOperationKey
+ * generate the nsParameters
+ */
+ void preProcessRequest (DelegateExecution execution) {
+ String msg = ""
+ logger.trace("Enter preProcessRequest()")
+ //Need update
+ //1. Prepare service parameter.
+ //2. Prepare slice profile parameters.
+
+ String sliceserviceInstanceId = execution.getVariable("serviceInstanceId")
+ String allottedResourceId = UUID.randomUUID().toString()
+ execution.setVariable("sliceserviceInstanceId", sliceserviceInstanceId)
+ execution.setVariable("allottedResourceId", allottedResourceId)
+
+ String uuiRequest = execution.getVariable("uuiRequest")
+ String modelInvariantUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceInvariantUuid")
+ String modelUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceUuid")
+ //here modelVersion is not set, we use modelUuid to decompose the service.
+ def isDebugLogEnabled = true
+ execution.setVariable("serviceInstanceId",sliceserviceInstanceId)
+ execution.setVariable("isDebugLogEnabled",isDebugLogEnabled)
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+
+ logger.trace("Exit preProcessRequest")
+ }
+
+
+ void createServiceProfile(DelegateExecution execution) {
+
+ String sliceserviceInstanceId = execution.getVariable("sliceserviceInstanceId")
+ Map<String, Object> serviceProfileMap = execution.getVariable("serviceProfile")
+ String serviceProfileID = UUID.randomUUID().toString()
+ ServiceProfile serviceProfile = new ServiceProfile();
+ serviceProfile.setProfileId(serviceProfileID)
+ serviceProfile.setLatency(Integer.parseInt(serviceProfileMap.get("latency").toString()))
+ serviceProfile.setMaxNumberOfUEs(Integer.parseInt(serviceProfileMap.get("maxNumberofUEs").toString()))
+ serviceProfile.setCoverageAreaTAList(serviceProfileMap.get("coverageAreaTAList").toString())
+ serviceProfile.setUeMobilityLevel(serviceProfileMap.get("uEMobilityLevel").toString())
+ serviceProfile.setResourceSharingLevel(serviceProfileMap.get("resourceSharingLevel").toString())
+ serviceProfile.setExpDataRateUL(Integer.parseInt(serviceProfileMap.get("expDataRateUL").toString()))
+ serviceProfile.setExpDataRateDL(Integer.parseInt(serviceProfileMap.get("expDataRateDL").toString()))
+ serviceProfile.setAreaTrafficCapUL(Integer.parseInt(serviceProfileMap.get("areaTrafficCapUL").toString()))
+ serviceProfile.setAreaTrafficCapDL(Integer.parseInt(serviceProfileMap.get("areaTrafficCapDL").toString()))
+ serviceProfile.setActivityFactor(Integer.parseInt(serviceProfileMap.get("activityFactor").toString()))
+
+ serviceProfile.setJitter(0)
+ serviceProfile.setSurvivalTime(0)
+ serviceProfile.setCsAvailability(new Object())
+ serviceProfile.setReliability(new Object())
+ serviceProfile.setExpDataRate(0)
+ serviceProfile.setTrafficDensity(0)
+ serviceProfile.setConnDensity(0)
+ try {
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE, execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"), sliceserviceInstanceId, serviceProfileID)
+ client.create(uri, serviceProfile)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+
+ void instantiateSliceService(DelegateExecution execution) {
+
+ ServiceDecomposition serviceDecomposition= execution.getVariable("sliceServiceDecomposition")
+ String uuiRequest = execution.getVariable("uuiRequest")
+ ModelInfo modelInfo = serviceDecomposition.getModelInfo()
+ String serviceRole = "e2eslice-service"
+ String serviceType = execution.getVariable("serviceType")
+ Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
+ String ssInstanceId = execution.getVariable("serviceInstanceId")
+ try {
+ org.onap.aai.domain.yang.ServiceInstance ss = new org.onap.aai.domain.yang.ServiceInstance()
+ ss.setServiceInstanceId(ssInstanceId)
+ String sliceInstanceName = execution.getVariable("serviceInstanceName")
+ ss.setServiceInstanceName(sliceInstanceName)
+ ss.setServiceType(serviceType)
+ String serviceStatus = "deactivated"
+ ss.setOrchestrationStatus(serviceStatus)
+ String modelInvariantUuid = modelInfo.getModelInvariantUuid()
+ String modelUuid = modelInfo.getModelUuid()
+ ss.setModelInvariantId(modelInvariantUuid)
+ ss.setModelVersionId(modelUuid)
+ String serviceInstanceLocationid = serviceProfile.get("plmnIdList")
+ ss.setServiceInstanceLocationId(serviceInstanceLocationid)
+ String snssai = serviceProfile.get("sNSSAI")
+ ss.setEnvironmentContext(snssai)
+ ss.setServiceRole(serviceRole)
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), ssInstanceId)
+ client.create(uri, ss)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+
+ def rollbackData = execution.getVariable("RollbackData")
+ if (rollbackData == null) {
+ rollbackData = new RollbackData();
+ }
+ //rollbackData.put("SERVICEINSTANCE", "disableRollback", disableRollback.toString())
+ rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true")
+ rollbackData.put("SERVICEINSTANCE", "serviceInstanceId", ssInstanceId)
+ rollbackData.put("SERVICEINSTANCE", "subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
+ rollbackData.put("SERVICEINSTANCE", "globalSubscriberId", execution.getVariable("globalSubscriberId"))
+ execution.setVariable("rollbackData", rollbackData)
+ execution.setVariable("RollbackData", rollbackData)
+ logger.debug("RollbackData:" + rollbackData)
+
+ }
+
+
+ void createAllottedResource(DelegateExecution execution) {
+ String serviceInstanceId = execution.getVariable('sliceserviceInstanceId')
+
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri ssServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)
+
+// try {
+//
+// if(resourceClient.exists(ssServiceuri)){
+// execution.setVariable("ssi_resourceLink", uri.build().toString())
+// }else{
+// exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai to " +
+// "associate allotted resource for service :"+serviceInstanceId)
+// }
+// }catch(BpmnError e) {
+// throw e;
+// }catch (Exception ex){
+// String msg = "Exception in getServiceInstance. " + ex.getMessage()
+// logger.debug(msg)
+// exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+// }
+
+ try {
+ String allottedResourceId = execution.getVariable("allottedResourceId")
+ ServiceDecomposition serviceDecomposition = execution.getVariable("sliceServiceDecomposition")
+ List<org.onap.so.bpmn.core.domain.AllottedResource> allottedResourceList = serviceDecomposition.getAllottedResources()
+ for(org.onap.so.bpmn.core.domain.AllottedResource allottedResource : allottedResourceList)
+ {
+ //AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceFromParentURI(ssServiceuri, AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId)
+ AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE,
+ execution.getVariable("globalSubscriberId"),execution.getVariable("subscriptionServiceType"),
+ execution.getVariable("sliceserviceInstanceId"), allottedResourceId)
+ execution.setVariable("allottedResourceUri", allottedResourceUri)
+ String arType = allottedResource.getAllottedResourceType()
+ String arRole = allottedResource.getAllottedResourceRole()
+ String modelInvariantId = allottedResource.getModelInfo().getModelInvariantUuid()
+ String modelVersionId = allottedResource.getModelInfo().getModelUuid()
+
+ org.onap.aai.domain.yang.AllottedResource resource = new org.onap.aai.domain.yang.AllottedResource()
+ resource.setId(allottedResourceId)
+ resource.setType(arType)
+ resource.setAllottedResourceName("Allotted_"+ execution.getVariable("serviceInstanceName"))
+ resource.setRole(arRole)
+ resource.setModelInvariantId(modelInvariantId)
+ resource.setModelVersionId(modelVersionId)
+ getAAIClient().create(allottedResourceUri, resource)
+ //AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.SERVICE_INSTANCE, UriBuilder.fromPath(ssServiceuri).build())
+ //getAAIClient().connect(allottedResourceUri,ssServiceuri)
+ }
+ //execution.setVariable("aaiARPath", allottedResourceUri.build().toString());
+
+ }catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception in createAaiAR " + ex.getMessage())
+ }
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceOption.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceOption.groovy
new file mode 100644
index 0000000000..c66a89b9c6
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceOption.groovy
@@ -0,0 +1,524 @@
+package org.onap.so.bpmn.infrastructure.scripts
+
+import com.fasterxml.jackson.core.type.TypeReference
+import groovy.json.JsonBuilder
+import groovy.json.JsonSlurper
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.Relationship
+import org.onap.aai.domain.yang.RelationshipList
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.beans.nsmf.SliceTaskParams
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.OofUtils
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.domain.ServiceProxy
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.AAIResourcesClient
+import org.onap.so.client.aai.entities.AAIResultWrapper
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.db.request.client.RequestsDbClient
+import org.onap.so.db.request.beans.OrchestrationTask
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import javax.ws.rs.NotFoundException
+import javax.ws.rs.core.Response
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+public class DoCreateSliceServiceOption extends AbstractServiceTaskProcessor{
+
+ private static final Logger logger = LoggerFactory.getLogger( DoCreateSliceServiceOption.class)
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ JsonUtils jsonUtil = new JsonUtils()
+
+ RequestsDbClient requestsDbClient = new RequestsDbClient()
+
+ OofUtils oofUtils = new OofUtils()
+
+ /**
+ * Pre Process the BPMN Flow Request
+ * Inclouds:
+ * generate the nsOperationKey
+ * generate the nsParameters
+ */
+ void preProcessRequest (DelegateExecution execution) {
+ String msg = ""
+ logger.trace("Enter preProcessRequest()")
+ String taskID = execution.getVariable("taskID")
+ Boolean isSharable = true
+ String resourceSharingLevel = execution.getVariable("resourceSharingLevel")
+ if (resourceSharingLevel.equals("shared"))
+ isSharable = true
+ execution.setVariable("isSharable",isSharable)
+ logger.trace("Exit preProcessRequest")
+
+ }
+
+
+ void getNSIOptionfromOOF(DelegateExecution execution) {
+
+ String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
+ logger.debug( "get NSI option OOF Url: " + urlString)
+ boolean isNSISuggested = true
+ execution.setVariable("isNSISuggested",isNSISuggested)
+ String nsiInstanceId = ""
+ String nsiName = ""
+ SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
+ //Prepare auth for OOF - Begin
+ def authHeader = ""
+ String basicAuth = UrnPropertiesReader.getVariable("mso.oof.auth", execution)
+ String msokey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
+
+ String basicAuthValue = utils.encrypt(basicAuth, msokey)
+ if (basicAuthValue != null) {
+ logger.debug( "Obtained BasicAuth username and password for OOF: " + basicAuthValue)
+ try {
+ authHeader = utils.getBasicAuth(basicAuthValue, msokey)
+ execution.setVariable("BasicAuthHeaderValue", authHeader)
+ } catch (Exception ex) {
+ logger.debug( "Unable to encode username and password string: " + ex)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - Unable to " +
+ "encode username and password string")
+ }
+ } else {
+ logger.debug( "Unable to obtain BasicAuth - BasicAuth value null")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
+ "value null")
+ }
+ //Prepare auth for OOF - End
+
+ String requestId = execution.getVariable("msoRequestId")
+ Map<String, Object> profileInfo = execution.getVariable("serviceProfile")
+ String nstModelUuid = execution.getVariable("nstModelUuid")
+ String nstModelInvariantUuid = execution.getVariable("nstModelInvariantUuid")
+ String nstInfo = """"NSTInfo" : {
+ "invariantUUID":"${nstModelInvariantUuid}",
+ "UUID":"${nstModelUuid}"
+ }"""
+
+ String oofRequest = oofUtils.buildSelectNSIRequest(execution, requestId, nstInfo, profileInfo)
+
+ //send request to get NSI option - Begin
+ URL url = new URL(urlString+"/api/oof/v1/selectnsi")
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.OOF)
+ httpClient.addAdditionalHeader("Authorization", authHeader)
+ Response httpResponse = httpClient.post(oofRequest)
+
+ int responseCode = httpResponse.getStatus()
+ logger.debug("OOF sync response code is: " + responseCode)
+
+ if(responseCode != 200){
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
+ logger.debug("Info: No NSI suggested by OOF" )
+ }
+
+ if(httpResponse.hasEntity()){
+ String OOFResponse = httpResponse.readEntity(String.class)
+ execution.setVariable("OOFResponse", OOFResponse)
+ int index = 0 //This needs to be changed to derive a value when we add policy to decide the solution options.
+ Map OOFResponseObject = new JsonSlurper().parseText(OOFResponse)
+ if(execution.getVariable("isSharable" ) == true && OOFResponseObject.get("solutions").containsKey("sharedNSIsolutions")) {
+ nsiInstanceId = OOFResponseObject.get("solutions").get("sharedNSIsolutions").get(0).get("NSISolution").NSIId
+ nsiName = OOFResponseObject.get("solutions").get("sharedNSIsolutions").get(0).get("NSISolution").NSIName
+ sliceTaskParams.setNstId(nsiInstanceId)
+ sliceTaskParams.setSuggestNsiName(nsiName)
+ execution.setVariable("nsiInstanceId",nsiInstanceId)
+ execution.setVariable("nsiName",nsiName)
+ }else {
+ if(OOFResponseObject.get("solutions").containsKey("newNSISolutions")) {
+ List NSSImap = OOFResponseObject.get("solutions").get("newNSISolutions").get(index).get("NSSISolutions")
+ for(Map nssi : NSSImap) {
+ String nssiName = nssi.get("NSSISolution").NSSIName
+ String nssiId = nssi.get("NSSISolution").NSSIId
+ String domain = nssi.get("NSSISolution").domain.toUpperCase()
+ switch (domain) {
+ case "AN":
+ sliceTaskParams.setAnSuggestNssiId(nssiId)
+ sliceTaskParams.setAnSuggestNssiName(nssiName)
+ break;
+ case "CN":
+ sliceTaskParams.setCnSuggestNssiId(nssiId)
+ sliceTaskParams.setCnSuggestNssiName(nssiName)
+ break;
+ case "TN":
+ sliceTaskParams.setTnSuggestNssiId(nssiId)
+ sliceTaskParams.setTnSuggestNssiName(nssiName)
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ }
+ execution.setVariable("sliceTaskParams", sliceTaskParams)
+ logger.debug("Info: No NSI suggested by OOF" )
+ }
+ //send request to get NSI option - Begin
+
+
+ //send request to get NSI service Info - Begin
+
+ /***
+ * Need to check whether its needed.
+ */
+// logger.debug("Begin to query OOF suggetsed NSI from AAI ")
+// if(isBlank(nsiInstanceId)){
+// isNSISuggested = false
+// execution.setVariable("isNSISuggested",isNSISuggested)
+// }else
+// {
+// try {
+// String globalSubscriberId = execution.getVariable('globalSubscriberId')
+// String serviceType = execution.getVariable('subscriptionServiceType')
+// AAIResourcesClient resourceClient = new AAIResourcesClient()
+// AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nsiInstanceId)
+// AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class)
+// Optional<org.onap.aai.domain.yang.ServiceInstance> si = wrapper.asBean(org.onap.aai.domain.yang.ServiceInstance.class)
+// org.onap.aai.domain.yang.ServiceInstance nsiServiceInstance = si.get()
+// execution.setVariable("nsiServiceInstance",nsiServiceInstance)
+// isNSISuggested = true
+// execution.setVariable("isNSISuggested",isNSISuggested)
+// SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
+// sliceTaskParams.setSuggestNsiId(nsiInstanceId)
+// sliceTaskParams.setSuggestNsiName(si.get().getServiceInstanceName())
+// execution.setVariable("sliceTaskParams", sliceTaskParams)
+// logger.debug("Info: NSI suggested by OOF exist in AAI ")
+// }catch(BpmnError e) {
+// throw e
+// }catch(Exception ex) {
+// String msg = "Internal Error in getServiceInstance: " + ex.getMessage()
+// //exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+// logger.debug("Info: NSI suggested by OOF doesnt exist in AAI " + nsiInstanceId)
+// }
+// }
+ //send request to get NSI service Info - End
+ //${OrchestrationTaskHandler.createOrchestrationTask(execution.getVariable("OrchestrationTask"))}
+ logger.debug( "*** Completed options Call to OOF ***")
+
+ }
+
+
+ public void parseServiceProfile(DelegateExecution execution) {
+ logger.debug("Start parseServiceProfile")
+ String serviceType = execution.getVariable("serviceType")
+ Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
+
+ // set sliceProfile for three domains
+ Map<String, Object> sliceProfileTn = getSliceProfile(serviceType, "TN", serviceProfile)
+ Map<String, Object> sliceProfileCn = getSliceProfile(serviceType, "CN", serviceProfile)
+ Map<String, Object> sliceProfileAn = getSliceProfile(serviceType, "AN", serviceProfile)
+
+ execution.setVariable("sliceProfileTn", sliceProfileTn)
+ execution.setVariable("sliceProfileCn", sliceProfileCn)
+ execution.setVariable("sliceProfileAn", sliceProfileAn)
+ logger.debug("sliceProfileTn: " + sliceProfileTn)
+ logger.debug("sliceProfileCn: " + sliceProfileCn)
+ logger.debug("sliceProfileAn: " + sliceProfileAn)
+
+ logger.debug("Finish parseServiceProfile")
+ }
+
+ public Map getSliceProfile(String serviceType, String domain, Map<String, Object> serviceProfile) {
+ String variablePath = "nsmf." + serviceType + ".profileMap" + domain
+ String profileMapStr = UrnPropertiesReader.getVariable(variablePath)
+ logger.debug("Profile map for " + domain + " : " + profileMapStr)
+ Map<String, String> profileMaps = objectMapper.readValue(profileMapStr, new TypeReference<Map<String, String>>(){})
+ Map<String, Object> sliceProfileTn = [:]
+ for (Map.Entry<String, String> profileMap : profileMaps) {
+ sliceProfileTn.put(profileMap.key, serviceProfile.get(profileMap.value))
+ }
+
+ return sliceProfileTn
+ }
+
+
+ void prepareNSSIList(DelegateExecution execution)
+ {
+ ServiceDecomposition serviceDecomposition= execution.getVariable("serviceDecomposition")
+ List<String> nssiAssociated = new ArrayList<>()
+ Map<String, String> nssimap = new HashMap<>()
+ String nsiInstanceId=execution.getVariable("nsiInstanceId")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("subscriptionServiceType")
+
+ try {
+
+ ServiceInstance si = execution.getVariable("nsiServiceInstance")
+ //List<Relationship> relationships = si.getRelationshipList().getRelationship().stream().filter(relation ->
+ // relation.getRelatedTo().equalsIgnoreCase("service-instance"))
+ RelationshipList relationshipList = si.getRelationshipList()
+ List<Relationship> relationships = relationshipList.getRelationship()
+ for(Relationship relationship in relationships)
+ {
+ if(relationship.getRelatedTo().equalsIgnoreCase("service-instance"))
+ {
+ String NSSIassociated = relationship.getRelatedLink().substring(relationship.getRelatedLink().lastIndexOf("/") + 1);
+ if(!NSSIassociated.equals(nsiInstanceId))
+ nssiAssociated.add(NSSIassociated)
+ }
+ }
+ }catch(BpmnError e) {
+ throw e
+ }catch(Exception ex) {
+ String msg = "Internal Error in getServiceInstance: " + ex.getMessage()
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ Map<String, Object> params = execution.getVariable("params")
+ SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
+ for(String nssiID in nssiAssociated)
+ {
+ try {
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nssiID)
+ AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class)
+ Optional<org.onap.aai.domain.yang.ServiceInstance> si = wrapper.asBean(org.onap.aai.domain.yang.ServiceInstance.class)
+ org.onap.aai.domain.yang.ServiceInstance nssi = si.get()
+
+ String domain = nssi.getEnvironmentContext().toString().toUpperCase()
+ switch (domain) {
+ case "AN":
+ sliceTaskParams.setAnSuggestNssiId(nssi.getServiceInstanceId())
+ sliceTaskParams.setAnSuggestNssiName(nssi.getServiceInstanceName())
+ break;
+ case "CN":
+ sliceTaskParams.setCnSuggestNssiId(nssi.getServiceInstanceId())
+ sliceTaskParams.setCnSuggestNssiName(nssi.getServiceInstanceName())
+ break;
+ case "TN":
+ sliceTaskParams.setTnSuggestNssiId(nssi.getServiceInstanceId())
+ sliceTaskParams.setTnSuggestNssiName(nssi.getServiceInstanceName())
+ break;
+ default:
+ break;
+ }
+ }catch(NotFoundException e)
+ {
+ logger.debug("NSSI Service Instance not found in AAI: " + nssiID)
+ }catch(Exception e)
+ {
+ logger.debug("NSSI Service Instance not found in AAI: " + nssiID)
+ }
+
+ }
+ String nstName = serviceDecomposition.getModelInfo().getModelName()
+ sliceTaskParams.setNstName(nstName)
+ String nstId = serviceDecomposition.getModelInfo().getModelUuid()
+ sliceTaskParams.setNstId(nstId)
+ execution.setVariable("sliceTaskParams",sliceTaskParams)
+
+ }
+
+
+ void updateOptionsInDB(DelegateExecution execution) {
+ logger.debug("Updating options with default value since not sharable : Begin ")
+ String taskID = execution.getVariable("taskID")
+ String params = execution.getVariable("params")
+ logger.debug("Updating options with default value since not sharable : End ")
+
+ }
+
+ void prepareNSTDecompose(DelegateExecution execution) {
+
+ String modelUuid = execution.getVariable("nstModelUuid")
+ String modelInvariantUuid = execution.getVariable("nstModelInvariantUuid")
+
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ }
+
+ void prepareNSSTDecompose(DelegateExecution execution) {
+ Boolean isMoreNSSTtoProcess = false
+ Integer maxNSST = execution.getVariable("maxNSST")
+ Integer currentNSST=execution.getVariable("currentNSST")
+ List<String> nsstModelUUIDList = new ArrayList<>()
+ nsstModelUUIDList = execution.getVariable("nsstModelUUIDList")
+ String modelUuid = nsstModelUUIDList.get(currentNSST)
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ currentNSST=currentNSST+1
+ if(currentNSST<maxNSST)
+ isMoreNSSTtoProcess=true
+ execution.setVariable("isMoreNSSTtoProcess",isMoreNSSTtoProcess)
+ execution.setVariable("maxNSST",maxNSST)
+ execution.setVariable("currentNSST",currentNSST)
+ }
+
+
+ void updateStatusInDB(DelegateExecution execution) {
+
+ String taskID = execution.getVariable("taskID")
+ //OrchestrationTask orchestrationTask = requestsDbClient.getNetworkSliceOption(taskID);
+ //orchestrationTask.setTaskStage("wait to confirm")
+ //requestsDbClient.updateNetworkSliceOption(orchestrationTask)
+ }
+
+ void prepareNSSTlistfromNST(DelegateExecution execution) {
+ //Need to update this part from decomposition.
+ logger.trace("Enter prepareNSSTlistfromNST()")
+ Boolean isMoreNSSTtoProcess = false
+ ServiceDecomposition serviceDecomposition= execution.getVariable("serviceDecomposition")
+ SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
+ String nstName = serviceDecomposition.getModelInfo().getModelName()
+ sliceTaskParams.setNstName(nstName)
+ String nstId = serviceDecomposition.getModelInfo().getModelUuid()
+ sliceTaskParams.setNstId(nstId)
+ execution.setVariable("sliceTaskParams",sliceTaskParams)
+
+ List<ServiceProxy> proxyList = serviceDecomposition.getServiceProxy()
+ List<String> nsstModelUUIDList = new ArrayList<>()
+ for(ServiceProxy serviceProxy:proxyList)
+ nsstModelUUIDList.add(serviceProxy.getSourceModelUuid())
+ execution.setVariable("nsstModelUUIDList",nsstModelUUIDList)
+ Integer maxNSST = nsstModelUUIDList.size()
+ Integer currentNSST=0
+ execution.setVariable("maxNSST",maxNSST)
+ execution.setVariable("currentNSST",currentNSST)
+ if(currentNSST<maxNSST)
+ isMoreNSSTtoProcess=true
+ execution.setVariable("isMoreNSSTtoProcess",isMoreNSSTtoProcess)
+ logger.trace("Exit prepareNSSTlistfromNST()")
+
+ }
+
+
+ void getNSSTOption(DelegateExecution execution) {
+ ServiceDecomposition serviceDecomposition= execution.getVariable("serviceDecomposition")
+ String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("subscriptionServiceType")
+ String nssiInstanceId =""
+ String nssiName =""
+ SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
+ logger.debug( "get NSI option OOF Url: " + urlString)
+ boolean isNSISuggested = false
+ execution.setVariable("isNSISuggested",isNSISuggested)
+
+ //Prepare auth for OOF - Begin
+ def authHeader = ""
+ String basicAuth = UrnPropertiesReader.getVariable("mso.oof.auth", execution)
+ String msokey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
+
+ String basicAuthValue = utils.encrypt(basicAuth, msokey)
+ if (basicAuthValue != null) {
+ logger.debug( "Obtained BasicAuth username and password for OOF: " + basicAuthValue)
+ try {
+ authHeader = utils.getBasicAuth(basicAuthValue, msokey)
+ execution.setVariable("BasicAuthHeaderValue", authHeader)
+ } catch (Exception ex) {
+ logger.debug( "Unable to encode username and password string: " + ex)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - Unable to " +
+ "encode username and password string")
+ }
+ } else {
+ logger.debug( "Unable to obtain BasicAuth - BasicAuth value null")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
+ "value null")
+ }
+ //Prepare auth for OOF - End
+ //Prepare send request to OOF - Begin
+ String requestId = execution.getVariable("msoRequestId")
+ Map<String, Object> profileInfo = execution.getVariable("serviceProfile")
+ String nsstModelInvariantUuid = serviceDecomposition.getModelInfo().getModelInvariantUuid()
+ String nsstModelUuid = serviceDecomposition.getModelInfo().getModelUuid()
+ String nsstInfo = """"NSSTInfo": {
+ "invariantUUID":"${nsstModelInvariantUuid}",
+ "UUID":"${nsstModelUuid}"
+ }"""
+ String oofRequest = oofUtils.buildSelectNSSIRequest(execution, requestId, nsstInfo ,profileInfo)
+
+
+ URL url = new URL(urlString+"/api/oof/v1/selectnssi")
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.OOF)
+ httpClient.addAdditionalHeader("Authorization", authHeader)
+ Response httpResponse = httpClient.post(oofRequest)
+
+ int responseCode = httpResponse.getStatus()
+ logger.debug("OOF sync response code is: " + responseCode)
+
+ if(responseCode != 200){
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
+ }
+
+ if(httpResponse.hasEntity()){
+ String OOFResponse = httpResponse.readEntity(String.class)
+ execution.setVariable("OOFResponse", OOFResponse)
+ nssiInstanceId = jsonUtil.getJsonValue(OOFResponse, "NSSIIInfo.NSSIID")
+ nssiName = jsonUtil.getJsonValue(OOFResponse, "NSSIInfo.NSSIName")
+ execution.setVariable("nssiInstanceId",nssiInstanceId)
+ execution.setVariable("nssiName",nssiName)
+ }
+ if(isBlank(nssiInstanceId)){
+ logger.debug( "There is no valid NSST suggested by OOF.")
+ }else
+ {
+ try {
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nssiInstanceId)
+ AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class)
+ Optional<org.onap.aai.domain.yang.ServiceInstance> si = wrapper.asBean(org.onap.aai.domain.yang.ServiceInstance.class)
+ org.onap.aai.domain.yang.ServiceInstance nssi = si.get()
+
+ String domain = nssi.getEnvironmentContext().toString().toUpperCase()
+ switch (domain) {
+ case "AN":
+ sliceTaskParams.setAnSuggestNssiId(nssi.getServiceInstanceId())
+ sliceTaskParams.setAnSuggestNssiName(nssi.getServiceInstanceName())
+ break;
+ case "CN":
+ sliceTaskParams.setCnSuggestNssiId(nssi.getServiceInstanceId())
+ sliceTaskParams.setCnSuggestNssiName(nssi.getServiceInstanceName())
+ break;
+ case "TN":
+ sliceTaskParams.setTnSuggestNssiId(nssi.getServiceInstanceId())
+ sliceTaskParams.setTnSuggestNssiName(nssi.getServiceInstanceName())
+ break;
+ default:
+ break;
+ }
+ }catch(NotFoundException e)
+ {
+ logger.debug("NSSI Service Instance not found in AAI: " + nssiInstanceId)
+ }catch(Exception e)
+ {
+ logger.debug("NSSI Service Instance not found in AAI: " + nssiInstanceId)
+ }
+ }
+
+
+ //Prepare send request to OOF - End
+
+// String content = serviceDecomposition.getServiceInfo().getServiceArtifact().get(0).getContent()
+// String nsstID = jsonUtil.getJsonValue(content, "metadata.id")
+// String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
+// String domain = jsonUtil.getJsonValue(content, "metadata.domainType")
+// String type = jsonUtil.getJsonValue(content, "metadata.type")
+// String nsstContentInfo = """{
+// "NsstID":"${nsstID}",
+// "Vendor":"${vendor}",
+// "type":"${type}"
+// }"""
+
+ logger.debug("Prepare NSSI option completed ")
+ }
+}
+
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy
index d8897a2468..8d8e97328d 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy
@@ -76,7 +76,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
*
* @param execution
*/
- private void prepareDecomposeService(DelegateExecution execution)
+ void prepareDecomposeService(DelegateExecution execution)
{
LOGGER.trace(" *****${PREFIX} Start prepareDecomposeService *****")
try
@@ -103,7 +103,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
* get vendor Info
* @param execution
*/
- private void processDecomposition(DelegateExecution execution) {
+ void processDecomposition(DelegateExecution execution) {
LOGGER.debug("*****${PREFIX} start processDecomposition *****")
try {
@@ -130,7 +130,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
* send deallocate request to nssmf
* @param execution
*/
- private void sendRequestToNSSMF(DelegateExecution execution)
+ void sendRequestToNSSMF(DelegateExecution execution)
{
LOGGER.debug("*****${PREFIX} start sendRequestToNSSMF *****")
def currentNSSI = execution.getVariable("currentNSSI")
@@ -160,7 +160,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
URL url = new URL(nssmfRequest)
LOGGER.info("deallocate nssmfRequest:${nssmfRequest}, reqBody: ${json}")
- HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
+ HttpClient httpClient = getHttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
Response httpResponse = httpClient.post(json)
checkNssmfResponse(httpResponse, execution)
@@ -176,7 +176,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
* send to nssmf query progress
* @param execution
*/
- private void getJobStatus(DelegateExecution execution)
+ void getJobStatus(DelegateExecution execution)
{
def currentNSSI = execution.getVariable("currentNSSI")
String jobId = currentNSSI['jobId']
@@ -198,7 +198,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
URL url = new URL(nssmfRequest)
LOGGER.info("get deallocate job status, nssmfRequest:${nssmfRequest}, requestBody: ${json}")
- HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
+ HttpClient httpClient = getHttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
Response httpResponse = httpClient.post(json)
checkNssmfResponse(httpResponse, execution)
@@ -248,7 +248,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
* prepare update requestdb
* @param execution
*/
- private void handleJobStatus(DelegateExecution execution)
+ void handleJobStatus(DelegateExecution execution)
{
def currentNSSI = execution.getVariable("currentNSSI")
int currentProgress = currentNSSI["jobProgress"]
@@ -267,7 +267,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
LOGGER.debug("update operation, currentProgress=${currentProgress}, proportion=${proportion}, progress = ${progress}" )
}
- private void timeDelay(DelegateExecution execution) {
+ void timeDelay(DelegateExecution execution) {
try {
Thread.sleep(10000);
} catch(InterruptedException e) {
@@ -279,7 +279,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
* delete slice profile from aai
* @param execution
*/
- private void delSliceProfileFromAAI(DelegateExecution execution)
+ void delSliceProfileFromAAI(DelegateExecution execution)
{
LOGGER.debug("*****${PREFIX} start delSliceProfileFromAAI *****")
def currentNSSI = execution.getVariable("currentNSSI")
@@ -291,12 +291,11 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
try
{
LOGGER.debug("delete nssiServiceInstanceId:${nssiServiceInstanceId}, profileId:${profileId}")
- AAIResourcesClient resourceClient = new AAIResourcesClient()
AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, globalSubscriberId, serviceType, nssiServiceInstanceId, profileId)
- if (!resourceClient.exists(resourceUri)) {
+ if (!getAAIClient().exists(resourceUri)) {
exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
}
- resourceClient.delete(resourceUri)
+ getAAIClient().delete(resourceUri)
}
catch (any)
{
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceService.groovy
index 7c2a2be6ac..76086dab49 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceService.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceService.groovy
@@ -29,7 +29,6 @@ import org.onap.aai.domain.yang.SliceProfiles
import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
import org.onap.so.bpmn.common.scripts.ExceptionUtil
import org.onap.so.client.aai.AAIObjectType
-import org.onap.so.client.aai.AAIResourcesClient
import org.onap.so.client.aai.entities.AAIResultWrapper
import org.onap.so.client.aai.entities.uri.AAIResourceUri
import org.onap.so.client.aai.entities.uri.AAIUriFactory
@@ -309,12 +308,11 @@ class DoDeleteSliceService extends AbstractServiceTaskProcessor {
String globalSubscriberId = execution.getVariable("globalSubscriberId")
String serviceType = execution.getVariable("serviceType")
- AAIResourcesClient resourceClient = new AAIResourcesClient()
AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(aaiObjectType, globalSubscriberId, serviceType, instanceId)
- if (!resourceClient.exists(resourceUri)) {
+ if (!getAAIClient().exists(resourceUri)) {
exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMsg)
}
- AAIResultWrapper wrapper = resourceClient.get(resourceUri, NotFoundException.class)
+ AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
LOGGER.trace(" *****${PREFIX} Exit queryAAI *****")
return wrapper
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoSendCommandToNSSMF.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoSendCommandToNSSMF.groovy
new file mode 100644
index 0000000000..63cd3c72f9
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoSendCommandToNSSMF.groovy
@@ -0,0 +1,463 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., 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.so.bpmn.infrastructure.scripts
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.beans.nsmf.*
+import org.onap.so.bpmn.common.scripts.*
+import org.onap.so.bpmn.common.util.OofInfraUtils
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.bpmn.core.domain.ServiceArtifact
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.logger.ErrorCode
+import org.onap.so.logger.LoggingAnchor
+import org.onap.so.logger.MessageEnum
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import org.springframework.web.util.UriUtils
+
+import javax.ws.rs.core.Response
+import java.lang.reflect.Type
+
+/**
+ * This class supports the DoCreateVnf building block subflow
+ * with the creation of a generic vnf for
+ * infrastructure.
+ *
+ */
+class DoSendCommandToNSSMF extends AbstractServiceTaskProcessor {
+
+ private static final Logger logger = LoggerFactory.getLogger( DoSendCommandToNSSMF.class);
+ String Prefix="DoCNSSMF_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ VidUtils vidUtils = new VidUtils(this)
+ SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
+ OofInfraUtils oofInfraUtils = new OofInfraUtils()
+
+ /**
+ * This method gets and validates the incoming
+ * request.
+ *
+ * @param - execution
+ *
+ */
+ public void preProcessRequest(DelegateExecution execution) {
+
+ execution.setVariable("prefix",Prefix)
+ logger.debug("STARTED Do sendcommandtoNssmf PreProcessRequest Process")
+
+ /*******************/
+ try{
+ // Get Variables
+ String e2eserviceInstanceId = execution.getVariable("e2eserviceInstanceId")
+ String serviceInstanceId = execution.getVariable("e2eserviceInstanceId")
+ execution.setVariable("e2eserviceInstanceId", e2eserviceInstanceId)
+ execution.setVariable("serviceInstanceId", serviceInstanceId)
+ logger.debug("Incoming e2eserviceInstanceId is: " + e2eserviceInstanceId)
+
+ String NSIserviceid = execution.getVariable("NSIserviceid")
+ execution.setVariable("NSIserviceid", NSIserviceid)
+ logger.debug("Incoming NSI id is: " + NSIserviceid)
+
+
+ String nssiMap = execution.getVariable("nssiMap")
+ Type type = new TypeToken<HashMap<String, NSSI>>(){}.getType()
+ Map<String, NSSI> DonssiMap = new Gson().fromJson(nssiMap,type)
+ String strDonssiMap = mapToJsonStr(DonssiMap)
+ execution.setVariable("DonssiMap",strDonssiMap)
+ logger.debug("Incoming DonssiMap is: " + strDonssiMap)
+
+ String requestId = execution.getVariable("msoRequestId")
+ execution.setVariable("msoRequestId", requestId)
+
+ String operationType = execution.getVariable("operationType")
+ execution.setVariable("operationType", operationType)
+ logger.debug("Incoming operationType is: " + operationType)
+
+ if (operationType == "activation") {
+ execution.setVariable("activationSequence","an,tn,cn")
+ }else {
+ execution.setVariable("activationSequence","cn,tn,an")
+ }
+ execution.setVariable("activationIndex",0)
+ execution.setVariable("miniute", "0")
+ execution.setVariable("activateNumberSlice",0)
+
+ logger.info("the end !!")
+ }catch(BpmnError b){
+ logger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ logger.info("the end of catch !!")
+ logger.debug(" Error Occured in DoSendCommandToNSSMF PreProcessRequest method!" + e.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoSendCommandToNSSMF PreProcessRequest")
+
+ }
+ logger.trace("COMPLETED DoSendCommandToNSSMF PreProcessRequest Process")
+ }
+ private String mapToJsonStr(Map<String, NSSI> stringNSSIHashMap) {
+ HashMap<String, NSSI> map = new HashMap<String, NSSI>()
+ for(Map.Entry<String, NSSI> child:stringNSSIHashMap.entrySet())
+ {
+ map.put(child.getKey(), child.getValue())
+ }
+ return new Gson().toJson(map)
+ }
+ public void getNSSIformlist(DelegateExecution execution) {
+
+ String nssiMap = execution.getVariable("DonssiMap")
+ Type type = new TypeToken<HashMap<String, NSSI>>(){}.getType()
+ Map<String, NSSI> DonssiMap = new Gson().fromJson(nssiMap,type)
+ String isNSSIActivate = execution.getVariable("isNSSIActivate")
+
+ String activationSequence01 = execution.getVariable("activationSequence")
+ String[] strlist = activationSequence01.split(",")
+
+ int activationIndex = execution.getVariable("activationIndex")
+ int indexcurrent = 0
+ if (isNSSIActivate == "true")
+ {
+ execution.setVariable("isGetSuccessfull", "false")
+ }else{for (int index = activationIndex; index < 3;index++) {
+ String domaintype01 = strlist[index]
+ if (DonssiMap.containsKey(domaintype01)) {
+ NSSI nssiobject = DonssiMap.get(domaintype01)
+ execution.setVariable("domainType", domaintype01)
+ execution.setVariable("nssiId", nssiobject.getNssiId())
+ execution.setVariable("modelInvariantUuid", nssiobject.getModelInvariantId())
+ execution.setVariable("modelUuid", nssiobject.getModelVersionId())
+ execution.setVariable("isGetSuccessfull", "true")
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelUuid = execution.getVariable("modelUuid")
+ //here modelVersion is not set, we use modelUuid to decompose the service.
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ indexcurrent = index
+ execution.setVariable("activationIndex", indexcurrent)
+ break
+ }else
+ {
+ indexcurrent = index + 1
+
+ }
+ }
+ if ( activationIndex > 2) {
+ execution.setVariable("isGetSuccessfull", "false")
+ }
+ execution.setVariable("activationIndex", indexcurrent)}
+
+ }
+ /**
+ * get vendor Info
+ * @param execution
+ */
+ private void processDecomposition(DelegateExecution execution) {
+ logger.debug("***** processDecomposition *****")
+
+ try {
+ ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") as ServiceDecomposition
+ ServiceArtifact serviceArtifact = serviceDecomposition.getServiceInfo().getServiceArtifact().get(0)
+ String content = serviceArtifact.getContent()
+ String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
+ //String domainType = jsonUtil.getJsonValue(content, "metadata.domainType")
+
+ execution.setVariable("vendor", vendor)
+ // currentNSSI['domainType'] = domainType
+ logger.info("processDecomposition, current vendor-domainType:" + vendor)
+
+ } catch (any) {
+ String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
+ logger.debug(exceptionMessage)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
+ }
+ logger.debug("***** Exit processDecomposition *****")
+ }
+ public void UpdateIndex(DelegateExecution execution) {
+ def activationIndex = execution.getVariable("activationIndex")
+ int activateNumberSlice = execution.getVariable("activateNumberSlice") as Integer
+ def activationCount= execution.getVariable("activationCount")
+ //DecimalFormat df1 = new DecimalFormat("##%")
+ int rate = (activateNumberSlice / activationCount) * 100
+ if (rate == 100)
+ {
+ execution.setVariable("isNSSIActivate","true")
+ }
+ else{
+ execution.setVariable("isNSSIActivate","false")
+ }
+ activationIndex = activationIndex + 1
+ execution.setVariable("activationIndex",activationIndex)
+ logger.trace("the Progress of activation is " + rate.toString() + "%" )
+ try{
+ String serviceId = execution.getVariable("serviceInstanceId")
+ String operationId = UUID.randomUUID().toString()
+ String operationType = execution.getVariable("operationType")
+ String userId = ""
+ String result = (operationType.equals("activation"))? "ACTIVATING": "DEACTIVATING"
+ int progress = rate
+ String reason = ""
+ String operationContent = "Service activation in progress"
+ logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId)
+ serviceId = UriUtils.encode(serviceId,"UTF-8")
+ execution.setVariable("e2eserviceInstanceId", serviceId)
+ execution.setVariable("operationId", operationId)
+ execution.setVariable("operationType", operationType)
+
+ def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint",execution)
+ execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
+ logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
+
+ String payload =
+ """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:ns="http://org.onap.so/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <ns:initServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
+ <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
+ <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
+ <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
+ <userId>${MsoUtils.xmlEscape(userId)}</userId>
+ <result>${MsoUtils.xmlEscape(result)}</result>
+ <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent>
+ <progress>${MsoUtils.xmlEscape(progress)}</progress>
+ <reason>${MsoUtils.xmlEscape(reason)}</reason>
+ </ns:initServiceOperationStatus>
+ </soapenv:Body>
+ </soapenv:Envelope>"""
+
+ payload = utils.formatXml(payload)
+ execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
+ logger.debug("Outgoing CVFMI_updateServiceOperStatusRequest: \n" + payload)
+
+ }catch(Exception e){
+ logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
+ "Exception Occured Processing Activate Slice .", "BPMN",
+ ErrorCode.UnknownError.getValue(), "Exception is:\n" + e)
+ execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during Activate Slice Method:\n" + e.getMessage())
+ }
+ logger.trace("finished Activate Slice")
+ }
+ public void WaitForReturn(DelegateExecution execution) {
+ //logger.debug("Query : "+ Jobid)
+ def miniute=execution.getVariable("miniute")
+ Thread.sleep(10000)
+ int miniute01 = Integer.parseInt(miniute) + 1
+ logger.debug("waiting for : "+ miniute + "miniutes")
+ execution.setVariable("miniute", String.valueOf(miniute01))
+ }
+ public void GetTheStatusOfActivation(DelegateExecution execution) {
+
+ String snssai= execution.getVariable("snssai")
+ String domaintype = execution.getVariable("domainType")
+ String NSIserviceid=execution.getVariable("NSIserviceid")
+ String nssiId = execution.getVariable("nssiId")
+ String Jobid=execution.getVariable("JobId")
+ def miniute=execution.getVariable("miniute")
+ String vendor = execution.getVariable("vendor")
+ String jobstatus ="error"
+
+
+ logger.debug("Query the jobid activation of SNSSAI: "+ Jobid)
+ logger.debug("the domain is : "+ domaintype)
+ logger.debug("the NSSID is : "+nssiId)
+ logger.debug("the NSIserviceid is : "+NSIserviceid)
+
+ JobStatusRequest jobStatusRequest = new JobStatusRequest()
+
+ EsrInfo info = new EsrInfo()
+ info.setNetworkType(NetworkType.fromString(domaintype))
+ info.setVendor(vendor)
+
+ jobStatusRequest.setNsiId(NSIserviceid)
+ jobStatusRequest.setNssiId(nssiId)
+ jobStatusRequest.setEsrInfo(info)
+
+
+ ObjectMapper mapper = new ObjectMapper()
+ String Reqjson = mapper.writeValueAsString(jobStatusRequest)
+ String isActivateSuccessfull=false
+
+ String urlString = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
+ String nssmfRequest = urlString + "/api/rest/provMns/v1/NSS/jobs/" +Jobid
+
+ //send request to active NSSI TN option
+ URL url = new URL(nssmfRequest)
+
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
+ Response httpResponse = httpClient.post(Reqjson)
+
+ int responseCode = httpResponse.getStatus()
+ logger.debug("NSSMF activation response code is: " + responseCode)
+
+ if (responseCode == 404) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad job status Response from NSSMF.")
+ isActivateSuccessfull = false
+ execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
+ jobstatus="error"
+ }else if(responseCode == 200) {
+ if (httpResponse.hasEntity()) {
+ JobStatusResponse jobStatusResponse = httpResponse.readEntity(JobStatusResponse.class)
+ execution.setVariable("statusDescription", jobStatusResponse.getResponseDescriptor().getStatusDescription())
+ jobstatus = jobStatusResponse.getResponseDescriptor().getStatus()
+ switch(jobstatus) {
+ case "started":
+ case "processing":
+ isActivateSuccessfull = "waitting"
+ execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
+ break
+ case "finished":
+ isActivateSuccessfull = "true"
+ execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
+ execution.setVariable("activateNumberSlice",execution.getVariable("activateNumberSlice")+ 1)
+ break
+ case "error":
+ default:
+ isActivateSuccessfull = "false"
+ execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
+
+ }
+ if(Integer.parseInt(miniute) > 6 )
+ {
+ isActivateSuccessfull = "false"
+ execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a timeout job status Response from NSSMF.")
+ }
+ }else
+ {
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad job status Response from NSSMF.")
+ isActivateSuccessfull = false
+ execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
+ }
+ } else {
+ isActivateSuccessfull = false
+ execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad job status Response from NSSMF.")
+ }
+ }
+ public void SendCommandToNssmf(DelegateExecution execution) {
+
+ String snssai= execution.getVariable("snssai")
+ String domaintype = execution.getVariable("domainType")
+ String NSIserviceid=execution.getVariable("NSIserviceid")
+ String nssiId = execution.getVariable("nssiId")
+ String vendor = execution.getVariable("vendor")
+
+
+ logger.debug("the domain is : "+domaintype)
+ logger.debug("SNSSAI: "+snssai +" will be activated")
+ logger.debug("the NSSID is : "+nssiId)
+ logger.debug("the NSIserviceid is : "+NSIserviceid)
+
+ EsrInfo esr = new EsrInfo();
+ esr.setNetworkType(NetworkType.fromString(domaintype))
+ esr.setVendor(vendor)
+
+ ActDeActNssi actNssi = new ActDeActNssi();
+ actNssi.setNsiId(NSIserviceid);
+ actNssi.setNssiId(nssiId);
+ NssiActDeActRequest actRequest = new NssiActDeActRequest();
+ actRequest.setActDeActNssi(actNssi);
+ actRequest.setEsrInfo(esr)
+
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(actRequest);
+
+
+ String urlString = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
+
+ //Prepare auth for NSSMF - Begin
+ def authHeader = ""
+ String basicAuth = UrnPropertiesReader.getVariable("mso.nssmf.auth", execution)
+ String operationType = execution.getVariable("operationType")
+
+ String nssmfRequest = urlString + "/api/rest/provMns/v1/NSS/" + snssai + "/" + operationType
+
+ //send request to active NSSI TN option
+ URL url = new URL(nssmfRequest)
+
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
+ Response httpResponse = httpClient.post(json)
+
+ int responseCode = httpResponse.getStatus()
+ logger.debug("NSSMF activate response code is: " + responseCode)
+ checkNssmfResponse(httpResponse, execution)
+
+ NssiResponse nssmfResponse = httpResponse.readEntity(NssiResponse.class)
+ String jobId = nssmfResponse.getJobId() ?: ""
+ execution.setVariable("JobId", jobId)
+
+ }
+ private void checkNssmfResponse(Response httpResponse, DelegateExecution execution) {
+ int responseCode = httpResponse.getStatus()
+ logger.debug("NSSMF response code is: " + responseCode)
+
+ if ( responseCode < 200 || responseCode > 202 || !httpResponse.hasEntity()) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Response from NSSMF.")
+ String isNSSIActivated = "false"
+ execution.setVariable("isNSSIActivated", isNSSIActivated)
+ execution.setVariable("isNSSIActivate","false")
+ }else{
+ String isNSSIActivated = "true"
+ execution.setVariable("isNSSIActivated", isNSSIActivated)
+ }
+ }
+
+
+ void sendSyncError (DelegateExecution execution) {
+ logger.trace("start sendSyncError")
+ try {
+ String errorMessage = ""
+ if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
+ WorkflowException wfe = execution.getVariable("WorkflowException")
+ errorMessage = wfe.getErrorMessage()
+ } else {
+ errorMessage = "Sending Sync Error."
+ }
+
+ String buildworkflowException =
+ """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
+ <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
+ <aetgt:ErrorCode>7000</aetgt:ErrorCode>
+ </aetgt:WorkflowException>"""
+
+ logger.debug(buildworkflowException)
+ sendWorkflowResponse(execution, 500, buildworkflowException)
+
+ } catch (Exception ex) {
+ logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
+ }
+ logger.trace("finished sendSyncError")
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ExecutionVariableNames.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ExecutionVariableNames.java
index fab3496559..3ea8b190ad 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ExecutionVariableNames.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ExecutionVariableNames.java
@@ -35,8 +35,10 @@ public class ExecutionVariableNames {
public final static String TIMEOUT_FOR_NOTIFICATION = "timeoutForPnfEntryNotification";
public final static String PNF_UUID = "pnfUuid";
public final static String SERVICE_INSTANCE_ID = "serviceInstanceId";
+ public final static String REQUEST_ID = "requestId";
public final static String MSO_REQUEST_ID = "msoRequestId";
public final static String MODEL_UUID = "modelUuid";
+ public final static String REQUEST_PAYLOAD = "requestPayload";
public final static String SERVICE_MODEL_INFO = "serviceModelInfo";
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcher.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcher.java
index 4482d2a327..6c140061c0 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcher.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcher.java
@@ -69,7 +69,7 @@ public class NfSoftwareUpgradeDispatcher implements JavaDelegate {
@Override
public void execute(DelegateExecution delegateExecution) throws Exception {
- logger.debug("Running execute block for activity id:{}, name:{}", delegateExecution.getCurrentActivityId(),
+ logger.debug("Running execute block for activity id: {}, name: {}", delegateExecution.getCurrentActivityId(),
delegateExecution.getCurrentActivityName());
RequestDetails bpmnRequestDetails = requestVerification(delegateExecution);
@@ -82,9 +82,10 @@ public class NfSoftwareUpgradeDispatcher implements JavaDelegate {
final List<PnfResourceCustomization> pnfCustomizations =
getPnfResourceCustomizations(delegateExecution, serviceModelUuid);
final PnfResourceCustomization pnfResourceCustomization = pnfCustomizations.get(0);
+ final String payload = bpmnRequestDetails.getRequestParameters().getPayload();
populateExecution(delegateExecution, bpmnRequestDetails, pnfResourceCustomization, pnf, serviceInstanceName,
- pnfName, serviceModelUuid, userParams);
+ pnfName, serviceModelUuid, userParams, payload);
logger.trace("Completed preProcessRequest PnfSoftwareUpgradeServiceRequest Request ");
}
@@ -104,7 +105,7 @@ public class NfSoftwareUpgradeDispatcher implements JavaDelegate {
private void populateExecution(DelegateExecution delegateExecution, RequestDetails bpmnRequestDetails,
PnfResourceCustomization pnfResourceCustomization, Pnf pnf, String serviceInstanceName, String pnfName,
- String serviceModelUuid, List<Map<String, Object>> userParams) {
+ String serviceModelUuid, List<Map<String, Object>> userParams, String payload) {
delegateExecution.setVariable(SERVICE_MODEL_INFO, bpmnRequestDetails.getModelInfo());
delegateExecution.setVariable(SERVICE_INSTANCE_NAME, serviceInstanceName);
@@ -124,6 +125,8 @@ public class NfSoftwareUpgradeDispatcher implements JavaDelegate {
delegateExecution.setVariable(param.get("name").toString(), param.get("value").toString());
}
}
+
+ delegateExecution.setVariable(REQUEST_PAYLOAD, payload);
}
private Pnf getPnfByPnfName(DelegateExecution delegateExecution, String pnfName) {
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationServiceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationServiceTest.groovy
new file mode 100644
index 0000000000..7e02779f10
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationServiceTest.groovy
@@ -0,0 +1,224 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., 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.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity
+import org.junit.Before
+import org.junit.Test
+import org.mockito.ArgumentCaptor
+import org.mockito.Captor
+import org.mockito.Mockito
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+
+import static org.junit.Assert.assertEquals
+import static org.junit.Assert.assertNotNull
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.times
+import static org.mockito.Mockito.when
+
+class ActivateCommunicationServiceTest extends MsoGroovyTest {
+
+ @Before
+ void init() throws IOException {
+ super.init("ActivateCommunicationService")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest() {
+
+ String req = """
+ {
+ "globalSubscriberId": "5GCustomer",
+ "serviceType": "5G",
+ "operationId": "test123"
+ }
+ """
+ when(mockExecution.getVariable("bpmnRequest")).thenReturn(req)
+ when(mockExecution.getVariable("mso-request-id")).thenReturn("54321")
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345")
+
+
+ ActivateCommunicationService service = new ActivateCommunicationService()
+ service.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(5)).setVariable(captor.capture(), captor.capture())
+ }
+
+ @Test
+ void testPrepareInitOperationStatus() {
+
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345")
+ when(mockExecution.getVariable("operationId")).thenReturn("54321")
+
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("11111")
+
+ ActivateCommunicationService service = new ActivateCommunicationService()
+
+ service.prepareInitOperationStatus(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String res = captor.getValue()
+ assertNotNull(res)
+ }
+
+
+ @Test
+ void testSendSyncResponse() {
+ when(mockExecution.getVariable("operationId")).thenReturn("123456")
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345")
+ ActivateCommunicationService service = new ActivateCommunicationService()
+ service.sendSyncResponse(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sentSyncResponse"), captor.capture())
+ def updateVolumeGroupRequest = captor.getValue()
+ assertEquals(updateVolumeGroupRequest, true)
+ }
+
+ @Test
+ void testPreRequestSend2NSMF() {
+ when(mockExecution.getVariable("e2e_service-instance.service-instance-id")).thenReturn("12333")
+ when(mockExecution.getVariable("requestParam")).thenReturn("activate")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("test111")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5GConsumer")
+ ActivateCommunicationService service = new ActivateCommunicationService()
+ service.preRequestSend2NSMF(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("CSMF_NSMFRequest"), captor.capture())
+ String resultSuccess = captor.getValue()
+
+ String expect = """
+ {
+ "globalSubscriberId":"test111",
+ "serviceType":"5GConsumer"
+ }
+ """
+ assertEquals(expect.replaceAll("\\s+", ""), resultSuccess.replaceAll("\\s+", ""))
+ }
+
+ @Test
+ void testProcessNSMFResponseSuccess() {
+ when(mockExecution.getVariable("CSMF_NSMFResponseCode")).thenReturn(202)
+ when(mockExecution.getVariable("CSMF_NSMFResponse")).thenReturn("""
+ {
+ "operationId": "e3819a23-3777-4172-a834-35ee78acf3f4"
+ }
+ """)
+
+ ActivateCommunicationService service = new ActivateCommunicationService()
+ service.processNSMFResponse(mockExecution)
+ Mockito.verify(mockExecution, times(2)).setVariable(captor.capture(), captor.capture())
+ def resultSuccess = captor.getAllValues()
+
+ def expect = new ArrayList<>()
+ expect.add("e2eOperationId")
+ expect.add("e3819a23-3777-4172-a834-35ee78acf3f4")
+ expect.add("ProcessNsmfSuccess")
+ expect.add("OK")
+ assertEquals(expect, resultSuccess)
+ }
+
+ @Test
+ void testProcessNSMFResponseError() {
+ when(mockExecution.getVariable("CSMF_NSMFResponseCode")).thenReturn(500)
+ ActivateCommunicationService service = new ActivateCommunicationService()
+ service.processNSMFResponse(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("ProcessNsmfSuccess"), captor.capture())
+ String resultSuccess = captor.getValue()
+ assertEquals("ERROR", resultSuccess)
+ }
+
+ @Test
+ void testPrepareUpdateOperationStatus() {
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345")
+ when(mockExecution.getVariable("operationId")).thenReturn("54321")
+ when(mockExecution.getVariable("operationType")).thenReturn("activate")
+
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("11111")
+ when(mockExecution.getVariable("mso.adapters.openecomp.db.endpoint"))
+ .thenReturn("http://localhost:28090/dbadapters/RequestsDbAdapter")
+ ActivateCommunicationService service = new ActivateCommunicationService()
+
+ service.prepareUpdateOperationStatus(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String res = captor.getValue()
+
+ String expect = getExpectPayload("updateServiceOperationStatus", "processing", "20",
+ "communication service activate operation processing: waiting nsmf service create finished")
+
+ assertEquals(expect.replaceAll("\\s+", ""), res.replaceAll("\\s+", ""))
+ }
+
+ private static getExpectPayload = { String type, String result, String progress, String operationContent ->
+ String expect =
+ """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:ns="http://org.onap.so/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <ns:${type} xmlns:ns="http://org.onap.so/requestsdb">
+ <serviceId>12345</serviceId>
+ <operationId>54321</operationId>
+ <operationType>activate</operationType>
+ <userId>11111</userId>
+ <result>${result}</result>
+ <operationContent>${operationContent}</operationContent>
+ <progress>${progress}</progress>
+ <reason></reason>
+ </ns:${type}>
+ </soapenv:Body>
+ </soapenv:Envelope>
+ """
+ return expect
+ }
+
+ @Test
+ void testPrepareCallCheckProcessStatus() {
+ ActivateCommunicationService service = new ActivateCommunicationService()
+ service.prepareCallCheckProcessStatus(mockExecution)
+ Mockito.verify(mockExecution, times(9)).setVariable(captor.capture(), captor.capture())
+ def resultSuccess = captor.getAllValues()
+ assertNotNull(resultSuccess)
+ }
+
+ @Test
+ void testPrepareCompleteStatus() {
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345")
+ when(mockExecution.getVariable("operationId")).thenReturn("54321")
+ when(mockExecution.getVariable("operationType")).thenReturn("activate")
+ when(mockExecution.getVariable("operationContent"))
+ .thenReturn("communication service activate operation finished")
+
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("11111")
+ when(mockExecution.getVariable("operationStatus"))
+ .thenReturn("deactivated")
+ ActivateCommunicationService service = new ActivateCommunicationService()
+
+ service.prepareCompleteStatus(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String res = captor.getValue()
+
+ String expect = getExpectPayload("updateServiceOperationStatus", "deactivated", "100",
+ "communication service activate operation finished")
+
+ assertEquals(expect.replaceAll("\\s+", ""), res.replaceAll("\\s+", ""))
+ }
+
+}
+
+
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationServiceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationServiceTest.groovy
new file mode 100644
index 0000000000..8c08e51efe
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationServiceTest.groovy
@@ -0,0 +1,308 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., 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.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity
+import org.junit.Before
+import org.junit.Test
+import org.mockito.ArgumentCaptor
+import org.mockito.Captor
+import org.mockito.Mockito
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.entities.AAIResultWrapper
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+
+import javax.ws.rs.NotFoundException
+import javax.ws.rs.core.Response
+
+import static org.junit.Assert.assertEquals
+import static org.junit.Assert.assertNotNull
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.*
+
+class DeleteCommunicationServiceTest extends MsoGroovyTest {
+
+ private HttpClientFactory httpClientFactoryMock
+ private HttpClient httpClientMock
+
+ @Before
+ void init() throws IOException {
+ super.init("DeleteCommunicationServiceTest")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345")
+ when(mockExecution.getVariable("bpmnRequest")).thenReturn("""
+ {
+ "globalSubscriberId ":"5GCustomer",
+ "serviceType ":"5G"
+ }""".replaceAll("\\\\s+", ""))
+ when(mockExecution.getVariable("mso-request-id")).thenReturn("4c614769-f58a-4556-8ad9-dcd903077c82")
+
+ DeleteCommunicationService delCS = new DeleteCommunicationService()
+ delCS.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution,times(3)).setVariable(captor.capture() as String, captor.capture())
+ List<ExecutionEntity> values = captor.getAllValues()
+ assertNotNull(values)
+ }
+
+ @Test
+ void testPreInitUpdateOperationStatus(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceInstanceName")).thenReturn("5G-test")
+ when(mockExecution.getVariable("result")).thenReturn("processing")
+ when(mockExecution.getVariable("progress")).thenReturn("0")
+ when(mockExecution.getVariable("operationContent")).thenReturn("delete communication service operation start")
+
+ DeleteCommunicationService delCS = new DeleteCommunicationService()
+ delCS.preInitUpdateOperationStatus(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String updateOperationStatus= captor.getValue()
+ assertNotNull(updateOperationStatus)
+ }
+
+ @Test
+ void testQueryCommunicationSeriveFromAAI(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ DeleteCommunicationService obj = spy(DeleteCommunicationService.class)
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(mockQueryCommunicationServiceReturn())
+ when(obj.getAAIClient()).thenReturn(client)
+ when(client.exists(resourceUri)).thenReturn(true)
+ when(client.get(resourceUri, NotFoundException.class)).thenReturn(wrapper)
+ obj.queryCommunicationSeriveFromAAI(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("e2eSliceServiceInstanceId"), captor.capture())
+ String e2eSliceServiceInstanceId = captor.getValue()
+ assertNotNull(e2eSliceServiceInstanceId)
+ }
+
+ @Test
+ void testPrepareCallCheckProcessStatus(){
+ DeleteCommunicationService dcs = new DeleteCommunicationService()
+ dcs.prepareCallCheckProcessStatus(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("endProgress"), captor.capture())
+ int endProgress = captor.getValue()
+ assertEquals(90,endProgress)
+ }
+
+ @Test
+ void testDelCSProfileFromAAI()
+ {
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(mockQueryCommunicationServiceProfile())
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.COMMUNICATION_PROFILE_ALL, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ AAIResourceUri profileUri = AAIUriFactory.createResourceUri(AAIObjectType.COMMUNICATION_SERVICE_PROFILE, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be", "5G-111111")
+
+ DeleteCommunicationService obj = spy(DeleteCommunicationService.class)
+ when(obj.getAAIClient()).thenReturn(client)
+ when(client.exists(resourceUri)).thenReturn(true)
+ when(client.exists(profileUri)).thenReturn(true)
+ when(client.get(resourceUri, NotFoundException.class)).thenReturn(wrapper)
+ doNothing().when(client).delete(profileUri)
+ obj.delCSProfileFromAAI(mockExecution)
+ Mockito.verify(client,times(1)).delete(profileUri)
+ }
+
+ @Test
+ void testPrepareFailureStatus(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceInstanceName")).thenReturn("5G-test")
+ when(mockExecution.getVariable("result")).thenReturn("finished")
+ when(mockExecution.getVariable("progress")).thenReturn("100")
+ when(mockExecution.getVariable("operationContent")).thenReturn("terminate service failure.")
+
+ DeleteCommunicationService dcs = new DeleteCommunicationService()
+ dcs.prepareFailureStatus(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String updateOperationStatus= captor.getValue()
+ assertNotNull(updateOperationStatus)
+ }
+
+ @Test
+ void testDelCSFromAAI(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ DeleteCommunicationService obj = spy(DeleteCommunicationService.class)
+ when(obj.getAAIClient()).thenReturn(client)
+ doNothing().when(client).delete(serviceInstanceUri)
+
+ obj.delCSFromAAI(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String updateOperationStatus= captor.getValue()
+ assertNotNull(updateOperationStatus)
+ }
+
+ @Test
+ void testPreFailedOperationStatus(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceInstanceName")).thenReturn("5G-test")
+ when(mockExecution.getVariable("result")).thenReturn("error")
+ when(mockExecution.getVariable("progress")).thenReturn("100")
+ when(mockExecution.getVariable("operationContent")).thenReturn("terminate service failure")
+
+ DeleteCommunicationService deleteCommunicationService = new DeleteCommunicationService()
+ WorkflowException exception = new WorkflowException("11113",7000,"terminate service failure")
+ when(mockExecution.getVariable("WorkflowException")).thenReturn(exception)
+ deleteCommunicationService.preFailedOperationStatus(mockExecution)
+
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String updateOperationStatus= captor.getValue()
+ assertNotNull(updateOperationStatus)
+ }
+
+ @Test
+ void testSendRequest2NSMFWF(){
+ httpClientMock = mock(HttpClient.class)
+ httpClientFactoryMock = mock(HttpClientFactory.class)
+ String url ="http://so.onap:8080/onap/so/infra/e2eServiceInstances/v3/5G-777"
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("progress")).thenReturn("20")
+ when(mockExecution.getVariable("operationContent")).thenReturn("waiting nsmf service delete finished")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("mso.infra.endpoint.url")).thenReturn("http://so.onap:8080/onap/so/infra")
+ when(mockExecution.getVariable("e2eSliceServiceInstanceId")).thenReturn("5G-777")
+ when(mockExecution.getVariable("e2eOperationId")).thenReturn("e151059a-d924-4629-845f-264db19e50b3")
+ when(httpClientFactoryMock.newJsonClient(new URL(url), ONAPComponents.SO)).thenReturn(httpClientMock)
+ DeleteCommunicationService obj = spy(DeleteCommunicationService.class)
+
+ Response responseMock = mock(Response.class)
+ when(responseMock.getStatus()).thenReturn(200)
+ when(responseMock.hasEntity()).thenReturn(true)
+ when(responseMock.getEntity()).thenReturn(getNSSMFResponse())
+ when(obj.getHttpClientFactory()).thenReturn(httpClientFactoryMock)
+ when(httpClientMock.delete(anyString())).thenReturn(responseMock)
+
+ obj.sendRequest2NSMFWF(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String updateOperationStatus= captor.getValue()
+ assertNotNull(updateOperationStatus)
+ }
+
+ private String getNSSMFResponse(){
+ String response = """{
+ "service":{
+ "serviceId":"e151059a-d924-4629-845f-264db19e50b4",
+ "operationId":"e151059a-d924-4629-845f-264db19e50b3"
+ }
+ }"""
+ return response
+ }
+
+
+
+
+ private String mockQueryCommunicationServiceReturn()
+ {
+ String expect =
+ """{
+ "service-instance-id": "5G-666",
+ "service-instance-name": "eMBB_Slice_Communication_Service_5GCustomer",
+ "service-type": "eMBB",
+ "service-role": "communication-service",
+ "environment-context": "01-010101",
+ "workload-context": "12",
+ "created-at": "2019-12-11 19:56:00",
+ "description": "",
+ "model-invariant-id": "e75698d9-925a-4cdd-a6c0-edacbe6a0b51",
+ "model-version-id": "8ee5926d-720b-4bb2-86f9-d20e921c143b",
+ "service-instance-location-id": "300-01|300-02",
+ "resource-version": "1582623470778",
+ "orchestration-status": "created",
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v16/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/5G-777",
+ "relationship-data": [
+ {
+ "relationship-key": "customer.global-customer-id",
+ "relationship-value": "5GCustomer"
+ },
+ {
+ "relationship-key": "service-subscription.service-type",
+ "relationship-value": "5G"
+ },
+ {
+ "relationship-key": "service-instance.service-instance-id",
+ "relationship-value": "5G-777"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "eMBB_e2e_Slice_Service_5GCustomer"
+ }
+ ]
+ }
+ ]
+ }
+ }"""
+ return expect
+ }
+
+ private String mockQueryCommunicationServiceProfile()
+ {
+ String expect =
+ """{
+ "communication-service-profile": [
+ {
+ "profile-id": "5G-111111",
+ "max-number-of-UEs": 50,
+ "coverage-area-list": "longgang,futian",
+ "latency": 20,
+ "exp-data-rate-UL": 300,
+ "exp-data-rate-DL": 500,
+ "ue-mobility-level": "stationary",
+ "resource-sharing-level": "Non-Shared",
+ "resource-version": "1577454950460"
+ }
+ ]
+ }"""
+ return expect
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceServiceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceServiceTest.groovy
new file mode 100644
index 0000000000..fb50fcc43b
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceServiceTest.groovy
@@ -0,0 +1,171 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., 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.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity
+import org.junit.Before
+import org.junit.Test
+import org.mockito.ArgumentCaptor
+import org.mockito.Captor
+import org.mockito.Mockito
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.entities.AAIResultWrapper
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+
+import javax.ws.rs.NotFoundException
+
+import static org.junit.Assert.assertNotNull
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.doNothing
+import static org.mockito.Mockito.spy
+import static org.mockito.Mockito.times
+import static org.mockito.Mockito.when
+import static org.mockito.Mockito.when
+import static org.mockito.Mockito.when
+
+class DeleteSliceServiceTest extends MsoGroovyTest {
+ @Before
+ void init() throws IOException {
+ super.init("DeleteSliceServiceTest")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("eb0863e9-a69b-4b17-8a56-f05ad110bef7")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceInstanceName")).thenReturn("5G-test")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+ when(mockExecution.getVariable("result")).thenReturn("processing")
+ when(mockExecution.getVariable("progress")).thenReturn("0")
+ when(mockExecution.getVariable("operationContent")).thenReturn("Delete Slice service operation start")
+ when(mockExecution.getVariable("bpmnRequest")).thenReturn("""
+ {
+ "globalSubscriberId ":"5GCustomer",
+ "serviceType ":"5G"
+ }""".replaceAll("\\\\s+", ""))
+ when(mockExecution.getVariable("mso-request-id")).thenReturn("4c614769-f58a-4556-8ad9-dcd903077c82")
+
+ DeleteSliceService delSS = new DeleteSliceService()
+ delSS.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String updateOperationStatus = captor.getValue()
+ assertNotNull(updateOperationStatus)
+ }
+
+ @Test
+ void testDeleteSliceServiceInstance(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ when(mockExecution.getVariable("result")).thenReturn("finished")
+ when(mockExecution.getVariable("progress")).thenReturn("100")
+ when(mockExecution.getVariable("operationContent")).thenReturn("NSMF completes slicing service termination.")
+
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ DeleteSliceService obj = spy(DeleteSliceService.class)
+ when(obj.getAAIClient()).thenReturn(client)
+ doNothing().when(client).delete(serviceInstanceUri)
+
+ obj.deleteSliceServiceInstance(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String updateOperationStatus= captor.getValue()
+ assertNotNull(updateOperationStatus)
+ }
+
+ @Test
+ void testDelServiceProfileFromAAI(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(mockQuerySliceServiceProfile())
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE_ALL, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ AAIResourceUri profileUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be", "5G-2222222")
+
+ DeleteSliceService obj = spy(DeleteSliceService.class)
+ when(obj.getAAIClient()).thenReturn(client)
+ when(client.exists(resourceUri)).thenReturn(true)
+ when(client.exists(profileUri)).thenReturn(true)
+ when(client.get(resourceUri, NotFoundException.class)).thenReturn(wrapper)
+ doNothing().when(client).delete(profileUri)
+ obj.delServiceProfileFromAAI(mockExecution)
+ Mockito.verify(client,times(1)).delete(profileUri)
+ }
+
+ @Test
+ void testPrepareEndOperationStatus(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceInstanceName")).thenReturn("5G-test")
+ when(mockExecution.getVariable("result")).thenReturn("error")
+ when(mockExecution.getVariable("progress")).thenReturn("100")
+ when(mockExecution.getVariable("operationContent")).thenReturn("terminate service failure")
+
+ DeleteSliceService deleteSliceService = new DeleteSliceService()
+ WorkflowException exception = new WorkflowException("11113",7000,"terminate service failure")
+ when(mockExecution.getVariable("WorkflowException")).thenReturn(exception)
+ deleteSliceService.prepareEndOperationStatus(mockExecution)
+
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String updateOperationStatus= captor.getValue()
+ assertNotNull(updateOperationStatus)
+
+ }
+
+ private String mockQuerySliceServiceProfile(){
+ String expect =
+ """{
+ "service-profile": [
+ {
+ "profile-id": "5G-2222222",
+ "latency": 50,
+ "max-number-of-UEs": 500,
+ "coverage-area-TA-list": "longgang,futian",
+ "ue-mobility-level": "stationary",
+ "resource-sharing-level": "Non-Shared",
+ "exp-data-rate-UL": 10,
+ "exp-data-rate-DL": 30,
+ "area-traffic-cap-UL": 100,
+ "area-traffic-cap-DL": 100,
+ "activity-factor": 80,
+ "jitter": 10,
+ "survival-time": 30,
+ "cs-availability": 95.5,
+ "reliability": 99.9,
+ "exp-data-rate": 80,
+ "traffic-density": 100,
+ "conn-density": 80,
+ "resource-version": "1577454958647"
+ }
+ ]
+ }"""
+ return expect
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSITest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSITest.groovy
new file mode 100644
index 0000000000..493e2c9e1e
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSITest.groovy
@@ -0,0 +1,258 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., 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.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity
+import org.junit.Before
+import org.junit.Test
+import org.mockito.ArgumentCaptor
+import org.mockito.Captor
+import org.mockito.Mockito
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.beans.nsmf.JobStatusResponse
+import org.onap.so.beans.nsmf.NssiResponse
+import org.onap.so.beans.nsmf.ResponseDescriptor
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+import org.onap.so.bpmn.core.domain.ServiceArtifact
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.domain.ServiceInfo
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+
+import javax.ws.rs.core.Response
+
+import static org.junit.Assert.assertNotNull
+import static org.junit.Assert.assertTrue
+import static org.mockito.ArgumentMatchers.anyString
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.doNothing
+import static org.mockito.Mockito.mock
+import static org.mockito.Mockito.spy
+import static org.mockito.Mockito.times
+import static org.mockito.Mockito.when
+
+class DoDeallocateNSSITest extends MsoGroovyTest {
+
+ private HttpClientFactory httpClientFactoryMock
+ private HttpClient httpClientMock
+
+ @Before
+ void init() throws IOException {
+ super.init("DoDeallocateNSSITest")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+
+ @Test
+ void testPreProcessRequest(){
+ def currentNSSI = [:]
+ currentNSSI.put("nssiServiceInstanceId","5G-999")
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ DoDeallocateNSSI ddnssi = new DoDeallocateNSSI()
+ ddnssi.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution,times(1)).getVariable("currentNSSI")
+ }
+
+ @Test
+ void testPrepareDecomposeService(){
+ def currentNSSI = [:]
+ currentNSSI.put("modelInvariantId", "21d57d4b-52ad-4d3c-a798-248b5bb9124b")
+ currentNSSI.put("modelVersionId", "bfba363e-e39c-4bd9-a9d5-1371c28f4d22")
+ currentNSSI.put("nssiServiceInstanceId","5G-999")
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ DoDeallocateNSSI ddnssi = new DoDeallocateNSSI()
+ ddnssi.prepareDecomposeService(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("serviceModelInfo"), captor.capture())
+ String serviceModelInfo = captor.getValue()
+ assertNotNull(serviceModelInfo)
+ }
+
+ @Test
+ void testProcessDecomposition(){
+ def currentNSSI = [:]
+ ServiceArtifact artifact = new ServiceArtifact()
+ artifact.setContent(getArtifactContent())
+ ServiceInfo serviceInfo = new ServiceInfo()
+ List<ServiceArtifact> artifactList = new ArrayList<>()
+ artifactList.add(artifact)
+ serviceInfo.setServiceArtifact(artifactList)
+ ServiceDecomposition decomposition = new ServiceDecomposition()
+ decomposition.setServiceInfo(serviceInfo)
+ when(mockExecution.getVariable("serviceDecomposition")).thenReturn(decomposition)
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ DoDeallocateNSSI ddnssi = new DoDeallocateNSSI()
+ ddnssi.processDecomposition(mockExecution)
+ String vendor = currentNSSI.get("vendor")
+ assertNotNull(vendor)
+ }
+
+ @Test
+ void testHandleJobStatus(){
+ def currentNSSI = [:]
+ currentNSSI.put("jobProgress", 10)
+ currentNSSI.put("proportion", 90)
+ currentNSSI.put("statusDescription","")
+ currentNSSI.put("e2eServiceInstanceId","21d57d4b-52ad-4d3c-a798-248b5bb9124b")
+ currentNSSI.put("operationId","4c614769-f58a-4556-8ad9-dcd903077c82")
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ DoDeallocateNSSI ddnssi = new DoDeallocateNSSI()
+ ddnssi.handleJobStatus(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String updateOperationStatus= captor.getValue()
+ assertNotNull(updateOperationStatus)
+ }
+
+ @Test
+ void testDelSliceProfileFromAAI(){
+ def currentNSSI = [:]
+ currentNSSI.put("nssiServiceInstanceId", "5G-999")
+ currentNSSI.put("profileId", "ddf57704-fe8d-417b-882d-2f2a12ddb225")
+ currentNSSI.put("globalSubscriberId","5GCustomer")
+ currentNSSI.put("serviceType","5G")
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ AAIResourceUri profileUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, "5GCustomer", "5G", "5G-999", "ddf57704-fe8d-417b-882d-2f2a12ddb225")
+ DoDeallocateNSSI obj = spy(DoDeallocateNSSI.class)
+ when(obj.getAAIClient()).thenReturn(client)
+ when(client.exists(profileUri)).thenReturn(true)
+ doNothing().when(client).delete(profileUri)
+
+ obj.delSliceProfileFromAAI(mockExecution)
+ Mockito.verify(client,times(1)).delete(profileUri)
+ }
+
+ @Test
+ void testSendRequestToNSSMF(){
+ httpClientFactoryMock = mock(HttpClientFactory.class)
+ httpClientMock = mock(HttpClient.class)
+
+ def currentNSSI = [:]
+ currentNSSI.put("snssai", "01-010101")
+ currentNSSI.put("profileId", "ddf57704-fe8d-417b-882d-2f2a12ddb225")
+ currentNSSI.put("nssiServiceInstanceId","5G-999")
+ currentNSSI.put("nsiServiceInstanceId","5G-888")
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+ when(mockExecution.getVariable("mso.adapters.nssmf.endpoint")).thenReturn("http://so-nssmf-adapter.onap:8088")
+ String nssmfRequest = "http://so-nssmf-adapter.onap:8088/api/rest/provMns/v1/NSS/SliceProfiles/ddf57704-fe8d-417b-882d-2f2a12ddb225"
+
+ when(httpClientFactoryMock.newJsonClient(new URL(nssmfRequest), ONAPComponents.EXTERNAL)).thenReturn(httpClientMock)
+ DoDeallocateNSSI obj = spy(DoDeallocateNSSI.class)
+ when(obj.getHttpClientFactory()).thenReturn(httpClientFactoryMock)
+ Response responseMock = mock(Response.class)
+ NssiResponse response = new NssiResponse()
+ response.setNssiId("NSSI-C-004-HDBHZ-NSSMF-01-A-HW")
+ response.setJobId("a5c5913d-448a-bcb1-9b800a944d84")
+ when(httpClientMock.post(anyString())).thenReturn(responseMock)
+ when(responseMock.getStatus()).thenReturn(202)
+ when(responseMock.readEntity(NssiResponse.class)) thenReturn(response)
+ when(responseMock.hasEntity()).thenReturn(true)
+
+ obj.sendRequestToNSSMF(mockExecution)
+ String jobId = currentNSSI['jobId']
+ assertNotNull(jobId)
+ }
+
+ @Test
+ void testGetJobStatus(){
+ httpClientFactoryMock = mock(HttpClientFactory.class)
+ httpClientMock = mock(HttpClient.class)
+
+ def currentNSSI = [:]
+ currentNSSI.put("jobId", "a5c5913d-448a-bcb1-9b800a944d84")
+ currentNSSI.put("nssiServiceInstanceId","5G-999")
+ currentNSSI.put("nsiServiceInstanceId","5G-888")
+ currentNSSI.put("jobProgress",60)
+
+ when(mockExecution.getVariable("isNSSIDeAllocated")).thenReturn(false)
+ when(mockExecution.getVariable("isNSSIDeAllocated")).thenReturn(false)
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+ when(mockExecution.getVariable("mso.adapters.nssmf.endpoint")).thenReturn("http://so-nssmf-adapter.onap:8088")
+ String nssmfRequest = "http://so-nssmf-adapter.onap:8088/api/rest/provMns/v1/NSS/jobs/a5c5913d-448a-bcb1-9b800a944d84"
+
+ when(httpClientFactoryMock.newJsonClient(new URL(nssmfRequest), ONAPComponents.EXTERNAL)).thenReturn(httpClientMock)
+ DoDeallocateNSSI obj = spy(DoDeallocateNSSI.class)
+ when(obj.getHttpClientFactory()).thenReturn(httpClientFactoryMock)
+ Response responseMock = mock(Response.class)
+ ResponseDescriptor descriptor = new ResponseDescriptor()
+ descriptor.setProgress(100)
+ descriptor.setStatusDescription("finished deallocate nssi")
+ JobStatusResponse jobStatusResponse = new JobStatusResponse()
+ jobStatusResponse.setResponseDescriptor(descriptor)
+ when(httpClientMock.post(anyString())).thenReturn(responseMock)
+ when(responseMock.getStatus()).thenReturn(202)
+ when(responseMock.readEntity(JobStatusResponse.class)) thenReturn(jobStatusResponse)
+ when(responseMock.hasEntity()).thenReturn(true)
+
+ obj.getJobStatus(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("isNSSIDeAllocated"), captor.capture())
+ boolean value = captor.getValue()
+ assertTrue(value)
+ }
+
+
+ private String getArtifactContent(){
+ String content =
+ """
+ {
+ "metadata":{
+ "id":"NSST-C-001-HDBNJ-NSSMF-01-A-HW",
+ "vendor":"HW",
+ "version":"1.0",
+ "name":"eMBB_demo",
+ "description":"eMBB for demo",
+ "type":"embb",
+ "domainType":"cn"
+ },
+ "capabilities":{
+ "latency":{
+ "type":"integer",
+ "constrainstsl":"less_or_equal",
+ "value":"20"
+ },
+ "areaTrafficCapDL":{
+ "type":"integer",
+ "constrainstsl":"less_or_equal",
+ "value":"300"
+ },
+ "areaTrafficCapUL":{
+ "type":"integer",
+ "constrainstsl":"less_or_equal",
+ "value":"300"
+ },
+ "maxNumberofUEs":{
+ "type":"integer",
+ "constrainstsl":"less_or_equal",
+ "value":"300"
+ }
+ }
+ }
+ """
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceServiceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceServiceTest.groovy
new file mode 100644
index 0000000000..8a18376819
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceServiceTest.groovy
@@ -0,0 +1,460 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., 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.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity
+import org.junit.Before
+import org.junit.Test
+import org.mockito.ArgumentCaptor
+import org.mockito.Captor
+import org.mockito.Mockito
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.entities.AAIResultWrapper
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+
+import javax.ws.rs.NotFoundException
+
+import static org.junit.Assert.assertEquals
+import static org.junit.Assert.assertNotNull
+import static org.junit.Assert.assertTrue
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.doNothing
+import static org.mockito.Mockito.spy
+import static org.mockito.Mockito.times
+import static org.mockito.Mockito.verify
+import static org.mockito.Mockito.when
+
+class DoDeleteSliceServiceTest extends MsoGroovyTest {
+ @Before
+ void init() throws IOException {
+ super.init("DoDeleteSliceServiceTest")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest(){
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("e2a747a0-2ca6-476d-ac28-de999cf3fbfe")
+
+ DoDeleteSliceService doDeleteSliceService = new DoDeleteSliceService()
+ doDeleteSliceService.preProcessRequest(mockExecution)
+
+ Mockito.verify(mockExecution,times(1)).setVariable(captor.capture() as String, captor.capture())
+ List<ExecutionEntity> values = captor.getAllValues()
+ assertNotNull(values)
+ }
+
+ @Test
+ void testQueryE2ESliceSeriveFromAAI(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ DoDeleteSliceService obj = spy(DoDeleteSliceService.class)
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(mockQuerySliceServiceReturn())
+ when(obj.getAAIClient()).thenReturn(client)
+ when(client.exists(resourceUri)).thenReturn(true)
+ when(client.get(resourceUri, NotFoundException.class)).thenReturn(wrapper)
+ obj.queryE2ESliceSeriveFromAAI(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("snssai"), captor.capture())
+ String snssai = captor.getValue()
+ assertNotNull(snssai)
+ }
+
+ @Test
+ void testGetAllottedResFromAAI(){
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE_ALL, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ DoDeleteSliceService obj = spy(DoDeleteSliceService.class)
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(mockQueryAllottedResource())
+ when(obj.getAAIClient()).thenReturn(client)
+ when(client.exists(resourceUri)).thenReturn(true)
+ when(client.get(resourceUri, NotFoundException.class)).thenReturn(wrapper)
+ obj.getAllottedResFromAAI(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("nsiId"), captor.capture())
+ String nsiId = captor.getValue()
+ assertNotNull(nsiId)
+ }
+
+ @Test
+ void testGetNSIFromAAI(){
+ when(mockExecution.getVariable("nsiId")).thenReturn("5G-888")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "5G-888")
+ DoDeleteSliceService obj = spy(DoDeleteSliceService.class)
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(mockNSIReturn())
+ when(obj.getAAIClient()).thenReturn(client)
+ when(client.exists(resourceUri)).thenReturn(true)
+ when(client.get(resourceUri, NotFoundException.class)).thenReturn(wrapper)
+ obj.getNSIFromAAI(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("nssiIdList"), captor.capture())
+ List<String> nssiIdList = captor.getValue()
+ assertNotNull(nssiIdList)
+ }
+
+ @Test
+ void testGetNSSIListFromAAI(){
+ List<String> nssiIdList = []
+ nssiIdList.add("5G-999")
+
+ when(mockExecution.getVariable("nssiIdList")).thenReturn(nssiIdList)
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "5G-999")
+ DoDeleteSliceService obj = spy(DoDeleteSliceService.class)
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(mockNSSIReturn())
+ when(obj.getAAIClient()).thenReturn(client)
+ when(client.exists(resourceUri)).thenReturn(true)
+ when(client.get(resourceUri, NotFoundException.class)).thenReturn(wrapper)
+ obj.getNSSIListFromAAI(mockExecution)
+ Mockito.verify(mockExecution,times(1)).setVariable(eq("nssiInstanceList"), captor.capture())
+ List<ServiceInstance> nssiInstanceList = captor.getValue()
+ assertNotNull(nssiInstanceList)
+ }
+
+ @Test
+ void testGetCurrentNSSI(){
+ ServiceInstance nssi = new ServiceInstance()
+ nssi.setServiceInstanceId("5G-999")
+ nssi.setModelInvariantId("21d57d4b-52ad-4d3c-a798-248b5bb9124a")
+ nssi.setModelVersionId("bfba363e-e39c-4bd9-a9d5-1371c28f4d22")
+ List<ServiceInstance> nssiInstanceList = []
+ nssiInstanceList.add(nssi)
+ when(mockExecution.getVariable("currentNSSIIndex")).thenReturn(0)
+ when(mockExecution.getVariable("nssiInstanceList")).thenReturn(nssiInstanceList)
+ when(mockExecution.getVariable("snssai")).thenReturn("01-010101")
+ when(mockExecution.getVariable("nsiId")).thenReturn("5G-888")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("5G-777")
+ when(mockExecution.getVariable("msoRequestId")).thenReturn("4c614769-f58a-4556-8ad9-dcd903077c82")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+ when(mockExecution.getVariable("proportion")).thenReturn("90")
+
+ DoDeleteSliceService ddss = new DoDeleteSliceService()
+ ddss.getCurrentNSSI(mockExecution)
+ verify(mockExecution,times(1)).setVariable(eq("currentNSSI"), captor.capture())
+ Map currentNSSI = captor.getValue()
+ assertTrue(currentNSSI.size()>0)
+ }
+
+ @Test
+ void testQuerySliceProfileFromAAI(){
+ def currentNSSI = [:]
+ currentNSSI.put("nssiServiceInstanceId","5G-999")
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(mockSliceProfile())
+ AAIResourceUri profileUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE_ALL, "5GCustomer", "5G", "5G-999")
+
+ DoDeleteSliceService obj = spy(DoDeleteSliceService.class)
+ when(obj.getAAIClient()).thenReturn(client)
+ when(client.exists(profileUri)).thenReturn(true)
+ when(client.get(profileUri, NotFoundException.class)).thenReturn(wrapper)
+ obj.querySliceProfileFromAAI(mockExecution)
+ verify(mockExecution,times(1)).setVariable(eq("currentNSSI"), captor.capture())
+ Map value = captor.getValue()
+ assertNotNull(currentNSSI.get('profileId'))
+ }
+
+ @Test
+ void parseNextNSSI(){
+ ServiceInstance nssi = new ServiceInstance()
+ nssi.setServiceInstanceId("5G-999")
+ nssi.setModelInvariantId("21d57d4b-52ad-4d3c-a798-248b5bb9124b")
+ nssi.setModelVersionId("bfba363e-e39c-4bd9-a9d5-1371c28f4d22")
+ List<ServiceInstance> nssiInstanceList = []
+ nssiInstanceList.add(nssi)
+ when(mockExecution.getVariable("currentNSSIIndex")).thenReturn(0)
+ when(mockExecution.getVariable("nssiInstanceList")).thenReturn(nssiInstanceList)
+
+ DoDeleteSliceService ddss = new DoDeleteSliceService()
+ ddss.parseNextNSSI(mockExecution)
+ verify(mockExecution,times(1)).setVariable(eq("isAllNSSIFinished"), captor.capture())
+ boolean isAllNSSIFinished = captor.getValue()
+ assertTrue(isAllNSSIFinished)
+ }
+
+ private String mockSliceProfile(){
+ String expect =
+ """{
+ "slice-profile": [
+ {
+ "profile-id": "ddf57704-fe8d-417b-882d-2f2a12ddb225",
+ "latency": 20,
+ "max-number-of-UEs": 0,
+ "coverage-area-TA-list": "[{\\"province\\":\\"??\\",\\"city\\":\\"???\\",\\"county\\":\\"???\\",\\"street\\":\\"?????\\"}]",
+ "ue-mobility-level": "stationary",
+ "resource-sharing-level": "0",
+ "exp-data-rate-UL": 100,
+ "exp-data-rate-DL": 100,
+ "activity-factor": 0,
+ "e2e-latency": 0,
+ "jitter": 0,
+ "survival-time": 0,
+ "exp-data-rate": 0,
+ "payload-size": 0,
+ "traffic-density": 0,
+ "conn-density": 0,
+ "s-nssai": "01003",
+ "resource-version": "1580800791373"
+ }
+ ]
+ }
+ """
+ return expect
+ }
+
+ private String mockNSSIReturn(){
+ String expect =
+ """
+ {
+ "service-instance-id": "5G-999",
+ "service-instance-name": "eMBB_Slice_NSSI_5GCustomer",
+ "service-type": "eMBB",
+ "service-role": "nssi",
+ "environment-context": "cn",
+ "model-invariant-id": "21d57d4b-52ad-4d3c-a798-248b5bb9124a",
+ "model-version-id": "bfba363e-e39c-4bd9-a9d5-1371c28f4d22",
+ "service-instance-location-id": "300-01|300-02",
+ "resource-version": "1578449638032",
+ "orchestration-status": "activated",
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v16/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/5G-888",
+ "relationship-data": [
+ {
+ "relationship-key": "customer.global-customer-id",
+ "relationship-value": "5GCustomer"
+ },
+ {
+ "relationship-key": "service-subscription.service-type",
+ "relationship-value": "5G"
+ },
+ {
+ "relationship-key": "service-instance.service-instance-id",
+ "relationship-value": "5G-888"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "eMBB_e2e_Slice_Service_5GCustomer"
+ }
+ ]
+ }
+ ]
+ }
+ }
+ """
+ return expect
+ }
+
+ private String mockNSIReturn(){
+ String expect =
+ """
+ {
+ "service-instance-id": "5G-888",
+ "service-instance-name": "eMBB_e2e_Slice_Service_5GCustomer",
+ "service-type": "embb",
+ "service-role": "nsi",
+ "model-invariant-id": "0e9bcb9a-c832-433b-a0c1-74866768f608",
+ "model-version-id": "2c5fd79d-0f84-4057-9222-952cb6f27036",
+ "service-instance-location-id": "300-01|300-02",
+ "resource-version": "1579691104911",
+ "orchestration-status": "activated",
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v16/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/5G-999",
+ "relationship-data": [
+ {
+ "relationship-key": "customer.global-customer-id",
+ "relationship-value": "5GCustomer"
+ },
+ {
+ "relationship-key": "service-subscription.service-type",
+ "relationship-value": "5G"
+ },
+ {
+ "relationship-key": "service-instance.service-instance-id",
+ "relationship-value": "5G-999"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "eMBB_Slice_NSSI_5GCustomer"
+ }
+ ]
+ },
+ {
+ "related-to": "allotted-resource",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v16/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/5G-777/allotted-resources/allotted-resource/5G-1234",
+ "relationship-data": [
+ {
+ "relationship-key": "customer.global-customer-id",
+ "relationship-value": "5GCustomer"
+ },
+ {
+ "relationship-key": "service-subscription.service-type",
+ "relationship-value": "5G"
+ },
+ {
+ "relationship-key": "service-instance.service-instance-id",
+ "relationship-value": "5G-777"
+ },
+ {
+ "relationship-key": "allotted-resource.id",
+ "relationship-value": "5G-1234"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "allotted-resource.description"
+ },
+ {
+ "property-key": "allotted-resource.allotted-resource-name"
+ }
+ ]
+ }
+ ]
+ }
+ }
+ """
+ return expect
+ }
+
+ private String mockQueryAllottedResource(){
+ String expect =
+ """{
+ "allotted-resource": [
+ {
+ "id": "5G-1234",
+ "resource-version": "1577454983471",
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v16/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/5G-888",
+ "relationship-data": [
+ {
+ "relationship-key": "customer.global-customer-id",
+ "relationship-value": "5GCustomer"
+ },
+ {
+ "relationship-key": "service-subscription.service-type",
+ "relationship-value": "5G"
+ },
+ {
+ "relationship-key": "service-instance.service-instance-id",
+ "relationship-value": "5G-888"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "eMBB_e2e_Slice_Service_5GCustomer"
+ }
+ ]
+ }
+ ]
+ }
+ }
+ ]
+ }
+ """
+ return expect
+ }
+
+ String mockQuerySliceServiceReturn(){
+ String expect =
+ """{
+ "service-instance-id": "5G-777",
+ "service-instance-name": "eMBB_e2e_Slice_Service_5GCustomer",
+ "service-type": "embb",
+ "service-role": "e2eslice-service",
+ "environment-context": "01-010101",
+ "model-invariant-id": "e65d737a-41e0-4ad1-958f-56defdf2e907",
+ "model-version-id": "f2f5967e-72d3-4c5c-b880-e214e71dba4e",
+ "service-instance-location-id": "300-01|300-02",
+ "resource-version": "1578449638436",
+ "orchestration-status": "activated",
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v16/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/5G-666",
+ "relationship-data": [
+ {
+ "relationship-key": "customer.global-customer-id",
+ "relationship-value": "5GCustomer"
+ },
+ {
+ "relationship-key": "service-subscription.service-type",
+ "relationship-value": "5G"
+ },
+ {
+ "relationship-key": "service-instance.service-instance-id",
+ "relationship-value": "5G-666"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "eMBB_Slice_Communication_Service_5GCustomer"
+ }
+ ]
+ }
+ ]
+ }
+ }
+ """
+ return expect
+ }
+
+}