aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/so-bpmn-infrastructure-common/src
diff options
context:
space:
mode:
Diffstat (limited to 'bpmn/so-bpmn-infrastructure-common/src')
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSliceSubnet.groovy181
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/AllocateSliceSubnet.groovy190
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/AnNssmfutils.groovy448
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCommunicationService.groovy15
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceService.groovy360
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeAllocateSliceSubnet.groovy170
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateAccessNSSI.groovy589
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateCoreNSSI.groovy685
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateTnNssi.groovy162
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateAccessNSSI.groovy1041
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNSSI.groovy157
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNonSharedSlice.groovy432
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreSharedSlice.groovy658
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSIandNSSI.groovy887
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateNSSI.groovy733
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateCommunicationService.groovy4
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceInstance.groovy247
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateSliceServiceOption.groovy877
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateTnNssiInstance.groovy231
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeAllocateAccessNSSI.groovy556
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateCoreNSSI.groovy1298
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy153
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateTnNssi.groovy169
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceService.groovy142
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyAccessNSSI.groovy656
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyCoreNSSI.groovy732
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyRanNfNssi.groovy193
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyTnNssi.groovy401
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/GenericPnfSoftwareUpgrade.groovy (renamed from bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/PNFSoftwareUpgrade.groovy)4
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ModifySliceSubnet.groovy173
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/QueryJobStatus.groovy141
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/TnAllocateNssi.groovy339
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/TnNssmfUtils.groovy244
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSliceSubnetTest.groovy68
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/AllocateSliceSubnetTest.groovy135
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceServiceTest.groovy39
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeAllocateSliceSubnetTest.groovy72
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateCoreNSSITest.groovy631
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateTnNssiTest.groovy178
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNSSITest.groovy103
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNonSharedSliceTest.groovy118
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreSharedSliceTest.groovy646
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateTnNssiTest.groovy167
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateCoreNSSITest.groovy829
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateTnNssiTest.groovy135
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyTnNssiTest.groovy174
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ModifySliceSubnetTest.groovy72
47 files changed, 14871 insertions, 1764 deletions
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSliceSubnet.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSliceSubnet.groovy
new file mode 100644
index 0000000000..c7fe7e36a6
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSliceSubnet.groovy
@@ -0,0 +1,181 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, Wipro Limited.
+ #
+ # 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.delegate.BpmnError
+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.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class ActivateSliceSubnet extends AbstractServiceTaskProcessor {
+ String Prefix="ActSS"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+
+ private static final Logger logger = LoggerFactory.getLogger(ActivateSliceSubnet.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix + "preProcessRequest Start")
+ execution.setVariable("prefix", Prefix)
+ execution.setVariable("startTime", System.currentTimeMillis())
+ def msg
+ try {
+ // get request input
+ String subnetInstanceReq = execution.getVariable("bpmnRequest")
+ logger.debug(subnetInstanceReq)
+
+ String requestId = execution.getVariable("mso-request-id")
+ execution.setVariable("msoRequestId", requestId)
+ logger.debug("Input Request:" + subnetInstanceReq + " reqId:" + requestId)
+
+ //subscriberInfo
+ String globalSubscriberId = jsonUtil.getJsonValue(subnetInstanceReq, "globalSubscriberId")
+ if (isBlank(globalSubscriberId)) {
+ msg = "Input globalSubscriberId' is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("globalSubscriberId", globalSubscriberId)
+ }
+
+ //NSSI ID
+ String serviceInstanceID = jsonUtil.getJsonValue(subnetInstanceReq, "serviceInstanceID")
+ if (isBlank(serviceInstanceID)) {
+ msg = "Input serviceInstanceID is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("serviceInstanceID", serviceInstanceID)
+ }
+
+ String nsiId = jsonUtil.getJsonValue(subnetInstanceReq, "additionalProperties.nsiId")
+ if (isBlank(nsiId)) {
+ msg = "Input nsiId is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("nsiId", nsiId)
+ }
+ String networkType = jsonUtil.getJsonValue(subnetInstanceReq, "networkType")
+ if (isBlank(networkType)) {
+ msg = "Input networkType is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("networkType", networkType.toUpperCase())
+ }
+
+ //requestParameters, subscriptionServiceType is 5G
+ String subscriptionServiceType = jsonUtil.getJsonValue(subnetInstanceReq, "subscriptionServiceType")
+ if (isBlank(subscriptionServiceType)) {
+ msg = "Input subscriptionServiceType is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("subscriptionServiceType", subscriptionServiceType)
+ }
+
+ //operationType = deactivateInstance/activateInstance
+ String operationType = execution.getVariable("requestAction")
+ if (isBlank(operationType)) {
+ msg = "Input operationType is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("operationType", operationType)
+ }
+
+ String jobId = UUID.randomUUID().toString()
+ execution.setVariable("jobId", jobId)
+
+ String sliceParams = jsonUtil.getJsonValue(subnetInstanceReq, "additionalProperties")
+ execution.setVariable("sliceParams", sliceParams)
+
+ } catch(BpmnError e) {
+ throw e
+ } catch(Exception ex) {
+ msg = "Exception in ActivateSliceSubnet.preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "preProcessRequest Exit")
+ }
+
+
+ /**
+ * create operation status in request db
+ *
+ * Init the Operation Status
+ */
+ def prepareInitOperationStatus = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareInitOperationStatus Start")
+
+ String serviceId = execution.getVariable("serviceInstanceID")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operationType = execution.getVariable("operationType")
+ logger.debug("Generated new job for Service Instance serviceId:" + serviceId + " jobId:" + jobId)
+
+ ResourceOperationStatus initStatus = new ResourceOperationStatus()
+ initStatus.setServiceId(serviceId)
+ initStatus.setOperationId(jobId)
+ initStatus.setResourceTemplateUUID(nsiId)
+ initStatus.setOperType(operationType)
+ requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
+
+ logger.debug(Prefix + "prepareInitOperationStatus Exit")
+ }
+
+
+
+ /**
+ * return sync response
+ */
+ def sendSyncResponse = { DelegateExecution execution ->
+ logger.debug(Prefix + "sendSyncResponse Start")
+ try {
+ String jobId = execution.getVariable("jobId")
+ String activateSyncResponse = """{"jobId": "${jobId}","status": "processing"}"""
+ .trim().replaceAll(" ", "")
+
+ logger.debug("sendSyncResponse to APIH:" + "\n" + activateSyncResponse)
+ sendWorkflowResponse(execution, 202, activateSyncResponse)
+
+ execution.setVariable("sentSyncResponse", true)
+ } catch (Exception ex) {
+ String msg = "Exception in sendSyncResponse:" + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "sendSyncResponse Exit")
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/AllocateSliceSubnet.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/AllocateSliceSubnet.groovy
new file mode 100644
index 0000000000..5a7722d679
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/AllocateSliceSubnet.groovy
@@ -0,0 +1,190 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, Wipro Limited.
+ #
+ # 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.delegate.BpmnError
+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.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class AllocateSliceSubnet extends AbstractServiceTaskProcessor {
+
+ String Prefix="ASS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ private static final Logger logger = LoggerFactory.getLogger(AllocateSliceSubnet.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix + "preProcessRequest Start")
+ execution.setVariable("prefix", Prefix)
+ execution.setVariable("startTime", System.currentTimeMillis())
+ def msg
+ try {
+ // get request input
+ String subnetInstanceReq = execution.getVariable("bpmnRequest")
+ logger.debug(subnetInstanceReq)
+
+ String requestId = execution.getVariable("mso-request-id")
+ execution.setVariable("msoRequestId", requestId)
+ logger.debug("Input Request:" + subnetInstanceReq + " reqId:" + requestId)
+
+ //modelInfo
+ String modelInvariantUuid = jsonUtil.getJsonValue(subnetInstanceReq, "modelInvariantUuid")
+ if (isBlank(modelInvariantUuid)) {
+ msg = "Input modelInvariantUuid is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("modelInvariantUuid", modelInvariantUuid)
+ }
+
+ logger.debug("modelInvariantUuid: " + modelInvariantUuid)
+
+ String modelUuid = jsonUtil.getJsonValue(subnetInstanceReq, "modelUuid")
+ if (isBlank(modelUuid)) {
+ msg = "Input modelUuid is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("modelUuid", modelUuid)
+ }
+
+ logger.debug("modelUuid: " + modelUuid)
+
+
+ //subscriberInfo
+ String globalSubscriberId = jsonUtil.getJsonValue(subnetInstanceReq, "globalSubscriberId")
+ if (isBlank(globalSubscriberId)) {
+ msg = "Input globalSubscriberId' is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("globalSubscriberId", globalSubscriberId)
+ }
+ String dummyServiceId = new UUID(0,0).toString();
+ execution.setVariable("dummyServiceId", dummyServiceId)
+ logger.debug("dummyServiceId: " + dummyServiceId)
+ String servicename = jsonUtil.getJsonValue(subnetInstanceReq, "name")
+ execution.setVariable("servicename", servicename)
+
+ String nsiId = jsonUtil.getJsonValue(subnetInstanceReq, "additionalProperties.nsiInfo.nsiId")
+ if (isBlank(nsiId)) {
+ msg = "Input nsiId is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("nsiId", nsiId)
+ }
+
+ String networkType = jsonUtil.getJsonValue(subnetInstanceReq, "networkType")
+ if (isBlank(networkType)) {
+ msg = "Input networkType is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("networkType", networkType.toUpperCase())
+ }
+
+ //requestParameters, subscriptionServiceType is 5G
+ String subscriptionServiceType = jsonUtil.getJsonValue(subnetInstanceReq, "subscriptionServiceType")
+ if (isBlank(subscriptionServiceType)) {
+ msg = "Input subscriptionServiceType is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("subscriptionServiceType", subscriptionServiceType)
+ }
+
+ String jobId = UUID.randomUUID().toString()
+ execution.setVariable("jobId", jobId)
+
+ String sliceParams = jsonUtil.getJsonValue(subnetInstanceReq, "additionalProperties")
+ execution.setVariable("sliceParams", sliceParams)
+
+ } catch(BpmnError e) {
+ throw e
+ } catch(Exception ex) {
+ msg = "Exception in AllocateSliceSubnet.preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "preProcessRequest Exit")
+ }
+
+
+ /**
+ * create operation status in request db
+ *
+ * Init the Operation Status
+ */
+ def prepareInitOperationStatus = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareInitOperationStatus Start")
+
+ String serviceId = execution.getVariable("dummyServiceId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ logger.debug("Generated new job for Service Instance serviceId:" + serviceId + " jobId:" + jobId)
+
+ ResourceOperationStatus initStatus = new ResourceOperationStatus()
+ initStatus.setServiceId(serviceId)
+ initStatus.setOperationId(jobId)
+ initStatus.setResourceTemplateUUID(nsiId)
+ initStatus.setOperType("Allocate")
+ requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
+
+ logger.debug(Prefix + "prepareInitOperationStatus Exit")
+ }
+
+
+ /**
+ * return sync response
+ */
+ def sendSyncResponse = { DelegateExecution execution ->
+ logger.debug(Prefix + "sendSyncResponse Start")
+ try {
+ String jobId = execution.getVariable("jobId")
+ String allocateSyncResponse = """{"jobId": "${jobId}","status": "processing"}"""
+ .trim().replaceAll(" ", "").trim().replaceAll(" ", "")
+
+ logger.debug("sendSyncResponse to APIH:" + "\n" + allocateSyncResponse)
+ sendWorkflowResponse(execution, 202, allocateSyncResponse)
+
+ execution.setVariable("sentSyncResponse", true)
+ } catch (Exception ex) {
+ String msg = "Exception in sendSyncResponse:" + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "sendSyncResponse Exit")
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/AnNssmfutils.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/AnNssmfutils.groovy
new file mode 100644
index 0000000000..d59f865b01
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/AnNssmfutils.groovy
@@ -0,0 +1,448 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, Wipro Limited.
+ #
+ # 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.google.gson.JsonArray
+import org.camunda.bpm.engine.delegate.BpmnError
+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.common.scripts.NssmfAdapterUtils
+import org.onap.so.bpmn.common.scripts.OofUtils
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.sql.Timestamp
+import java.util.List
+import static org.apache.commons.lang3.StringUtils.isBlank
+import com.google.gson.JsonObject
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import javax.ws.rs.NotFoundException
+import org.onap.so.beans.nsmf.AllocateTnNssi
+import org.onap.so.beans.nsmf.DeAllocateNssi
+import org.onap.so.beans.nsmf.EsrInfo
+import org.onap.so.beans.nsmf.ServiceInfo
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aai.domain.yang.SliceProfile
+import org.onap.aai.domain.yang.SliceProfiles
+import org.onap.aai.domain.yang.Relationship
+
+class AnNssmfUtils {
+
+ private static final Logger logger = LoggerFactory.getLogger(AnNssmfUtils.class)
+ ObjectMapper objectMapper = new ObjectMapper();
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ public String buildSelectRANNSSIRequest(String requestId, String messageType, String UUID,String invariantUUID,
+ String name, Map<String, Object> profileInfo, List<String> nsstInfoList, JsonArray capabilitiesList, Boolean preferReuse){
+
+ def transactionId = requestId
+ logger.debug( "transactionId is: " + transactionId)
+ String correlator = requestId
+ String callbackUrl = UrnPropertiesReader.getVariable("mso.adapters.oof.callback.endpoint") + "/" + messageType + "/" + correlator
+ ObjectMapper objectMapper = new ObjectMapper();
+ String profileJson = objectMapper.writeValueAsString(profileInfo);
+ String nsstInfoListString = objectMapper.writeValueAsString(nsstInfoList);
+ //Prepare requestInfo object
+ JsonObject requestInfo = new JsonObject()
+ requestInfo.addProperty("transactionId", transactionId)
+ requestInfo.addProperty("requestId", requestId)
+ requestInfo.addProperty("callbackUrl", callbackUrl)
+ requestInfo.addProperty("sourceId","SO" )
+ requestInfo.addProperty("timeout", 600)
+ requestInfo.addProperty("numSolutions", 1)
+
+ //Prepare serviceInfo object
+ JsonObject ranNsstInfo = new JsonObject()
+ ranNsstInfo.addProperty("UUID", UUID)
+ ranNsstInfo.addProperty("invariantUUID", invariantUUID)
+ ranNsstInfo.addProperty("name", name)
+
+ JsonObject json = new JsonObject()
+ json.add("requestInfo", requestInfo)
+ json.add("NSTInfo", ranNsstInfo)
+ json.addProperty("serviceProfile", profileJson)
+ json.addProperty("NSSTInfo", nsstInfoListString)
+ json.add("subnetCapabilities", capabilitiesList)
+ json.addProperty("preferReuse", preferReuse)
+
+ return json.toString()
+}
+
+public String buildCreateTNNSSMFSubnetCapabilityRequest() {
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType("TN")
+ esrInfo.setVendor("ONAP")
+
+ JsonArray subnetTypes = new JsonArray()
+ subnetTypes.add("TN_FH")
+ subnetTypes.add("TN_MH")
+ JsonObject response = new JsonObject()
+ response.add("subnetCapabilityQuery", subnetTypes)
+ response.addProperty("esrInfo", objectMapper.writeValueAsString(esrInfo))
+ return response.toString()
+}
+
+public String buildCreateANNFNSSMFSubnetCapabilityRequest() {
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType("AN")
+ esrInfo.setVendor("ONAP")
+
+ JsonArray subnetTypes = new JsonArray()
+ subnetTypes.add("AN_NF")
+ JsonObject response = new JsonObject()
+ response.add("subnetCapabilityQuery", subnetTypes)
+ response.addProperty("esrInfo", objectMapper.writeValueAsString(esrInfo))
+ return response.toString()
+}
+public void createDomainWiseSliceProfiles(List<String> ranConstituentSliceProfiles, DelegateExecution execution) {
+
+ for(String profile : ranConstituentSliceProfiles) {
+ String domainType = jsonUtil.getJsonValue(profile, "domainType")
+ switch(domainType) {
+ case "AN_NF":
+ execution.setVariable("ranNfSliceProfile", profile)
+ break
+ case "TN_FH":
+ execution.setVariable("tnFhSliceProfile", profile)
+ break
+ case "TN_MH":
+ execution.setVariable("tnMhSliceProfile", profile)
+ break
+ default:
+ logger.debug("No expected match found for current domainType")
+ logger.error("No expected match found for current domainType "+ domainType)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current domainType "+ domainType)
+ }
+
+ }
+}
+
+public void createSliceProfilesInAai(DelegateExecution execution) {
+
+ org.onap.aai.domain.yang.ServiceInstance ANNF_sliceProfileInstance = new ServiceInstance();
+ org.onap.aai.domain.yang.ServiceInstance TNFH_sliceProfileInstance = new ServiceInstance();
+ org.onap.aai.domain.yang.ServiceInstance TNMH_sliceProfileInstance = new ServiceInstance();
+ //generate slice profile ids and slice profile instance ids
+ String ANNF_sliceProfileInstanceId = UUID.randomUUID().toString()
+ String ANNF_sliceProfileId = UUID.randomUUID().toString()
+ String TNFH_sliceProfileInstanceId = UUID.randomUUID().toString()
+ String TNFH_sliceProfileId = UUID.randomUUID().toString()
+ String TNMH_sliceProfileInstanceId = UUID.randomUUID().toString()
+ String TNMH_sliceProfileId = UUID.randomUUID().toString()
+ execution.setVariable("ANNF_sliceProfileInstanceId",ANNF_sliceProfileInstanceId)
+ execution.setVariable("ANNF_sliceProfileId",ANNF_sliceProfileId)
+ execution.setVariable("TNFH_sliceProfileInstanceId",TNFH_sliceProfileInstanceId)
+ execution.setVariable("TNFH_sliceProfileId",TNFH_sliceProfileId)
+ execution.setVariable("TNMH_sliceProfileInstanceId",TNMH_sliceProfileInstanceId)
+ execution.setVariable("TNMH_sliceProfileId",TNMH_sliceProfileId)
+ //slice profiles assignment
+ org.onap.aai.domain.yang.SliceProfiles ANNF_SliceProfiles = new SliceProfiles()
+ org.onap.aai.domain.yang.SliceProfiles TNFH_SliceProfiles = new SliceProfiles()
+ org.onap.aai.domain.yang.SliceProfiles TNMH_SliceProfiles = new SliceProfiles()
+ org.onap.aai.domain.yang.SliceProfile ANNF_SliceProfile = new SliceProfile()
+ org.onap.aai.domain.yang.SliceProfile TNFH_SliceProfile = new SliceProfile()
+ org.onap.aai.domain.yang.SliceProfile TNMH_SliceProfile = new SliceProfile()
+ ANNF_SliceProfile = createSliceProfile("AN-NF", execution)
+ TNFH_SliceProfile = createSliceProfile("TN-FH",execution)
+ TNMH_SliceProfile = createSliceProfile("TN-MH",execution)
+
+ ANNF_SliceProfiles.getSliceProfile().add(ANNF_SliceProfile)
+ TNFH_SliceProfiles.getSliceProfile().add(TNFH_SliceProfile)
+ TNMH_SliceProfiles.getSliceProfile().add(TNMH_SliceProfile)
+
+ logger.debug("sliceProfiles : 1. "+ANNF_SliceProfiles.toString()+"\n 2. "+TNFH_SliceProfiles.toString()+"\n 3. "+TNMH_SliceProfiles.toString())
+ //ANNF slice profile instance creation
+ ANNF_sliceProfileInstance.setServiceInstanceId(ANNF_sliceProfileInstanceId)
+ String sliceInstanceName = "sliceprofile_"+ANNF_sliceProfileId
+ ANNF_sliceProfileInstance.setServiceInstanceName(sliceInstanceName)
+ String serviceType = jsonUtil.getJsonValue(execution.getVariable("ranNfSliceProfile"), "sST")
+ ANNF_sliceProfileInstance.setServiceType(serviceType)
+ String serviceStatus = "deactivated"
+ ANNF_sliceProfileInstance.setOrchestrationStatus(serviceStatus)
+ String serviceInstanceLocationid = jsonUtil.getJsonValue(execution.getVariable("ranNfSliceProfile"), "plmnIdList")
+ ANNF_sliceProfileInstance.setServiceInstanceLocationId(serviceInstanceLocationid)
+ String serviceRole = "slice-profile-instance"
+ ANNF_sliceProfileInstance.setServiceRole(serviceRole)
+ List<String> snssaiList = objectMapper.readValue(execution.getVariable("snssaiList"), List.class)
+ String snssai = snssaiList.get(0)
+ ANNF_sliceProfileInstance.setEnvironmentContext(snssai)
+ ANNF_sliceProfileInstance.setWorkloadContext("AN-NF")
+ ANNF_sliceProfileInstance.setSliceProfiles(ANNF_SliceProfiles)
+ logger.debug("completed ANNF sliceprofileinstance build "+ ANNF_sliceProfileInstance.toString())
+ //TNFH slice profile instance creation
+ TNFH_sliceProfileInstance.setServiceInstanceId(TNFH_sliceProfileInstanceId)
+ sliceInstanceName = "sliceprofile_"+TNFH_sliceProfileId
+ TNFH_sliceProfileInstance.setServiceInstanceName(sliceInstanceName)
+ serviceType = jsonUtil.getJsonValue(execution.getVariable("tnFhSliceProfile"), "sST")
+ TNFH_sliceProfileInstance.setServiceType(serviceType)
+ TNFH_sliceProfileInstance.setOrchestrationStatus(serviceStatus)
+ serviceInstanceLocationid = jsonUtil.getJsonValue(execution.getVariable("tnFhSliceProfile"), "plmnIdList")
+ TNFH_sliceProfileInstance.setServiceInstanceLocationId(serviceInstanceLocationid)
+ TNFH_sliceProfileInstance.setServiceRole(serviceRole)
+ TNFH_sliceProfileInstance.setEnvironmentContext(snssai)
+ TNFH_sliceProfileInstance.setWorkloadContext("TN-FH")
+ TNFH_sliceProfileInstance.setSliceProfiles(TNFH_SliceProfiles)
+ logger.debug("completed TNFH sliceprofileinstance build "+TNFH_sliceProfileInstance)
+ //TNMH slice profile instance creation
+ TNMH_sliceProfileInstance.setServiceInstanceId(TNMH_sliceProfileInstanceId)
+ sliceInstanceName = "sliceprofile_"+TNMH_sliceProfileId
+ TNMH_sliceProfileInstance.setServiceInstanceName(sliceInstanceName)
+ serviceType = jsonUtil.getJsonValue(execution.getVariable("tnMhSliceProfile"), "sST")
+ TNMH_sliceProfileInstance.setServiceType(serviceType)
+ TNMH_sliceProfileInstance.setOrchestrationStatus(serviceStatus)
+ serviceInstanceLocationid = jsonUtil.getJsonValue(execution.getVariable("tnMhSliceProfile"), "plmnIdList")
+ TNMH_sliceProfileInstance.setServiceInstanceLocationId(serviceInstanceLocationid)
+ TNMH_sliceProfileInstance.setServiceRole(serviceRole)
+ TNMH_sliceProfileInstance.setEnvironmentContext(snssai)
+ TNMH_sliceProfileInstance.setWorkloadContext("TN-MH")
+ TNMH_sliceProfileInstance.setSliceProfiles(TNMH_SliceProfiles)
+ logger.debug("completed TNMH sliceprofileinstance build "+TNMH_sliceProfileInstance)
+ String msg = ""
+ try {
+
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri sliceProfileUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), ANNF_sliceProfileInstanceId)
+ client.create(sliceProfileUri, ANNF_sliceProfileInstance)
+
+ AAIResourceUri sliceProfileUri1 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), TNFH_sliceProfileInstanceId)
+ client.create(sliceProfileUri1, TNFH_sliceProfileInstance)
+
+ AAIResourceUri sliceProfileUri2 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), TNMH_sliceProfileInstanceId)
+ client.create(sliceProfileUri2, TNMH_sliceProfileInstance)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in AnNssmfUtils.createSliceProfilesInAai " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+}
+private SliceProfile createSliceProfile(String domainType, DelegateExecution execution) {
+
+ SliceProfile result = new SliceProfile()
+ Map<String,Object> profile
+ switch(domainType) {
+ case "AN-NF":
+ profile = objectMapper.readValue(execution.getVariable("ranNfSliceProfile"), Map.class)//pending fields - maxBandwidth, sST, pLMNIdList, cSReliabilityMeanTime,
+ //msgSizeByte, maxNumberofPDUSessions,overallUserDensity,transferIntervalTarget
+ result.setJitter(profile.get("jitter"))
+ result.setLatency(profile.get("latency"))
+ result.setResourceSharingLevel(profile.get("resourceSharingLevel"))
+ result.setSNssai(profile.get("sNSSAI"))
+ result.setUeMobilityLevel(profile.get("uEMobilityLevel"))
+ result.setMaxNumberOfUEs(profile.get("maxNumberofUEs"))
+ result.setActivityFactor(profile.get("activityFactor"))
+ result.setCoverageAreaTAList(profile.get("coverageAreaTAList"))
+ result.setCsAvailability(profile.get("cSAvailabilityTarget"))
+ result.setExpDataRateDL(profile.get("expDataRateDL"))
+ result.setExpDataRateUL(profile.get("expDataRateUL"))
+ result.setSurvivalTime(profile.get("survivalTime"))
+ result.setAreaTrafficCapDL(profile.get("areaTrafficCapDL"))
+ result.setAreaTrafficCapUL(profile.get("areaTrafficCapUL"))
+ result.setExpDataRate(profile.get("expDataRate"))
+ result.setProfileId(execution.getVariable("ANNF_sliceProfileId"))
+ break
+ case "TN-FH":
+ profile = objectMapper.readValue(execution.getVariable("tnFhSliceProfile"), Map.class) //pending fields - maxBandwidth, sST, pLMNIdList
+ result.setJitter(profile.get("jitter"))
+ result.setLatency(profile.get("latency"))
+ result.setResourceSharingLevel(profile.get("resourceSharingLevel"))
+ result.setSNssai(profile.get("sNSSAI"))
+ result.setProfileId(execution.getVariable("TNFH_sliceProfileId"))
+ break
+ case "TN-MH":
+ profile = objectMapper.readValue(execution.getVariable("tnMhSliceProfile"), Map.class)//pending fields - maxBandwidth, sST, pLMNIdList
+ result.setJitter(profile.get("jitter"))
+ result.setLatency(profile.get("latency"))
+ result.setResourceSharingLevel(profile.get("resourceSharingLevel"))
+ result.setSNssai(profile.get("sNSSAI"))
+ result.setProfileId(execution.getVariable("TNMH_sliceProfileId"))
+ break
+ default:
+ logger.debug("No expected match found for current domainType")
+ logger.error("No expected match found for current domainType "+ domainType)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current domainType "+ domainType)
+ }
+ return result
+}
+
+ /**
+ * create relationship in AAI
+ */
+ public createRelationShipInAAI = { DelegateExecution execution, final Relationship relationship, String instanceId ->
+ logger.debug("createRelationShipInAAI Start")
+ String msg
+ AAIResourcesClient client = new AAIResourcesClient()
+ try {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ instanceId).relationshipAPI()
+ client.create(uri, relationship)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in CreateCommunicationService.createRelationShipInAAI. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug("createRelationShipInAAI Exit")
+
+ }
+
+ public void processRanNfModifyRsp(DelegateExecution execution) {
+ String status = execution.getVariable("ranNfStatus")
+ if(status.equals("success")) {
+ logger.debug("completed Ran NF NSSI modification ... proceeding with the flow")
+ }
+ else {
+ logger.error("failed to modify ran Nf nssi")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1000, "modify ran nf nssi not successfull")
+ }
+ }
+
+ public String buildCreateNSSMFRequest(DelegateExecution execution, String domainType, String action) {
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType("TN")
+ esrInfo.setVendor("ONAP")
+ String esrInfoString = objectMapper.writeValueAsString(esrInfo)
+ JsonObject response = new JsonObject()
+ JsonObject allocateTnNssi = new JsonObject()
+ JsonObject serviceInfo = new JsonObject()
+ JsonArray transportSliceNetworksList = new JsonArray()
+ JsonArray connectionLinksList = new JsonArray()
+ JsonObject connectionLinks = new JsonObject()
+ if(action.equals("allocate")){
+ Map<String, String> endpoints
+ if(domainType.equals("TN_FH")) {
+ serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("TNFH_modelInvariantUuid"))
+ serviceInfo.addProperty("serviceUuid", execution.getVariable("TNFH_modelUuid"))
+ allocateTnNssi.addProperty("nsstId", execution.getVariable("TNFH_modelUuid"))
+ allocateTnNssi.addProperty("nssiName", execution.getVariable("TNFH_modelName"))
+ Map<String,Object> sliceProfile = objectMapper.readValue(execution.getVariable("tnFhSliceProfile"), Map.class)
+ sliceProfile.put("sliceProfileId", execution.getVariable("TNFH_sliceProfileInstanceId"))
+ String sliceProfileString = objectMapper.writeValueAsString(sliceProfile)
+ allocateTnNssi.addProperty("sliceProfile", sliceProfileString)
+ endpoints.put("transportEndpointA", execution.getVariable("tranportEp_ID_RU"))
+ endpoints.put("transportEndpointB", execution.getVariable("tranportEp_ID_DUIN"))
+ String endpointsString = objectMapper.writeValueAsString(endpoints)
+ connectionLinksList.add(endpointsString)
+ }else if(domainType.equals("TN_MH")) {
+ serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("TNMH_modelInvariantUuid"))
+ serviceInfo.addProperty("serviceUuid", execution.getVariable("TNMH_modelUuid"))
+ allocateTnNssi.addProperty("nsstId", execution.getVariable("TNMH_modelUuid"))
+ allocateTnNssi.addProperty("nssiName", execution.getVariable("TNMH_modelName"))
+ Map<String,Object> sliceProfile = objectMapper.readValue(execution.getVariable("tnMhSliceProfile"), Map.class)
+ sliceProfile.put("sliceProfileId", execution.getVariable("TNMH_sliceProfileInstanceId"))
+ String sliceProfileString = objectMapper.writeValueAsString(sliceProfile)
+ allocateTnNssi.addProperty("sliceProfile", sliceProfileString)
+ endpoints.put("transportEndpointA", execution.getVariable("tranportEp_ID_DUEG"))
+ endpoints.put("transportEndpointB", execution.getVariable("tranportEp_ID_CUIN"))
+ String endpointsString = objectMapper.writeValueAsString(endpoints)
+ connectionLinksList.add(endpointsString)
+ }
+
+ //Connection links
+ connectionLinks.add("connectionLinks", connectionLinksList)
+ transportSliceNetworksList.add(connectionLinks)
+ allocateTnNssi.add("transportSliceNetworks", transportSliceNetworksList)
+ allocateTnNssi.addProperty("nssiId", null)
+ serviceInfo.addProperty("nssiId", null)
+ }else if(action.equals("modify-allocate")) {
+ if(domainType.equals("TN_FH")) {
+ serviceInfo.addProperty("serviceInvariantUuid", null)
+ serviceInfo.addProperty("serviceUuid", null)
+ allocateTnNssi.addProperty("nsstId", null)
+ allocateTnNssi.addProperty("nssiName", execution.getVariable("TNFH_nssiName"))
+ allocateTnNssi.addProperty("sliceProfileId", execution.getVariable("TNFH_sliceProfileInstanceId"))
+ allocateTnNssi.addProperty("nssiId", execution.getVariable("TNFH_NSSI"))
+ serviceInfo.addProperty("nssiId", execution.getVariable("TNFH_NSSI"))
+ }else if(domainType.equals("TN_MH")) {
+ serviceInfo.addProperty("serviceInvariantUuid", null)
+ serviceInfo.addProperty("serviceUuid", null)
+ allocateTnNssi.addProperty("nsstId", null)
+ allocateTnNssi.addProperty("nssiName", execution.getVariable("TNMH_nssiName"))
+ allocateTnNssi.addProperty("sliceProfileId", execution.getVariable("TNMH_sliceProfileInstanceId"))
+ allocateTnNssi.addProperty("nssiId", execution.getVariable("TNMH_NSSI"))
+ serviceInfo.addProperty("nssiId", execution.getVariable("TNMH_NSSI"))
+ }
+ }
+ String nsiInfo = jsonUtil.getJsonValue(execution.getVariable("sliceParams"), "nsiInfo")
+ allocateTnNssi.addProperty("nsiInfo", nsiInfo)
+ allocateTnNssi.addProperty("scriptName", "TN1")
+ serviceInfo.addProperty("nsiId", execution.getVariable("nsiId"))
+ serviceInfo.addProperty("globalSubscriberId", execution.getVariable("globalSubscriberId"))
+ serviceInfo.addProperty("subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
+ response.addProperty("esrInfo", esrInfoString)
+ response.add("serviceInfo", serviceInfo)
+ response.add("allocateTnNssi", allocateTnNssi)
+ return response.toString()
+ }
+
+ public String buildDeallocateNssiRequest(DelegateExecution execution,String domainType) {
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ JsonObject deAllocateNssi = new JsonObject()
+ deAllocateNssi.addProperty("snssaiList", execution.getVariable("snssaiList"))
+ deAllocateNssi.addProperty("nsiId", execution.getVariable("nsiId"))
+ deAllocateNssi.addProperty("modifyAction", true)
+ deAllocateNssi.addProperty("terminateNssiOption", 0)
+ deAllocateNssi.addProperty("scriptName", "TN1")
+
+ if(domainType.equals("TN_FH")) {
+ deAllocateNssi.addProperty("nssiId", execution.getVariable("TNFH_NSSI"))
+ deAllocateNssi.addProperty("sliceProfileId", execution.getVariable("TNFH_sliceProfileInstanceId"))
+ }else if(domainType.equals("TN_MH")) {
+ deAllocateNssi.addProperty("nssiId", execution.getVariable("TNMH_NSSI"))
+ deAllocateNssi.addProperty("sliceProfileId", execution.getVariable("TNMH_sliceProfileInstanceId"))
+ }
+
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setVendor("ONAP")
+ esrInfo.setNetworkType("TN")
+
+ JsonObject serviceInfo = new JsonObject()
+ serviceInfo.addProperty("serviceInvariantUuid", null)
+ serviceInfo.addProperty("serviceUuid", null)
+ serviceInfo.addProperty("globalSubscriberId", globalSubscriberId)
+ serviceInfo.addProperty("subscriptionServiceType", subscriptionServiceType)
+
+ JsonObject json = new JsonObject()
+ json.add("deAllocateNssi", deAllocateNssi)
+ json.addProperty("esrInfo", objectMapper.writeValueAsString(esrInfo))
+ json.add("serviceInfo", serviceInfo)
+ return json.toString()
+
+ }
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCommunicationService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCommunicationService.groovy
index 12cd0dde0b..f8eafe7e98 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCommunicationService.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCommunicationService.groovy
@@ -184,7 +184,7 @@ class CreateCommunicationService extends AbstractServiceTaskProcessor {
logger.debug(Prefix + "prepareInitOperationStatus Start")
String serviceId = execution.getVariable("serviceInstanceId")
- // 生成 operationId
+ //operationId is generated
String operationId = execution.getVariable("operationId")
logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId)
@@ -370,20 +370,23 @@ class CreateCommunicationService extends AbstractServiceTaskProcessor {
for (String e2eInput in e2eInputs) {
- if (jsonUtil.getJsonValue(e2eInput, "type") == "integer") {
+ key = jsonUtil.getJsonValue(e2eInput, "name")
+ String type = jsonUtil.getJsonValue(e2eInput, "type")
+ if (type == "integer") {
def temp
- key = jsonUtil.getJsonValue(e2eInput, "name")
value = csInputMap.containsKey(key) ? csInputMap.getOrDefault(key, 0) : (isBlank(temp = jsonUtil.getJsonValue(e2eInput, "default")) ? 0 : temp)
e2eInputMap.put(key, value as Integer)
- } else {
- e2eInputMap.put(key = jsonUtil.getJsonValue(e2eInput, "name"), csInputMap.containsKey(key)
+ } else if(type == "string") {
+ e2eInputMap.put(key, csInputMap.containsKey(key)
? csInputMap.getOrDefault(key, null) : (jsonUtil.getJsonValue(e2eInput, "default")))
+
}
}
+ //TODO
e2eInputMap.put("sNSSAI", execution.getVariable("sNSSAI_id"))
- e2eInputMap.put("sST", execution.getVariable("csServiceType"))
+ e2eInputMap.put("sST", execution.getVariable("csServiceType"))
execution.setVariable("e2eInputMap", e2eInputMap)
execution.setVariable("e2eServiceType", e2eServiceDecomposition.getServiceType())
execution.setVariable("e2eModelInvariantUuid", e2eServiceDecomposition.getModelInfo().getModelInvariantUuid())
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 15a0f34482..342fce75a5 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
@@ -2,19 +2,19 @@
* ============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.
+ # Copyright (c) 2020, 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=========================================================
*/
@@ -22,21 +22,22 @@ package org.onap.so.bpmn.infrastructure.scripts
import com.fasterxml.jackson.databind.ObjectMapper
import org.onap.aai.domain.yang.ServiceInstance
-import org.onap.so.client.HttpClient
-import org.onap.so.client.HttpClientFactory
import org.onap.aaiclient.client.aai.AAIObjectType
import org.onap.aaiclient.client.aai.AAIResourcesClient
import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
-
-import javax.ws.rs.core.Response
+import org.onap.so.beans.nsmf.EsrInfo
+import org.onap.so.beans.nsmf.NssmfAdapterNBIRequest
+import org.onap.so.beans.nsmf.SliceTaskParamsAdapter
+import org.onap.so.beans.nsmf.oof.TemplateInfo
+import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
import static org.apache.commons.lang3.StringUtils.*
import org.springframework.web.util.UriUtils
import groovy.json.JsonSlurper
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.SliceTaskParams
import org.onap.so.db.request.beans.OrchestrationTask
import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
@@ -59,8 +60,10 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
JsonSlurper jsonSlurper = new JsonSlurper()
ObjectMapper objectMapper = new ObjectMapper()
OofUtils oofUtils = new OofUtils()
- private static final Logger logger = LoggerFactory.getLogger(CreateSliceService.class)
+ NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
+ AAIResourcesClient client = getAAIClient()
+ private static final Logger logger = LoggerFactory.getLogger(CreateSliceService.class)
public void preProcessRequest(DelegateExecution execution) {
logger.debug("Start preProcessRequest")
@@ -150,7 +153,7 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
logger.debug("User Input Parameters map: " + inputMap.toString())
String uuiRequest = inputMap.get("UUIRequest")
- Map uuiReqMap = jsonSlurper.parseText(uuiRequest)
+ Map uuiReqMap = jsonSlurper.parseText(uuiRequest) as Map
Map<String, Object> serviceObject = (Map<String, Object>) uuiReqMap.get("service")
Map<String, Object> parameterObject = (Map<String, Object>) serviceObject.get("parameters")
Map<String, Object> requestInputs = (Map<String, Object>) parameterObject.get("requestInputs")
@@ -162,7 +165,8 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
execution.setVariable("serviceInputParams", inputMap)
execution.setVariable("uuiRequest", uuiRequest)
- execution.setVariable("serviceProfile", serviceProfile)
+ execution.setVariable("se" +
+ "rviceProfile", serviceProfile)
//TODO
//execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams"))
@@ -178,100 +182,69 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
logger.debug("Finish preProcessRequest")
}
- public void getNSTSelection(DelegateExecution execution) {
- logger.debug("Start getNSTSelection")
- String requestId = execution.getVariable("msoRequestId")
- Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
- String oofUrl = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
-
- 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")
- }
-
- URL requestUrl = new URL(oofUrl + "/api/oof/v1/selection/nst")
- String oofRequest = oofUtils.buildSelectNSTRequest(requestId, serviceProfile)
- HttpClient httpClient = new HttpClientFactory().newJsonClient(requestUrl, ONAPComponents.OOF)
- httpClient.addAdditionalHeader("Authorization", authHeader)
- Response httpResponse = httpClient.post(oofRequest)
+ /**
+ *
+ * @param execution
+ */
+ public void prepareInitServiceOperationStatus(DelegateExecution execution) {
+ logger.debug("Start prepareInitServiceOperationStatus")
+ try{
+ String serviceId = execution.getVariable("serviceInstanceId")
+ String operationId = execution.getVariable("operationId")
+ String operationType = "CREATE"
+ String userId = execution.getVariable("globalSubscriberId")
+ String result = "processing"
+ String progress = "0"
+ String reason = ""
+ String operationContent = "Prepare service creation"
+ logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId)
+ serviceId = UriUtils.encode(serviceId,"UTF-8")
+ execution.setVariable("serviceInstanceId", serviceId)
+ execution.setVariable("operationType", operationType)
- int responseCode = httpResponse.getStatus()
- logger.debug("OOF sync response code is: " + responseCode)
+ def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint",execution)
+ execution.setVariable("CSSOS_dbAdapterEndpoint", dbAdapterEndpoint)
+ logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
+ def dbAdapterAuth = UrnPropertiesReader.getVariable("mso.requestDb.auth")
+ Map<String, String> CSSOS_headerMap = [:]
+ CSSOS_headerMap.put("content-type", "application/soap+xml")
+ CSSOS_headerMap.put("Authorization", dbAdapterAuth)
+ execution.setVariable("CSSOS_headerMap", CSSOS_headerMap)
+ logger.debug("DB Adapter Header is: " + CSSOS_headerMap)
- if(responseCode != 200){
- exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
- }
+ 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>"""
- Map<String, Object> nstSolution
- try {
- Map<String, Object> resMap = httpResponse.readEntity(Map.class)
- List<Map<String, Object>> nstSolutions = (List<Map<String, Object>>) resMap.get("solutions")
- nstSolution = nstSolutions.get(0)
- execution.setVariable("nstSolution", nstSolution)
- } catch (Exception ex) {
- logger.debug( "Failed to get NST solution suggested by OOF.")
- exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Failed to get NST solution suggested by OOF.")
+ payload = utils.formatXml(payload)
+ execution.setVariable("CSSOS_updateServiceOperStatusRequest", payload)
+ logger.debug("Outgoing updateServiceOperStatusRequest: \n" + payload)
+ }catch(Exception e){
+ logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
+ "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN",
+ ErrorCode.UnknownError.getValue(), "Exception is:\n" + e)
}
-
- logger.debug("Finish getNSTSelection")
-
- }
-
- public void prepareDecomposeService(DelegateExecution execution) {
- logger.debug("Start prepareDecomposeService")
- String uuiRequest = execution.getVariable("uuiRequest")
- String ssModelInvariantUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceInvariantUuid")
- String ssModelUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceUuid")
- String ssServiceModelInfo = """{
- "modelInvariantUuid":"${ssModelInvariantUuid}",
- "modelUuid":"${ssModelUuid}",
- "modelVersion":""
- }"""
- execution.setVariable("ssServiceModelInfo", ssServiceModelInfo)
-
- logger.debug("Finish prepareDecomposeService")
- }
-
- public void processDecomposition(DelegateExecution execution) {
- logger.debug("Start processDecomposition")
- String uuiRequest = execution.getVariable("uuiRequest")
- Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
- Map<String, Object> nstSolution = execution.getVariable("nstSolution")
-
- Map uuiReqMap = jsonSlurper.parseText(uuiRequest)
- Map<String, Object> serviceObject = (Map<String, Object>) uuiReqMap.get("service")
- String subscriptionServiceType = serviceObject.get("serviceType")
-
- String serviceType = (String) serviceProfile.get("sST")
- String resourceSharingLevel = (String) serviceProfile.get("resourceSharingLevel")
- String nstModelUuid = (String) nstSolution.get("UUID")
- String nstModelInvariantUuid = (String) nstSolution.get("invariantUUID")
-
- execution.setVariable("subscriptionServiceType", subscriptionServiceType)
- execution.setVariable("serviceType", serviceType)
- execution.setVariable("resourceSharingLevel", resourceSharingLevel)
- execution.setVariable("nstModelUuid", nstModelUuid)
- execution.setVariable("nstModelInvariantUuid", nstModelInvariantUuid)
-
- logger.debug("Finish processDecomposition")
+ logger.debug("Finish prepareInitServiceOperationStatus")
}
+ /**
+ * prepare create OrchestrationTask
+ * @param execution
+ */
public void prepareCreateOrchestrationTask(DelegateExecution execution) {
logger.debug("Start createOrchestrationTask")
String taskId = execution.getBusinessKey()
@@ -289,21 +262,104 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
execution.setVariable("CSSOT_isManual", isManual)
execution.setVariable("CSSOT_requestMethod", requestMethod)
- Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
+ Map<String, Object> serviceProfile = execution.getVariable("serviceProfile") as Map<String, Object>
- SliceTaskParams sliceTaskParams = new SliceTaskParams()
+ SliceTaskParamsAdapter sliceTaskParams = new SliceTaskParamsAdapter()
sliceTaskParams.setServiceId(serviceInstanceId)
sliceTaskParams.setServiceName(serviceInstanceName)
sliceTaskParams.setServiceProfile(serviceProfile)
+
execution.setVariable("sliceTaskParams", sliceTaskParams)
- String paramJson = sliceTaskParams.convertToJson()
- execution.setVariable("CSSOT_paramJson", paramJson)
- logger.debug("CSSOT_paramJson: " + paramJson)
+ //todo:----------------------------------------
+// String paramJson = sliceTaskParams.convertToJson()
+// execution.setVariable("CSSOT_paramJson", paramJson)
+ /*-------------------------------------------*/
logger.debug("Finish createOrchestrationTask")
}
+ /**
+ * send sync response to csmf
+ * @param execution
+ */
+ public void sendSyncResponse(DelegateExecution execution) {
+ logger.debug("Start sendSyncResponse")
+ try {
+ String operationId = execution.getVariable("operationId")
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ // RESTResponse for API Handler (APIH) Reply Task
+ String createServiceRestRequest = """
+ {
+ "service": {
+ "serviceId":"${serviceInstanceId}",
+ "operationId":"${operationId}"
+ }
+ }
+ """.trim()
+
+ logger.debug("sendSyncResponse to APIH:" + "\n" + createServiceRestRequest)
+ sendWorkflowResponse(execution, 202, createServiceRestRequest)
+ execution.setVariable("sentSyncResponse", true)
+ } catch (Exception e) {
+ String msg = "Exceptuion in sendSyncResponse:" + e.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug("Finish sendSyncResponse")
+ }
+
+ public void prepareSelectNSTRequest(DelegateExecution execution) {
+ logger.debug("Start prepareSelectNSTRequest")
+ String requestId = execution.getVariable("msoRequestId")
+ String messageType = "NSTSelectionResponse"
+ Map<String, Object> serviceProfile = execution.getVariable("serviceProfile") as Map<String, Object>
+ execution.setVariable("nstSelectionUrl", "/api/oof/v1/selection/nst")
+ execution.setVariable("nstSelection_messageType", messageType)
+ execution.setVariable("nstSelection_correlator", requestId)
+ String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
+ execution.setVariable("nstSelection_timeout", timeout)
+ String oofRequest = oofUtils.buildSelectNSTRequest(requestId, messageType, serviceProfile)
+ execution.setVariable("nstSelection_oofRequest", oofRequest)
+ logger.debug("Finish prepareSelectNSTRequest")
+
+ }
+
+ /**
+ * process async response of oof, put the {@solutions} at {@nstSolution}
+ * @param execution
+ */
+ public void processNSTSolutions(DelegateExecution execution) {
+ Map<String, Object> nstSolution
+ try {
+ logger.debug("Start processing NSTSolutions")
+ Map<String, Object> resMap =
+ objectMapper.readValue(execution.getVariable("nstSelection_oofResponse") as String,
+ Map.class)
+
+ List<Map<String, Object>> nstSolutions = (List<Map<String, Object>>) resMap.get("solutions")
+ nstSolution = nstSolutions.get(0)
+ execution.setVariable("nstSolution", nstSolution)
+
+ //set nst info into sliceTaskParams
+ SliceTaskParamsAdapter sliceTaskParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+ TemplateInfo nstInfo = new TemplateInfo()
+ nstInfo.setUUID(nstSolution.get("UUID") as String)
+ nstInfo.setInvariantUUID(nstSolution.get("invariantUUID") as String)
+ nstInfo.setName(nstSolution.get("name") as String)
+
+ sliceTaskParams.setNSTInfo(nstInfo)
+
+ execution.setVariable("sliceTaskParams", sliceTaskParams)
+
+ } catch (Exception ex) {
+ logger.debug( "Failed to get NST solution suggested by OOF.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Failed to get NST solution suggested by OOF.")
+ }
+
+ }
+
public void prepareUpdateOrchestrationTask(DelegateExecution execution) {
logger.debug("Start prepareUpdateOrchestrationTask")
String requestMethod = "PUT"
@@ -316,6 +372,7 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
logger.debug("Finish prepareUpdateOrchestrationTask")
}
+
public void prepareGetUserOptions(DelegateExecution execution) {
logger.debug("Start prepareGetUserOptions")
String requestMethod = "GET"
@@ -349,7 +406,7 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
String orchStatus = execution.getVariable("orchestrationStatus")
try {
- ServiceInstance si = ServiceInstance si = new ServiceInstance()
+ ServiceInstance si = new ServiceInstance()
si.setOrchestrationStatus(orchStatus)
AAIResourcesClient client = new AAIResourcesClient()
AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)
@@ -365,61 +422,6 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
logger.debug("Finish updateAAIOrchStatus")
}
- public void prepareInitServiceOperationStatus(DelegateExecution execution) {
- logger.debug("Start prepareInitServiceOperationStatus")
- try{
- String serviceId = execution.getVariable("serviceInstanceId")
- String operationId = execution.getVariable("operationId")
- String operationType = "CREATE"
- String userId = execution.getVariable("globalSubscriberId")
- String result = "processing"
- String progress = "0"
- String reason = ""
- String operationContent = "Prepare service creation"
- logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId)
- serviceId = UriUtils.encode(serviceId,"UTF-8")
- execution.setVariable("serviceInstanceId", serviceId)
- execution.setVariable("operationType", operationType)
-
- def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint",execution)
- execution.setVariable("CSSOS_dbAdapterEndpoint", dbAdapterEndpoint)
- logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
- def dbAdapterAuth = UrnPropertiesReader.getVariable("mso.requestDb.auth")
- Map<String, String> CSSOS_headerMap = [:]
- CSSOS_headerMap.put("content-type", "application/soap+xml")
- CSSOS_headerMap.put("Authorization", dbAdapterAuth)
- execution.setVariable("CSSOS_headerMap", CSSOS_headerMap)
- logger.debug("DB Adapter Header is: " + CSSOS_headerMap)
-
- 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("CSSOS_updateServiceOperStatusRequest", payload)
- logger.debug("Outgoing updateServiceOperStatusRequest: \n" + payload)
- }catch(Exception e){
- logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
- "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN",
- ErrorCode.UnknownError.getValue(), "Exception is:\n" + e)
- }
- logger.debug("Finish prepareInitServiceOperationStatus")
- }
-
public void prepareUpdateServiceOperationStatus(DelegateExecution execution) {
logger.debug("Start preUpdateServiceOperationStatus")
try{
@@ -462,23 +464,7 @@ public class CreateSliceService extends AbstractServiceTaskProcessor {
logger.debug("Finish preUpdateServiceOperationStatus")
}
- public void sendSyncResponse(DelegateExecution execution) {
- logger.debug("Start sendSyncResponse")
- try {
- String operationId = execution.getVariable("operationId")
- String serviceInstanceId = execution.getVariable("serviceInstanceId")
- // RESTResponse for API Handler (APIH) Reply Task
- String createServiceRestRequest = """{"service":{"serviceId":"${serviceInstanceId}","operationId":"${operationId}"}}""".trim()
- logger.debug("sendSyncResponse to APIH:" + "\n" + createServiceRestRequest)
- sendWorkflowResponse(execution, 202, createServiceRestRequest)
- execution.setVariable("sentSyncResponse", true)
- } catch (Exception e) {
- String msg = "Exceptuion in sendSyncResponse:" + e.getMessage()
- logger.debug(msg)
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
- }
- logger.debug("Finish sendSyncResponse")
- }
+
public void prepareCompletionRequest (DelegateExecution execution) {
logger.trace("Start prepareCompletionRequest")
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeAllocateSliceSubnet.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeAllocateSliceSubnet.groovy
new file mode 100644
index 0000000000..964baa7a9d
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeAllocateSliceSubnet.groovy
@@ -0,0 +1,170 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, Wipro Limited.
+ #
+ # 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.delegate.BpmnError
+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.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class DeAllocateSliceSubnet extends AbstractServiceTaskProcessor {
+ String Prefix="DeASS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+
+ private static final Logger logger = LoggerFactory.getLogger(DeAllocateSliceSubnet.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix + "preProcessRequest Start")
+ execution.setVariable("prefix", Prefix)
+ execution.setVariable("startTime", System.currentTimeMillis())
+ def msg
+ try {
+ // get request input
+ String subnetInstanceReq = execution.getVariable("bpmnRequest")
+ logger.debug(subnetInstanceReq)
+
+ String requestId = execution.getVariable("mso-request-id")
+ execution.setVariable("msoRequestId", requestId)
+ logger.debug("Input Request:" + subnetInstanceReq + " reqId:" + requestId)
+
+ //subscriberInfo
+ String globalSubscriberId = jsonUtil.getJsonValue(subnetInstanceReq, "globalSubscriberId")
+ if (isBlank(globalSubscriberId)) {
+ msg = "Input globalSubscriberId' is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("globalSubscriberId", globalSubscriberId)
+ }
+
+ //NSSI ID
+ String serviceInstanceID = jsonUtil.getJsonValue(subnetInstanceReq, "serviceInstanceID")
+ if (isBlank(serviceInstanceID)) {
+ msg = "Input serviceInstanceID is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("serviceInstanceID", serviceInstanceID)
+ }
+
+ String nsiId = jsonUtil.getJsonValue(subnetInstanceReq, "additionalProperties.nsiId")
+ if (isBlank(nsiId)) {
+ msg = "Input nsiId is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("nsiId", nsiId)
+ }
+
+ String networkType = jsonUtil.getJsonValue(subnetInstanceReq, "networkType")
+ if (isBlank(networkType)) {
+ msg = "Input networkType is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("networkType", networkType.toUpperCase())
+ }
+
+ //requestParameters, subscriptionServiceType is 5G
+ String subscriptionServiceType = jsonUtil.getJsonValue(subnetInstanceReq, "subscriptionServiceType")
+ if (isBlank(subscriptionServiceType)) {
+ msg = "Input subscriptionServiceType is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("subscriptionServiceType", subscriptionServiceType)
+ }
+
+ String jobId = UUID.randomUUID().toString()
+ execution.setVariable("jobId", jobId)
+
+ String sliceParams = jsonUtil.getJsonValue(subnetInstanceReq, "additionalProperties")
+ execution.setVariable("sliceParams", sliceParams)
+
+ } catch(BpmnError e) {
+ throw e
+ } catch(Exception ex) {
+ msg = "Exception in DeAllocateSliceSubnet.preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "preProcessRequest Exit")
+ }
+
+
+ /**
+ * create operation status in request db
+ *
+ * Init the Operation Status
+ */
+ def prepareInitOperationStatus = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareInitOperationStatus Start")
+
+ String serviceId = execution.getVariable("serviceInstanceID")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ logger.debug("Generated new job for Service Instance serviceId:" + serviceId + " jobId:" + jobId)
+
+ ResourceOperationStatus initStatus = new ResourceOperationStatus()
+ initStatus.setServiceId(serviceId)
+ initStatus.setOperationId(jobId)
+ initStatus.setResourceTemplateUUID(nsiId)
+ initStatus.setOperType("Deallocate")
+ requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
+
+ logger.debug(Prefix + "prepareInitOperationStatus Exit")
+ }
+
+
+
+ /**
+ * return sync response
+ */
+ def sendSyncResponse = { DelegateExecution execution ->
+ logger.debug(Prefix + "sendSyncResponse Start")
+ try {
+ String jobId = execution.getVariable("jobId")
+ String deAllocateSyncResponse = """{"jobId": "${jobId}","status": "processing"}""".trim().replaceAll(" ", "")
+
+ logger.debug("sendSyncResponse to APIH:" + "\n" + deAllocateSyncResponse)
+ sendWorkflowResponse(execution, 202, deAllocateSyncResponse)
+
+ execution.setVariable("sentSyncResponse", true)
+ } catch (Exception ex) {
+ String msg = "Exception in sendSyncResponse:" + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "sendSyncResponse Exit")
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateAccessNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateAccessNSSI.groovy
new file mode 100644
index 0000000000..4d86fb4cd9
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateAccessNSSI.groovy
@@ -0,0 +1,589 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Wipro Limited. 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 static org.apache.commons.lang3.StringUtils.isBlank
+
+import javax.ws.rs.NotFoundException
+
+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.ServiceInstance
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.beans.nsmf.ActDeActNssi
+import org.onap.so.beans.nsmf.EsrInfo
+import org.onap.so.beans.nsmf.ServiceInfo
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.google.gson.JsonObject
+
+/**
+ * Internal AN NSSMF to handle NSSI Activation/Deactivation
+ *
+ */
+class DoActivateAccessNSSI extends AbstractServiceTaskProcessor {
+
+ String Prefix="DoActivateAccessNSSI"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ ObjectMapper objectMapper = new ObjectMapper()
+ private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
+
+ private static final Logger logger = LoggerFactory.getLogger(DoActivateAccessNSSI.class)
+ private static final String ROLE_SLICE_PROFILE = "slice-profile-instance"
+ private static final String ROLE_NSSI = "nssi"
+
+ private static final String KEY_SLICE_PROFILE = "SliceProfile"
+ private static final String KEY_NSSI = "NSSI"
+
+ private static final String AN_NF = "AN-NF"
+ private static final String TN_FH = "TN-FH"
+ private static final String TN_MH = "TN-MH"
+
+ private static final String ACTIVATE = "activateInstance"
+ private static final String DEACTIVATE = "deactivateInstance"
+
+ private static final String VENDOR_ONAP = "ONAP"
+
+ Map<String,String> orchStatusMap = new HashMap<>()
+
+ @Override
+ public void preProcessRequest(DelegateExecution execution) {
+ logger.debug("${Prefix} - Start preProcessRequest")
+
+ String sliceParams = execution.getVariable("sliceParams")
+ String sNssaiList = jsonUtil.getJsonValue(sliceParams, "snssaiList")
+ String anSliceProfileId = jsonUtil.getJsonValue(sliceParams, "sliceProfileId")
+ String nsiId = execution.getVariable("nsiId")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ String anNssiId = execution.getVariable("serviceInstanceID")
+ String operationType = execution.getVariable("operationType")
+
+ if(isBlank(sNssaiList) || isBlank(anSliceProfileId) || isBlank(nsiId)) {
+ String msg = "Input fields cannot be null : Mandatory attributes : [snssaiList, sliceProfileId, nsiId]"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ if( isBlank(anNssiId) || isBlank(globalSubscriberId) || isBlank(subscriptionServiceType) || isBlank(operationType)) {
+ String msg = "Missing Input fields from main process : [serviceInstanceID, globalSubscriberId, subscriptionServiceType, operationType]"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ execution.setVariable("sNssaiList", sNssaiList)
+ execution.setVariable("anSliceProfileId", anSliceProfileId)
+ execution.setVariable("nsiId", nsiId)
+ execution.setVariable("anNssiId", anNssiId)
+
+ orchStatusMap.put(ACTIVATE, "activated")
+ orchStatusMap.put(DEACTIVATE, "deactivated")
+
+ logger.debug("${Prefix} - Preprocessing completed with sliceProfileId : ${anSliceProfileId} , nsiId : ${nsiId} , nssiId : ${anNssiId}")
+
+ }
+
+ /**
+ * Method to fetch AN NSSI Constituents and Slice Profile constituents
+ * @param execution
+ */
+ void getRelatedInstances(DelegateExecution execution) {
+ logger.debug("${Prefix} - Get Related Instances")
+ String anSliceProfileId = execution.getVariable("anSliceProfileId")
+ String anNssiId = execution.getVariable("anNssiId")
+
+ Map<String,ServiceInstance> relatedSPs = new HashMap<>()
+ execution.setVariable("relatedSPs", getRelatedInstancesByRole(execution, ROLE_SLICE_PROFILE,KEY_SLICE_PROFILE, anSliceProfileId))
+
+ Map<String,ServiceInstance> relatedNssis = new HashMap<>()
+ execution.setVariable("relatedNssis", getRelatedInstancesByRole(execution, ROLE_NSSI,KEY_NSSI, anNssiId))
+ logger.trace("${Prefix} - Exit Get Related instances")
+ }
+
+ /**
+ * Method to check Slice profile orchestration status
+ * @param execution
+ */
+ void getSPOrchStatus(DelegateExecution execution) {
+ logger.debug("${Prefix} - Start getSPOrchStatus")
+ ServiceInstance sliceProfileInstance = execution.getVariable(KEY_SLICE_PROFILE)
+ String orchStatus = sliceProfileInstance.getOrchestrationStatus()
+ String operationType = execution.getVariable("operationType")
+ if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
+ execution.setVariable("shouldChangeSPStatus", true)
+ }else {
+ execution.setVariable("shouldChangeSPStatus", false)
+ }
+ logger.debug("${Prefix} - SPOrchStatus : ${orchStatus}")
+ }
+
+ /**
+ * Method to check AN NF's Slice profile instance orchestration status
+ * @param execution
+ */
+ void getAnNfSPOrchStatus(DelegateExecution execution) {
+ logger.debug("${Prefix} - getAnNfSPOrchStatus ")
+ ServiceInstance sliceProfileInstance = getInstanceByWorkloadContext(execution.getVariable("relatedSPs"), AN_NF)
+ String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
+ execution.setVariable("anNfNssiId", anNfNssiId)
+ String anNfSPId = sliceProfileInstance.getServiceInstanceId()
+ execution.setVariable("anNfSPId", anNfSPId)
+
+ String orchStatus = sliceProfileInstance.getOrchestrationStatus()
+ String operationType = execution.getVariable("operationType")
+ if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
+ execution.setVariable("shouldChangeAN_NF_SPStatus", true)
+ }else {
+ execution.setVariable("shouldChangeAN_NF_SPStatus", false)
+ }
+ logger.debug("${Prefix} - getAnNfSPOrchStatus AN_NF SP ID:${anNfSPId} : ${orchStatus}")
+ }
+
+ void prepareSdnrActivationRequest(DelegateExecution execution) {
+ logger.debug("${Prefix} - start prepareSdnrActivationRequest")
+ String operationType = execution.getVariable("operationType")
+ String action = operationType.equalsIgnoreCase(ACTIVATE) ? "activate":"deactivate"
+
+ String anNfNssiId = execution.getVariable("anNfNssiId")
+ String sNssai = execution.getVariable("sNssaiList")
+ String reqId = execution.getVariable("msoRequestId")
+ String messageType = "SDNRActivateResponse"
+ StringBuilder callbackURL = new StringBuilder(UrnPropertiesReader.getVariable("mso.workflow.message.endpoint", execution))
+ callbackURL.append("/").append(messageType).append("/").append(reqId)
+
+ JsonObject input = new JsonObject()
+ input.addProperty("RANNFNSSIId", anNfNssiId)
+ input.addProperty("callbackURL", callbackURL.toString())
+ input.addProperty("s-NSSAI", sNssai)
+
+ JsonObject Payload = new JsonObject()
+ Payload.addProperty("version", "1.0")
+ Payload.addProperty("rpc-name", "activateRANSlice")
+ Payload.addProperty("correlation-id", reqId)
+ Payload.addProperty("type", "request")
+
+ JsonObject wrapinput = new JsonObject()
+ wrapinput.addProperty("Action", action)
+
+ JsonObject CommonHeader = new JsonObject()
+ CommonHeader.addProperty("TimeStamp", new Date(System.currentTimeMillis()).format("yyyy-MM-ddTHH:mm:ss.sss", TimeZone.getDefault()))
+ CommonHeader.addProperty("APIver", "1.0")
+ CommonHeader.addProperty("RequestID", reqId)
+ CommonHeader.addProperty("SubRequestID", "1")
+
+ JsonObject body = new JsonObject()
+ body.add("input", wrapinput)
+
+ JsonObject sdnrRequest = new JsonObject()
+ Payload.add("input", input)
+ wrapinput.add("Payload", Payload)
+ wrapinput.add("CommonHeader", CommonHeader)
+ body.add("input", wrapinput)
+ sdnrRequest.add("body", body)
+
+ String json = sdnrRequest.toString()
+ execution.setVariable("sdnrRequest", sdnrRequest)
+ execution.setVariable("SDNR_messageType", messageType)
+ execution.setVariable("SDNR_timeout", "PT10M")
+
+ logger.debug("${Prefix} - prepareSdnrActivationRequest : SDNR Request : ${json}")
+ }
+
+ void processSdnrResponse(DelegateExecution execution) {
+ logger.debug("${Prefix} processing SdnrResponse")
+ Map<String, Object> resMap = objectMapper.readValue(execution.getVariable("SDNR_Response"),Map.class)
+ String status = resMap.get("status")
+ String reason = resMap.get("reason")
+ if("success".equalsIgnoreCase(status)) {
+ execution.setVariable("isANactivationSuccess", true)
+ }else {
+ execution.setVariable("isANactivationSuccess", false)
+ logger.debug("AN NF Activation/Deactivation failed with reason ${reason}")
+ }
+ logger.debug("${Prefix} processed SdnrResponse")
+ }
+
+ /**
+ * Update AN NF - NSSI and SP Instance status
+ * @param execution
+ */
+ void updateAnNfStatus(DelegateExecution execution) {
+ logger.debug("${Prefix}Start updateAnNfStatus")
+ String anNfNssiId = execution.getVariable("anNfNssiId")
+ String anNfSPId = execution.getVariable("anNfSPId")
+
+ updateOrchStatus(execution, anNfSPId)
+ updateOrchStatus(execution, anNfNssiId)
+ logger.debug("${Prefix}Exit updateAnNfStatus")
+ }
+
+ /**
+ * Method to check AN NF's Slice profile instance orchestration status
+ * @param execution
+ */
+ void getTnFhSPOrchStatus(DelegateExecution execution) {
+ logger.debug("${Prefix} start getTnFhSPOrchStatus ")
+ ServiceInstance sliceProfileInstance = getInstanceByWorkloadContext(execution.getVariable("relatedSPs"), TN_FH)
+ String tnFhNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_FH)
+ execution.setVariable("tnFhNssiId", tnFhNssiId)
+ String tnFhSPId = sliceProfileInstance.getServiceInstanceId()
+ execution.setVariable("tnFhSPId", tnFhSPId)
+
+ String orchStatus = sliceProfileInstance.getOrchestrationStatus()
+ String operationType = execution.getVariable("operationType")
+ if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
+ execution.setVariable("shouldChangeTN_FH_SPStatus", true)
+ }else {
+ execution.setVariable("shouldChangeTN_FH_SPStatus", false)
+ }
+
+ logger.debug("${Prefix} Exit getTnFhSPOrchStatus TN_FH SP ID:${tnFhSPId} : ${orchStatus}")
+ }
+
+ void doTnFhNssiActivation(DelegateExecution execution){
+ logger.debug("Start doTnFhNssiActivation in ${Prefix}")
+ String nssmfRequest = buildTNActivateNssiRequest(execution, TN_FH)
+ String operationType = execution.getVariable("operationType")
+ String urlOpType = operationType.equalsIgnoreCase(ACTIVATE) ? "activation":"deactivation"
+
+ List<String> sNssaiList = execution.getVariable("sNssaiList")
+ String snssai = sNssaiList != null ? sNssaiList.get(0) : ""
+
+ String urlString = "/api/rest/provMns/v1/NSS/" + snssai + urlOpType
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+ if (nssmfResponse != null) {
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TN_FH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ logger.debug("Exit doTnFhNssiActivation in ${Prefix}")
+ }
+
+ void getTnMhSPOrchStatus(DelegateExecution execution) {
+ logger.debug("${Prefix} Start getTnMhSPOrchStatus ")
+ ServiceInstance sliceProfileInstance = getInstanceByWorkloadContext(execution.getVariable("relatedSPs"), TN_MH)
+ String tnFhNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_MH)
+ execution.setVariable("tnMhNssiId", tnFhNssiId)
+ String tnFhSPId = sliceProfileInstance.getServiceInstanceId()
+ execution.setVariable("tnMhSPId", tnFhSPId)
+
+ String orchStatus = sliceProfileInstance.getOrchestrationStatus()
+ String operationType = execution.getVariable("operationType")
+ if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
+ execution.setVariable("shouldChangeTN_MH_SPStatus", true)
+ }else {
+ execution.setVariable("shouldChangeTN_MH_SPStatus", false)
+ }
+ logger.debug("${Prefix} Exit getTnMhSPOrchStatus TN_MH SP ID:${tnFhSPId} : ${orchStatus}")
+ }
+
+ void doTnMhNssiActivation(DelegateExecution execution){
+ logger.debug("Start doTnMhNssiActivation in ${Prefix}")
+ String nssmfRequest = buildTNActivateNssiRequest(execution, TN_MH)
+ String operationType = execution.getVariable("operationType")
+ String urlOpType = operationType.equalsIgnoreCase(ACTIVATE) ? "activation":"deactivation"
+
+ List<String> sNssaiList = execution.getVariable("sNssaiList")
+ String snssai = sNssaiList != null ? sNssaiList.get(0) : ""
+
+ String urlString = "/api/rest/provMns/v1/NSS/" + snssai + urlOpType
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+ if (nssmfResponse != null) {
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TN_MH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ logger.debug("Exit doTnMhNssiActivation in ${Prefix}")
+
+ }
+
+ /**
+ * Update TN FH - NSSI and SP Instance status
+ * @param execution
+ */
+ void updateTNFHStatus(DelegateExecution execution) {
+ logger.debug("${Prefix} Start updateTNFHStatus")
+
+ String tnFhNssiId = execution.getVariable("tnFhNssiId")
+ String tnFhSPId = execution.getVariable("tnFhSPId")
+ updateOrchStatus(execution, tnFhSPId)
+ updateOrchStatus(execution, tnFhNssiId)
+
+ logger.debug("${Prefix} Exit updateTNFHStatus")
+
+ }
+
+ /**
+ * Update TN MH - NSSI and SP Instance status
+ * @param execution
+ */
+ void updateTNMHStatus(DelegateExecution execution) {
+ logger.debug("${Prefix} Start updateTNMHStatus")
+
+ String tnMhNssiId = execution.getVariable("tnMhNssiId")
+ String tnMhSPId = execution.getVariable("tnMhSPId")
+ updateOrchStatus(execution, tnMhSPId)
+ updateOrchStatus(execution, tnMhNssiId)
+
+ logger.debug("${Prefix} Exit updateTNMHStatus")
+ }
+
+ /**
+ * Update AN - NSSI and SP Instance status
+ * @param execution
+ */
+ void updateANStatus(DelegateExecution execution) {
+ logger.debug("${Prefix} Start updateANStatus")
+ String anNssiId = execution.getVariable("anNssiId")
+ String anSliceProfileId = execution.getVariable("anSliceProfileId")
+ updateOrchStatus(execution, anNssiId)
+ updateOrchStatus(execution, anSliceProfileId)
+ logger.debug("${Prefix} Start updateANStatus")
+ }
+
+ void prepareQueryJobStatus(DelegateExecution execution,String jobId,String networkType,String instanceId) {
+ logger.debug("${Prefix} Start prepareQueryJobStatus : ${jobId}")
+ String responseId = "1"
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType(networkType)
+ esrInfo.setVendor(VENDOR_ONAP)
+
+ ServiceInfo serviceInfo = new ServiceInfo()
+ serviceInfo.setNssiId(instanceId)
+ serviceInfo.setNsiId(execution.getVariable("nsiId"))
+ serviceInfo.setGlobalSubscriberId(globalSubscriberId)
+ serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
+
+ execution.setVariable("${networkType}_esrInfo", esrInfo)
+ execution.setVariable("${networkType}_responseId", responseId)
+ execution.setVariable("${networkType}_serviceInfo", serviceInfo)
+
+ }
+
+ void validateJobStatus(DelegateExecution execution,String responseDescriptor) {
+ logger.debug("validateJobStatus ${responseDescriptor}")
+ String status = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.status")
+ String statusDescription = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.statusDescription")
+ if("finished".equalsIgnoreCase(status)) {
+ execution.setVariable("isSuccess", true)
+ }else {
+ execution.setVariable("isSuccess", false)
+ }
+ }
+
+
+ private void updateOrchStatus(DelegateExecution execution,String serviceId) {
+ logger.debug("${Prefix} Start updateOrchStatus : ${serviceId}")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ String operationType = execution.getVariable("operationType")
+
+ try {
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, serviceId)
+ if (!client.exists(uri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
+ }
+ AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
+ Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
+ if (si.isPresent()) {
+ String orchStatus = si.get().getOrchestrationStatus()
+ logger.debug("Orchestration status of instance ${serviceId} is ${orchStatus}")
+ if (ACTIVATE.equalsIgnoreCase(operationType) && "deactivated".equalsIgnoreCase(orchStatus)) {
+ si.get().setOrchestrationStatus("activated")
+ client.update(uri, si.get())
+ } else if(DEACTIVATE.equalsIgnoreCase(operationType) && "activated".equalsIgnoreCase(orchStatus)){
+ si.get().setOrchestrationStatus("deactivated")
+ client.update(uri, si.get())
+ }
+ }
+ } catch (Exception e) {
+ logger.info("Service is already in active state")
+ String msg = "Service is already in active state, " + e.getMessage()
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug("${Prefix} Exit updateOrchStatus : ${serviceId}")
+ }
+
+ void prepareUpdateJobStatus(DelegateExecution execution,String status,String progress,String statusDescription) {
+ logger.debug("${Prefix} Start prepareUpdateJobStatus : ${statusDescription}")
+ String serviceId = execution.getVariable("anNssiId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operationType = execution.getVariable("operationType")
+
+ ResourceOperationStatus roStatus = new ResourceOperationStatus()
+ roStatus.setServiceId(serviceId)
+ roStatus.setOperationId(jobId)
+ roStatus.setResourceTemplateUUID(nsiId)
+ roStatus.setOperType(operationType)
+ roStatus.setProgress(progress)
+ roStatus.setStatus(status)
+ roStatus.setStatusDescription(statusDescription)
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, status)
+ }
+
+
+
+ /**
+ * Fetches a collection of service instances with the specific role and maps it based on workload context
+ * (AN-NF,TN-FH,TN-MH)
+ * @param execution
+ * @param role - nssi/slice profile instance
+ * @param key - NSSI/Sliceprofile corresponding to instanceId
+ * @param instanceId - id to which the related list to be found
+ * @return
+ */
+ private Map<String,ServiceInstance> getRelatedInstancesByRole(DelegateExecution execution,String role,String key, String instanceId) {
+ logger.debug("${Prefix} - Fetching related ${role} from AAI")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ if( isBlank(role) || isBlank(instanceId)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Role and instanceId are mandatory")
+ }
+
+ Map<String,ServiceInstance> relatedInstances = new HashMap<>()
+
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, instanceId)
+ if (!client.exists(uri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
+ }
+ AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
+ Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
+ if(si.isPresent()) {
+ execution.setVariable(key, si.get())
+ List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo.toLowerCase() == "service-instance") {
+ String relatioshipurl = relationship.getRelatedLink()
+ String serviceInstanceId =
+ relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
+ uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, serviceInstanceId)
+ if (!client.exists(uri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
+ "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
+ }
+ AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
+ Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
+ if (serviceInstance.isPresent()) {
+ ServiceInstance instance = serviceInstance.get()
+ if (role.equalsIgnoreCase(instance.getServiceRole())) {
+ relatedInstances.put(instance.getWorkloadContext(),instance)
+ }
+ }
+ }
+ }
+ }
+ logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
+ return relatedInstances
+ }
+
+ private ServiceInstance getInstanceByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
+ ServiceInstance instance = instances.get(workloadContext)
+ if(instance == null) {
+ throw new BpmnError( 2500, "${workloadContext} Instance ID is not found.")
+ }
+ return instance
+ }
+
+ private String getInstanceIdByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
+ String instanceId = instances.get(workloadContext).getServiceInstanceId()
+ if(instanceId == null) {
+ throw new BpmnError( 2500, "${workloadContext} instance ID is not found.")
+ }
+ return instanceId
+ }
+
+
+ /**
+ * Method to handle deallocation of RAN NSSI constituents(TN_FH/TN_MH)
+ * @param execution
+ * @param serviceFunction - TN_FH/TN_MH
+ * @return
+ */
+ private String buildTNActivateNssiRequest(DelegateExecution execution,String serviceFunction) {
+ logger.debug("${Prefix} Exit buildTNActivateNssiRequest : ${serviceFunction}")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ Map<String, ServiceInstance> relatedNssis = execution.getVariable("relatedNssis")
+
+ String anNssiId = execution.getVariable("anNssiId")
+ List<String> sNssaiList = execution.getVariable("sNssaiList")
+
+ ServiceInstance tnNssi = relatedNssis.get(serviceFunction)
+ String nssiId = tnNssi.getServiceInstanceId()
+
+ Map<String, ServiceInstance> relatedSPs = execution.getVariable("relatedSPs")
+
+ ActDeActNssi actDeactNssi = new ActDeActNssi()
+ actDeactNssi.setNssiId(nssiId)
+ actDeactNssi.setNsiId(anNssiId)
+ actDeactNssi.setSliceProfileId(relatedSPs.get(serviceFunction).getServiceInstanceId())
+ actDeactNssi.setSnssaiList(sNssaiList)
+
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setVendor(VENDOR_ONAP)
+ esrInfo.setNetworkType("TN")
+
+ ServiceInfo serviceInfo = new ServiceInfo()
+ serviceInfo.setServiceInvariantUuid(tnNssi.getModelInvariantId())
+ serviceInfo.setServiceUuid(tnNssi.getModelVersionId())
+ serviceInfo.setGlobalSubscriberId(globalSubscriberId)
+ serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
+
+ JsonObject json = new JsonObject()
+ json.addProperty("actDeActNssi", objectMapper.writeValueAsString(actDeactNssi))
+ json.addProperty("esrInfo", objectMapper.writeValueAsString(esrInfo))
+ json.addProperty("serviceInfo", objectMapper.writeValueAsString(serviceInfo))
+ return json.toString()
+
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateCoreNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateCoreNSSI.groovy
new file mode 100644
index 0000000000..306c53a73c
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateCoreNSSI.groovy
@@ -0,0 +1,685 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Tech Mahindra
+ * ================================================================================
+ * 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.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.json.JSONObject
+import org.onap.logging.filter.base.ONAPComponents
+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.RequestDBUtil
+import org.onap.so.serviceinstancebeans.CloudConfiguration
+import org.onap.so.serviceinstancebeans.LineOfBusiness
+import org.onap.so.serviceinstancebeans.ModelInfo
+import org.onap.so.serviceinstancebeans.ModelType
+import org.onap.so.serviceinstancebeans.OwningEntity
+import org.onap.so.serviceinstancebeans.Platform
+import org.onap.so.serviceinstancebeans.Project
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.rest.catalog.beans.Vnf
+import org.onap.so.serviceinstancebeans.RequestDetails
+import org.onap.so.serviceinstancebeans.RequestInfo
+import org.onap.so.serviceinstancebeans.RequestParameters
+import org.onap.so.serviceinstancebeans.SubscriberInfo
+import org.onap.aai.domain.yang.GenericVnf
+import org.onap.aai.domain.yang.RelatedToProperty
+import org.onap.aai.domain.yang.Relationship
+import org.onap.aai.domain.yang.RelationshipData
+import org.onap.aai.domain.yang.RelationshipList
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aai.domain.yang.v19.SliceProfile
+import org.onap.aai.domain.yang.v19.SliceProfiles
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.db.request.beans.OperationStatus
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import com.fasterxml.jackson.databind.ObjectMapper
+
+import javax.ws.rs.NotFoundException
+import javax.ws.rs.core.Response
+
+class DoActivateCoreNSSI extends AbstractServiceTaskProcessor {
+ String Prefix="DACTCNSSI_"
+ private static final Logger logger = LoggerFactory.getLogger(DoActivateCoreNSSI.class);
+ CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
+ private RequestDBUtil requestDBUtil = new RequestDBUtil()
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ ObjectMapper mapper = new ObjectMapper();
+
+ JsonUtils jsonUtil = new JsonUtils()
+
+ private final Long TIMEOUT = 60 * 60 * 1000
+
+ @Override
+ public void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: preProcessRequest ****")
+
+ String operationType = execution.getVariable("operationType")
+ String oStatus= ""
+
+ if(operationType.equals("activateInstance")) {
+ oStatus ="activated"
+ } else {
+ oStatus ="deactivated"
+ }
+
+ execution.setVariable("oStatus", oStatus)
+ String sNssaiListAsString = jsonUtil.getJsonValue(execution.getVariable("sliceParams"), "snssaiList")
+
+ logger.debug("sNssaiListAsString "+sNssaiListAsString)
+
+ List<String> sNssaiList = jsonUtil.StringArrayToList(sNssaiListAsString)
+
+ logger.debug("sNssaiList "+sNssaiList)
+
+
+ String sNssai = sNssaiList.get(0)
+ execution.setVariable("sNssai", sNssai)
+
+ logger.debug("sNssai: "+sNssai)
+
+ String serviceType = execution.getVariable("subscriptionServiceType")
+ execution.setVariable("serviceType", serviceType)
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: preProcessRequest ****")
+ }
+
+ public void getNetworkInstanceWithSPInstanceAssociatedWithNssiId(DelegateExecution execution) {
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: getNetworkInstanceWithSPInstanceAssociatedWithNssiId ****")
+ //NSSI Id as service Instance Id to get from Request
+ String serviceInstanceId = execution.getVariable("serviceInstanceID")
+ String errorMsg = "query Network Service Instance from AAI failed"
+ AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
+ Optional<ServiceInstance> nsi = wrapper.asBean(ServiceInstance.class)
+ String networkServiceInstanceName = ""
+ String networkServiceInstanceId =""
+ if(nsi.isPresent()) {
+ List<Relationship> relationshipList = nsi.get().getRelationshipList()?.getRelationship()
+ List spiWithsNssaiAndOrchStatusList = new ArrayList<>()
+
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo == "service-instance") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ List<RelatedToProperty> relatedToPropertyList = relationship.getRelatedToProperty()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "service-instance.service-instance-id") {
+ execution.setVariable("networkServiceInstanceId", relationshipData.getRelationshipValue())
+ }
+ }
+ for (RelatedToProperty relatedToProperty : relatedToPropertyList) {
+ if (relatedToProperty.getPropertyKey() == "service-instance.service-instance-name") {
+ execution.setVariable("networkServiceInstanceName", relatedToProperty.getPropertyValue())
+ }
+ }
+ }
+
+ //If related to is allotted-Resource
+ if (relatedTo == "allotted-resource") {
+ //get slice Profile Instance Id from allotted resource in list by nssi
+ List<String> sliceProfileInstanceIdList = new ArrayList<>()
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "service-instance.service-instance-id") {
+ sliceProfileInstanceIdList.add(relationshipData.getRelationshipValue())
+ }
+ }
+ for (String sliceProfileServiceInstanceId : sliceProfileInstanceIdList) {
+ String errorSliceProfileMsg = "Slice Profile Service Instance was not found in aai"
+
+ //Query Slice Profile Service Instance From AAI by sliceProfileServiceInstanceId
+ AAIResultWrapper sliceProfileInstanceWrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, sliceProfileServiceInstanceId, errorSliceProfileMsg)
+ Optional<ServiceInstance> sliceProfileServiceInstance = sliceProfileInstanceWrapper.asBean(ServiceInstance.class)
+ if (sliceProfileServiceInstance.isPresent()) {
+ String orchestrationStatus= sliceProfileServiceInstance.get().getOrchestrationStatus()
+ String sNssai = sliceProfileServiceInstance.get().getSliceProfiles().getSliceProfile().get(0).getSNssai()
+ if(sNssai.equals(execution.getVariable("sNssai"))) {
+ orchestrationStatus = execution.getVariable("oStatus")
+ //Slice Profile Service Instance to be updated in AAI
+ execution.setVariable("sliceProfileServiceInstance", sliceProfileServiceInstance)
+ }
+
+ Map<String, Object> spiWithsNssaiAndOrchStatus = new LinkedHashMap<>()
+ spiWithsNssaiAndOrchStatus.put("snssai", sNssai)
+ spiWithsNssaiAndOrchStatus.put("status", orchestrationStatus)
+ spiWithsNssaiAndOrchStatusList.add(spiWithsNssaiAndOrchStatus)
+ }
+ }
+ }
+ }
+ execution.setVariable("snssaiAndOrchStatusList", spiWithsNssaiAndOrchStatusList)
+ }
+ logger.debug("NSSI Id: ${serviceInstanceId}, network Service Instance Id: ${networkServiceInstanceId}, serviceName: ${networkServiceInstanceName}")
+ //Get ServiceInstance Relationships
+ getServiceInstanceRelationships(execution)
+ //Get Vnf Relationships
+ getVnfRelationships(execution)
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getNetworkInstanceWithSPInstanceAssociatedWithNssiId ****")
+ }
+
+
+ private String prepareVnfInstanceParamsJson(DelegateExecution execution) {
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: prepareVnfInstanceParamsJson ****")
+ List instanceParamsvalues = execution.getVariable("snssaiAndOrchStatusList")
+ Map<String, Object> nSsai= new LinkedHashMap<>()
+ nSsai.put("sNssai", instanceParamsvalues)
+ String supportedsNssaiJson = mapper.writeValueAsString(nSsai)
+ //SupportedNssai
+ Map<String, Object> supportedNssai= new LinkedHashMap<>()
+ supportedNssai.put("supportedNssai", supportedsNssaiJson)
+ logger.debug("**** supportedsNssaiJson**** "+supportedNssai)
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: prepareVnfInstanceParamsJson ****")
+ return supportedNssai
+ }
+
+ private void getServiceInstanceRelationships(DelegateExecution execution) {
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: getServiceInstanceRelationships ****")
+ String serviceInstanceId = execution.getVariable("networkServiceInstanceId")
+ logger.debug("**** serviceInstanceId :: getServiceInstanceRelationships :: "+serviceInstanceId)
+ String errorMsg = "query Network Service Instance from AAI failed"
+ AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
+ Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
+
+ String networkServiceModelInvariantUuid = si.get().getModelInvariantId()
+ execution.setVariable("networkServiceModelInvariantUuid", networkServiceModelInvariantUuid)
+ if(si.isPresent()) {
+ List<Relationship> relationshipList = si.get().getRelationshipList()?.getRelationship()
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo == "owning-entity") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "owning-entity.owning-entity-id") {
+ execution.setVariable("owningEntityId", relationshipData.getRelationshipValue())
+ }
+ }
+ } else if (relatedTo == "generic-vnf") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ List<RelatedToProperty> relatedToPropertyList = relationship.getRelatedToProperty()
+
+ //Get VnfId
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "generic-vnf.vnf-id") {
+ execution.setVariable("vnfId", relationshipData.getRelationshipValue())
+ String vnfId = relationshipData.getRelationshipValue()
+ logger.debug("vnfId :"+vnfId)
+ }
+ }
+ } else if (relatedTo == "project") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "project.project-name") {
+ execution.setVariable("projectName", relationshipData.getRelationshipValue())
+ }
+ }
+ }
+ }
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getServiceInstanceRelationships ****")
+ }
+ }
+
+ private void getVnfRelationships(DelegateExecution execution) {
+
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: getVnfRelationships ****")
+ String msg = "query Generic Vnf from AAI failed"
+ try {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, execution.getVariable('vnfId'))
+ if (!getAAIClient().exists(uri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+ AAIResultWrapper wrapper = getAAIClient().get(uri, NotFoundException.class)
+ Optional<GenericVnf> vnf = wrapper.asBean(GenericVnf.class)
+ if(vnf.isPresent()) {
+ List<Relationship> relationshipList = vnf.get().getRelationshipList()?.getRelationship()
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo == "tenant") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "tenant.tenant-id") {
+ execution.setVariable("tenantId", relationshipData.getRelationshipValue())
+ }
+ }
+ } else if (relatedTo == "cloud-region") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "cloud-region.cloud-owner") {
+ execution.setVariable("cloudOwner", relationshipData.getRelationshipValue())
+ } else if (relationshipData.getRelationshipKey() == "cloud-region.cloud-region-id") {
+ execution.setVariable("lcpCloudRegionId", relationshipData.getRelationshipValue())
+ }
+ }
+ } else if (relatedTo == "platform") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "platform.platform-name") {
+ execution.setVariable("platformName", relationshipData.getRelationshipValue())
+ }
+ }
+ } else if (relatedTo == "line-of-business") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "line-of-business.line-of-business-name") {
+ execution.setVariable("lineOfBusinessName", relationshipData.getRelationshipValue())
+ }
+ }
+ }
+ }
+ }
+ } catch(BpmnError e){
+ throw e
+ } catch (Exception ex){
+ msg = "Exception in getVnfRelationships " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getVnfRelationships ****")
+ }
+
+
+ /**
+ * query AAI
+ * @param execution
+ * @param aaiObjectType
+ * @param instanceId
+ * @return AAIResultWrapper
+ */
+ private AAIResultWrapper queryAAI(DelegateExecution execution, AAIObjectType aaiObjectType, String instanceId, String errorMsg) {
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: queryAAI ****")
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("serviceType")
+
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(aaiObjectType, globalSubscriberId, serviceType, instanceId)
+ if (!getAAIClient().exists(resourceUri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMsg)
+ }
+ AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
+
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: queryAAI ****")
+ return wrapper
+ }
+
+ public void getServiceVNFAndVFsFromCatalogDB(DelegateExecution execution) {
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getServiceVNFAndVFsFromCatalogDB ****")
+
+ String modelInvariantUuid = execution.getVariable("networkServiceModelInvariantUuid")
+
+ try{
+ CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
+ String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution, modelInvariantUuid)
+ logger.debug("***** JSON IS: "+json)
+
+ String serviceVnfs = jsonUtil.getJsonValue(json, "serviceResources.serviceVnfs") ?: ""
+ String serviceModelInfo = jsonUtil.getJsonValue(json, "serviceResources.modelInfo") ?: ""
+
+
+ execution.setVariable("serviceVnfs",serviceVnfs)
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ logger.debug(Prefix +" ***** serviceVnfs is: "+ serviceVnfs)
+ }catch(BpmnError e){
+ throw e
+ } catch (Exception ex){
+ String msg = "Exception in getServiceVNFAndVFsFromCatalogDB " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getServiceVNFAndVFsFromCatalogDB ****")
+ }
+
+ public void prepareSOMacroRequestPayLoad(DelegateExecution execution) {
+ logger.debug("**** Enter DoActivateCoreNSSI ::: prepareSOMacroRequestPayLoad ****")
+ String json = execution.getVariable("serviceVnfs")
+ logger.debug(">>>> json "+json)
+ List<Object> vnfList = mapper.readValue(json, List.class);
+ logger.debug("vnfList: "+vnfList)
+ Map<String,Object> serviceMap = mapper.readValue(execution.getVariable("serviceModelInfo"), Map.class);
+ ModelInfo serviceModelInfo = new ModelInfo()
+ serviceModelInfo.setModelType(ModelType.service)
+ serviceModelInfo.setModelInvariantId(serviceMap.get("modelInvariantUuid"))
+ serviceModelInfo.setModelVersionId(serviceMap.get("modelUuid"))
+ serviceModelInfo.setModelName(serviceMap.get("modelName"))
+ serviceModelInfo.setModelVersion(serviceMap.get("modelVersion"))
+
+ logger.debug("serviceModelInfo: "+serviceModelInfo)
+ //List of Vnfs
+ List<Object> vnfModelInfoList = new ArrayList<>()
+
+ Map vnfMap = vnfList.get(0)
+ ModelInfo vnfModelInfo = vnfMap.get("modelInfo")
+ logger.debug("vnfModelInfo "+vnfModelInfo)
+
+ //List of VFModules
+ List<Map<String, Object>> vfModuleList = vnfMap.get("vfModules")
+ logger.debug("vfModuleList "+vfModuleList)
+
+ //List of VfModules
+ List<ModelInfo> vfModelInfoList = new ArrayList<>()
+
+ //Traverse VFModules List and add in vfModelInfoList
+ for (vfModule in vfModuleList) {
+ ModelInfo vfModelInfo = vfModule.get("modelInfo")
+ logger.debug("vfModelInfo "+vfModelInfo)
+ vfModelInfoList.add(vfModelInfo)
+ }
+
+ //RequestInfo
+ RequestInfo requestInfo = new RequestInfo()
+
+ //Dummy Product FamilyId
+ requestInfo.setProductFamilyId("test1234")
+ requestInfo.setSource("VID")
+ requestInfo.setInstanceName(execution.getVariable("networkServiceInstanceName"))
+ requestInfo.setSuppressRollback(false)
+ requestInfo.setRequestorId("NBI")
+
+ //Service Level InstanceParams
+ List<Map<String, Object>> serviceParams = new ArrayList<>()
+ Map<String, Object> serviceParamsValues = new LinkedHashMap<>()
+ serviceParams.add(serviceParamsValues)
+
+ //Cloud Configuration
+ CloudConfiguration cloudConfiguration = new CloudConfiguration()
+ cloudConfiguration.setLcpCloudRegionId(execution.getVariable("lcpCloudRegionId"))
+ cloudConfiguration.setTenantId(execution.getVariable("tenantId"))
+ cloudConfiguration.setCloudOwner(execution.getVariable("cloudOwner"))
+
+ //VFModules List
+ List<Map<String, Object>> vfModules = new ArrayList<>()
+ for (ModelInfo vfModuleModelInfo : vfModelInfoList) {
+ //Individual VFModule List
+ Map<String, Object> vfModuleValues = new LinkedHashMap<>()
+ vfModuleValues.put("modelInfo", vfModuleModelInfo)
+ vfModuleValues.put("instanceName", vfModuleModelInfo.getModelInstanceName())
+
+ //VFModule InstanceParams should be empty or this field should not be there?
+ List<Map<String, Object>> vfModuleInstanceParams = new ArrayList<>()
+ vfModuleValues.put("instanceParams", vfModuleInstanceParams)
+ }
+
+ //Vnf intsanceParams
+ ObjectMapper objectMapper = new ObjectMapper();
+ Map<String, Object> sliceProfile = objectMapper.readValue(execution.getVariable("sliceProfile"), Map.class);
+
+ List vnfInstanceParamsList = new ArrayList<>()
+ String supportedsNssaiJson= prepareVnfInstanceParamsJson(execution)
+ vnfInstanceParamsList.add(supportedsNssaiJson)
+
+ Platform platform = new Platform()
+ platform.setPlatformName(execution.getVariable("platform"))
+
+ LineOfBusiness lineOfbusiness = new LineOfBusiness()
+ lineOfbusiness.setLineOfBusinessName(execution.getVariable("lineOfBusiness"))
+
+ //Vnf Values
+ Map<String, Object> vnfValues = new LinkedHashMap<>()
+ vnfValues.put("lineOfBusiness", lineOfbusiness)
+ vnfValues.put("platform", platform)
+ vnfValues.put("productFamilyId", "test1234")
+ vnfValues.put("cloudConfiguration", cloudConfiguration)
+ vnfValues.put("vfModules", vfModules)
+ vnfValues.put("modelInfo", vnfModelInfo)
+ vnfValues.put("instanceName", execution.getVariable("vnfInstanceName"))
+ vnfValues.put("instanceParams",vnfInstanceParamsList)
+
+ vnfModelInfoList.add(vnfValues)
+ //Service Level Resources
+ Map<String, Object> serviceResources = new LinkedHashMap<>()
+ serviceResources.put("vnfs", vnfModelInfoList)
+
+ //Service Values
+ Map<String, Object> serviceValues = new LinkedHashMap<>()
+ serviceValues.put("modelInfo", serviceModelInfo)
+ serviceValues.put("instanceName", execution.getVariable("networkServiceInstanceName"))
+ serviceValues.put("resources", serviceResources)
+ serviceValues.put("instanceParams", serviceParams)
+
+ //UserParams Values
+ Map<String, Object> userParamsValues = new LinkedHashMap<>()
+
+ Map<String, Object> homingSolution = new LinkedHashMap<>()
+ homingSolution.put("Homing_Solution", "none")
+
+ userParamsValues.put("service", serviceValues)
+
+ //UserParams
+ List<Map<String, Object>> userParams = new ArrayList<>()
+ userParams.add(homingSolution)
+ userParams.add(userParamsValues)
+
+ //Request Parameters
+ RequestParameters requestParameters = new RequestParameters()
+ requestParameters.setaLaCarte(false)
+ requestParameters.setSubscriptionServiceType(execution.getVariable("serviceType"))
+ requestParameters.setUserParams(userParams)
+
+ //SubscriberInfo
+ SubscriberInfo subscriberInfo = new SubscriberInfo()
+ subscriberInfo.setGlobalSubscriberId(execution.getVariable("globalSubscriberId"))
+
+ //Owning Entity
+ OwningEntity owningEntity = new OwningEntity()
+ owningEntity.setOwningEntityId(execution.getVariable("owningEntityId"))
+
+ //Project
+ Project project = new Project()
+ project.setProjectName(execution.getVariable("projectName"))
+
+ RequestDetails requestDetails = new RequestDetails()
+ requestDetails.setModelInfo(serviceModelInfo)
+ requestDetails.setSubscriberInfo(subscriberInfo)
+ requestDetails.setRequestInfo(requestInfo)
+ requestDetails.setRequestParameters(requestParameters)
+ requestDetails.setCloudConfiguration(cloudConfiguration)
+ requestDetails.setOwningEntity(owningEntity)
+ requestDetails.setProject(project)
+
+ Map<String, Object> requestDetailsMap = new LinkedHashMap<>()
+ requestDetailsMap.put("requestDetails", requestDetails)
+ String requestPayload = objectMapper.writeValueAsString(requestDetailsMap)
+
+ logger.debug("requestDetails "+requestPayload)
+ execution.setVariable("requestPayload", requestPayload)
+
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: prepareSOMacroRequestPayLoad ****")
+ }
+
+ public void sendPutRequestToSOMacro(DelegateExecution execution) {
+
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: sendPutRequestToSOMacro ****")
+ try {
+ String msoEndpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
+ String url = msoEndpoint+"/serviceInstantiation/v7/serviceInstances/"+execution.getVariable("networkServiceInstanceId")+"/vnfs/"+execution.getVariable("vnfId")
+ String requestBody = execution.getVariable("requestPayload")
+ String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
+ String basicAuth = UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
+ String basicAuthValue = utils.encrypt(basicAuth, msoKey)
+ String encodeString = utils.getBasicAuth(basicAuthValue, msoKey)
+
+ HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.SO)
+ httpClient.addAdditionalHeader("Authorization", encodeString)
+ httpClient.addAdditionalHeader("Accept", "application/json")
+ Response httpResponse = httpClient.put(requestBody)
+ handleSOResponse(httpResponse, execution)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (any) {
+ String msg = "Exception in DoActivateCoreNSSSI " + any.getCause()
+ logger.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: sendPostRequestToSOMacro ****")
+ }
+
+ /**
+ * Handle SO Response for PUT and prepare update operation status
+ * @param execution
+ */
+ private void handleSOResponse(Response httpResponse, DelegateExecution execution){
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: handleSOResponse ****")
+
+ int soResponseCode = httpResponse.getStatus()
+ logger.debug("soResponseCode : "+soResponseCode)
+
+ if (soResponseCode >= 200 && soResponseCode < 204 && httpResponse.hasEntity()) {
+ String soResponse = httpResponse.readEntity(String.class)
+ String operationId = execution.getVariable("operationId")
+ def macroOperationId = jsonUtil.getJsonValue(soResponse, "operationId")
+ execution.setVariable("macroOperationId", macroOperationId)
+ execution.setVariable("isSOTimeOut", "no")
+ execution.setVariable("isSOResponseSucceed","yes")
+ }
+ else
+ {
+ String serviceName = execution.getVariable("serviceInstanceName")
+ execution.setVariable("isSOResponseSucceed","no")
+ prepareFailedOperationStatusUpdate(execution)
+ }
+
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: handleSOResponse ****")
+ }
+
+ /**
+ * prepare to call sub process CheckProcessStatus
+ * @param execution
+ */
+ void prepareCallCheckProcessStatus(DelegateExecution execution){
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: prepareCallCheckProcessStatus ****")
+ def successConditions = new ArrayList<>()
+ successConditions.add("finished")
+ execution.setVariable("successConditions", successConditions)
+ def errorConditions = new ArrayList<>()
+ errorConditions.add("error")
+ execution.setVariable("errorConditions", errorConditions)
+ execution.setVariable("processServiceType", "Network service")
+ execution.setVariable("subOperationType", "PUT")
+ execution.setVariable("initProgress", 20)
+ execution.setVariable("endProgress",90)
+ execution.setVariable("timeOut", TIMEOUT)
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: prepareCallCheckProcessStatus ****")
+ }
+
+ void prepareUpdateResourceOperationStatus(DelegateExecution execution) {
+
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: prepareUpdateResourceOperationStatus ****")
+
+ String nssiOperationId = execution.getVariable("nssiOperationId")
+ execution.setVariable("operationId", nssiOperationId)
+ //Prepare Update Status for PUT failure and success
+ if(execution.getVariable("isTimeOut").equals("YES")) {
+ logger.debug("TIMEOUT - SO PUT Failure")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SO PUT Failure")
+ }
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: prepareUpdateResourceOperationStatus ****")
+ }
+
+ void updateSliceProfileOrchestrationStatus(DelegateExecution execution) {
+
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: updateSliceProfileOrchestrationStatus ****")
+
+ String globalCustId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("serviceType")
+ String oStatus = execution.getVariable("oStatus")
+
+ ServiceInstance si = execution.getVariable("sliceProfileServiceInstance")
+ String sliceProfileInstanceId = si.getServiceInstanceId()
+ si.setOrchestrationStatus(oStatus)
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalCustId, serviceType, sliceProfileInstanceId)
+ try {
+
+ Response response = getAAIClient().update(uri, si)
+
+ if(response.getStatus()!=200 || response.getStatus()!=201 || response.getStatus()!=202) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, response.getStatus(), "AAI failed to update sliceProlie service Instance orchestration status")
+ } else {
+ setResourceOperationStatus(execution)
+ }
+ } catch (Exception e) {
+ logger.info("Update OrchestrationStatus in AAI failed")
+ String msg = "Update OrchestrationStatus in AAI failed, " + e.getMessage()
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: updateSliceProfileOrchestrationStatus ****")
+ }
+
+ /**
+ * prepare ResourceOperation status
+ * @param execution
+ * @param operationType
+ */
+ private void setResourceOperationStatus(DelegateExecution execution) {
+
+ logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: setResourceOperationStatus ****")
+
+ String serviceId = execution.getVariable("nssiId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operationType = execution.getVariable("operationType")
+ ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
+ resourceOperationStatus.setServiceId(serviceId)
+ resourceOperationStatus.setOperationId(jobId)
+ resourceOperationStatus.setResourceTemplateUUID(nsiId)
+ resourceOperationStatus.setOperType(operationType)
+ resourceOperationStatus.setStatus("finished")
+ resourceOperationStatus.setProgress("100")
+ resourceOperationStatus.setStatusDescription("Core Activation Successful")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
+
+ logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: setResourceOperationStatus ****")
+ }
+
+ void prepareFailedOperationStatusUpdate(DelegateExecution execution){
+ logger.debug(Prefix + " **** Enter DoActivateCoreNSSI ::: prepareFailedOperationStatusUpdate ****")
+
+ String serviceId = execution.getVariable("nssiId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operationType = execution.getVariable("operationType")
+
+ ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
+ resourceOperationStatus.setServiceId(serviceId)
+ resourceOperationStatus.setOperationId(jobId)
+ resourceOperationStatus.setResourceTemplateUUID(nsiId)
+ resourceOperationStatus.setOperType(operationType)
+ resourceOperationStatus.setProgress(0)
+ resourceOperationStatus.setStatus("failed")
+ resourceOperationStatus.setStatusDescription("Core NSSI Activation Failed")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
+
+ logger.debug(Prefix + " **** Exit DoActivateCoreNSSI ::: prepareFailedOperationStatusUpdate ****")
+ }
+
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateTnNssi.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateTnNssi.groovy
new file mode 100644
index 0000000000..04fe161295
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateTnNssi.groovy
@@ -0,0 +1,162 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 groovy.json.JsonSlurper
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+public class DoActivateTnNssi extends AbstractServiceTaskProcessor {
+ String Prefix = "TNACT_"
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ TnNssmfUtils tnNssmfUtils = new TnNssmfUtils()
+ JsonSlurper jsonSlurper = new JsonSlurper()
+ ObjectMapper objectMapper = new ObjectMapper()
+ private static final Logger logger = LoggerFactory.getLogger(DoActivateTnNssi.class)
+
+
+ public void preProcessRequest(DelegateExecution execution) {
+ logger.debug("Start preProcessRequest")
+
+ execution.setVariable("startTime", System.currentTimeMillis())
+ String msg = tnNssmfUtils.getExecutionInputParams(execution)
+ logger.debug("Activate TN NSSI input parameters: " + msg)
+
+ execution.setVariable("prefix", Prefix)
+
+ tnNssmfUtils.setSdncCallbackUrl(execution, true)
+ logger.debug("SDNC Callback URL: " + execution.getVariable("sdncCallbackUrl"))
+
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelUuid = execution.getVariable("modelUuid")
+ //here modelVersion is not set, we use modelUuid to decompose the service.
+ def isDebugLogEnabled = true
+ execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+
+ String sliceServiceInstanceId = execution.getVariable("serviceInstanceID")
+ execution.setVariable("sliceServiceInstanceId", sliceServiceInstanceId)
+
+ String sliceServiceInstanceName = execution.getVariable("servicename")
+ execution.setVariable("sliceServiceInstanceName", sliceServiceInstanceName)
+
+ String operationType = execution.getVariable("operationType")
+ String actionType = operationType.equals("activateInstance") ? "activate" : "deactivate"
+ execution.setVariable("actionType", actionType)
+
+
+ logger.debug("Finish preProcessRequest")
+ }
+
+ void preprocessSdncActOrDeactTnNssiRequest(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preprocessSdncActivateTnNssiRequest(' +
+ 'execution=' + execution.getId() + ')'
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+ logger.trace('Entered ' + method)
+
+ try {
+ String serviceInstanceId = execution.getVariable("sliceServiceInstanceId")
+ String actionType = execution.getVariable("actionType")
+
+ String sdncRequest = tnNssmfUtils.buildSDNCRequest(execution, serviceInstanceId, actionType)
+
+ execution.setVariable("TNNSSMF_SDNCRequest", sdncRequest)
+ logger.debug("Outgoing SDNCRequest is: \n" + sdncRequest)
+
+ } catch (Exception e) {
+ logger.debug("Exception Occured Processing preprocessSdncDeallocateTnNssiRequest. Exception is:\n" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage())
+ }
+ logger.trace("COMPLETED preprocessSdncActivateTnNssiRequest Process")
+ }
+
+
+ void validateSDNCResponse(DelegateExecution execution, String response) {
+ tnNssmfUtils.validateSDNCResponse(execution, response, method)
+ }
+
+
+ void updateAAIOrchStatus(DelegateExecution execution) {
+ logger.debug("Start updateAAIOrchStatus")
+ String tnNssiId = execution.getVariable("tnNssiId")
+ String orchStatus = execution.getVariable("orchestrationStatus")
+
+ try {
+ ServiceInstance si = new ServiceInstance()
+ si.setOrchestrationStatus(orchStatus)
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, tnNssiId)
+ client.update(uri, si)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in CreateSliceService.updateAAIOrchStatus " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ logger.debug("Finish updateAAIOrchStatus")
+ }
+
+ void prepareUpdateJobStatus(DelegateExecution execution,
+ String status,
+ String progress,
+ String statusDescription) {
+ String serviceId = execution.getVariable("serviceInstanceID")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operType = execution.getVariable("actionType")
+
+
+ ResourceOperationStatus roStatus = new ResourceOperationStatus()
+ roStatus.setServiceId(serviceId)
+ roStatus.setOperationId(jobId)
+ roStatus.setResourceTemplateUUID(nsiId)
+ roStatus.setOperType(operType)
+ roStatus.setProgress(progress)
+ roStatus.setStatus(status)
+ roStatus.setStatusDescription(statusDescription)
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, status)
+ }
+
+}
+
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateAccessNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateAccessNSSI.groovy
new file mode 100644
index 0000000000..3df0d3d6f0
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateAccessNSSI.groovy
@@ -0,0 +1,1041 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, Wipro Limited.
+ #
+ # 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.delegate.BpmnError
+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.common.scripts.NssmfAdapterUtils
+import org.onap.so.bpmn.common.scripts.OofUtils
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.sql.Timestamp
+import java.util.List
+import static org.apache.commons.lang3.StringUtils.isBlank
+import com.google.gson.JsonObject
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.google.gson.JsonArray
+import org.onap.aai.domain.yang.Relationship
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.beans.nsmf.AllocateTnNssi
+import org.onap.so.beans.nsmf.EsrInfo
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.domain.ServiceInstance
+import org.onap.so.bpmn.core.domain.ServiceProxy
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.aaiclient.client.aai.AAINamespaceConstants
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aai.domain.yang.NetworkPolicy
+import org.onap.aai.domain.yang.NetworkRoute
+
+class DoAllocateAccessNSSI extends AbstractServiceTaskProcessor {
+
+ String Prefix="AASS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ OofUtils oofUtils = new OofUtils()
+ AnNssmfUtils anNssmfUtils = new AnNssmfUtils()
+ ObjectMapper objectMapper = new ObjectMapper();
+ private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
+
+ private static final Logger logger = LoggerFactory.getLogger(DoAllocateAccessNSSI.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix + "preProcessRequest Start")
+ execution.setVariable("prefix", Prefix)
+ execution.setVariable("startTime", System.currentTimeMillis())
+ def msg
+ try {
+
+ logger.debug("input variables : msoRequestId - "+execution.getVariable("msoRequestId")
+ +" modelInvariantUuid - "+execution.getVariable("modelInvariantUuid")+
+ " modelUuid - "+execution.getVariable("modelUuid")+
+ " globalSubscriberId - "+execution.getVariable("globalSubscriberId")+
+ " dummyServiceId - "+ execution.getVariable("dummyServiceId")+
+ " nsiId - "+execution.getVariable("nsiId")+
+ " networkType - "+execution.getVariable("networkType")+
+ " subscriptionServiceType - "+execution.getVariable("subscriptionServiceType")+
+ " jobId - "+execution.getVariable("jobId")+
+ " sliceParams - "+execution.getVariable("sliceParams")+
+ " servicename - "+ execution.getVariable("servicename"))
+
+ //validate slice subnet inputs
+
+ String sliceParams = execution.getVariable("sliceParams")
+ String sliceProfile = jsonUtil.getJsonValue(sliceParams, "sliceProfile")
+ if (isBlank(sliceProfile)) {
+ msg = "Input sliceProfile is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("sliceProfile", sliceProfile)
+ }
+ String sliceProfileId = jsonUtil.getJsonValue(sliceProfile, "sliceProfileId")
+ def snssaiList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceProfile, "snssaiList"))
+ def plmnIdList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceProfile, "plmnIdList"))
+ def coverageAreaTAList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceProfile, "coverageAreaTAList"))
+
+ if (isBlank(sliceProfileId) || (snssaiList.empty) || (plmnIdList.empty)
+ || (coverageAreaTAList.empty)) {
+
+ msg = "Mandatory slice profile fields are empty"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("sliceProfileId", sliceProfileId)
+ execution.setVariable("snssaiList", snssaiList)
+ execution.setVariable("plmnIdList", plmnIdList)
+ execution.setVariable("coverageAreaTAList", coverageAreaTAList)
+ }
+ String nsiName = jsonUtil.getJsonValue(sliceParams, "nsiInfo.nsiName")
+ String scriptName = jsonUtil.getJsonValue(sliceParams, "scriptName")
+ execution.setVariable("nsiName", nsiName)
+ execution.setVariable("scriptName", scriptName)
+ //generate RAN,RAN NF NSSIs - will be re assigned if oof returns existing NSSI
+ String RANServiceInstanceId = UUID.randomUUID().toString()
+ String RANNFServiceInstanceId = UUID.randomUUID().toString()
+ logger.debug("RAN serviceInstance Id "+RANServiceInstanceId)
+ logger.debug("RAN NF serviceInstance Id "+RANNFServiceInstanceId)
+ execution.setVariable("RANServiceInstanceId", RANServiceInstanceId)
+ execution.setVariable("RANNFServiceInstanceId", RANNFServiceInstanceId)
+ execution.setVariable("ranNssiPreferReuse", true)
+ execution.setVariable("ranNfNssiPreferReuse", true)
+ execution.setVariable("job_timeout", 10)
+
+ //set BH end point
+ List<String> BH_endPoints = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceParams, "endPoints"))
+ logger.debug("BH end points list : "+BH_endPoints)
+ if(BH_endPoints.empty) {
+ msg = "End point info is empty"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }else {
+ execution.setVariable("bh_endpoint", BH_endPoints.get(0))
+ }
+
+ } catch(BpmnError e) {
+ throw e
+ } catch(Exception ex) {
+ msg = "Exception in DoAllocateAccessNSSI.preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "preProcessRequest Exit")
+ }
+
+ /*
+ * Prepare request params for decomposing RAN NSST
+ */
+
+ def prepareDecomposeService = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareDecomposeService method start")
+ String RANServiceInstanceId = execution.getVariable("RANServiceInstanceId")
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelUuid = execution.getVariable("modelUuid")
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ execution.setVariable("serviceInstanceId", RANServiceInstanceId)
+ logger.debug("serviceModelInfo : "+serviceModelInfo)
+ logger.debug("Finish RAN NSST prepareDecomposeService")
+ }
+
+ /* process the decompose service(RAN NSST) response
+ *
+ */
+ def processDecomposition = { DelegateExecution execution ->
+ logger.debug(Prefix+"processDecomposition method start")
+ ServiceDecomposition ranNsstServiceDecomposition = execution.getVariable("ranNsstServiceDecomposition")
+ logger.debug("ranNsstServiceDecomposition : "+ranNsstServiceDecomposition.toString())
+ //RAN NSST decomposition
+ String ranModelVersion = ranNsstServiceDecomposition.getModelInfo().getModelVersion()
+ String ranModelName = ranNsstServiceDecomposition.getModelInfo().getModelName()
+ List<ServiceProxy> serviceProxyList = ranNsstServiceDecomposition.getServiceProxy()
+ List<String> nsstInfoList = new ArrayList<>()
+ for(ServiceProxy serviceProxy : serviceProxyList)
+ {
+ String nsstModelUuid = serviceProxy.getModelInfo().getModelUuid()
+ String nsstModelInvariantUuid = serviceProxy.getModelInfo().getModelInvariantUuid()
+ String name = serviceProxy.getModelInfo().getModelName()
+ String nsstServiceModelInfo = """{
+ "UUID":"${nsstModelUuid}",
+ "invariantUUID":"${nsstModelInvariantUuid}",
+ "name":"${name}"
+ }"""
+ nsstInfoList.add(nsstServiceModelInfo)
+ }
+ int currentIndex=0
+ int maxIndex=nsstInfoList.size()
+ if(maxIndex < 1)
+ {
+ String msg = "Exception in RAN NSST processDecomposition. There is no NSST associated with RAN NSST "
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ execution.setVariable("ranNsstInfoList",nsstInfoList)
+ execution.setVariable("ranModelVersion", ranModelVersion)
+ execution.setVariable("ranModelName", ranModelName)
+ execution.setVariable("currentIndex",currentIndex)
+ execution.setVariable("maxIndex",maxIndex)
+ logger.debug(Prefix+"processDecomposition maxIndex value - "+maxIndex)
+ }
+
+ /*
+ * Function to subnet capabilities from nssmf adapter
+ */
+ def getSubnetCapabilities = { DelegateExecution execution ->
+ logger.debug(Prefix+"getSubnetCapabilities method start")
+
+ String tnNssmfRequest = anNssmfUtils.buildCreateTNNSSMFSubnetCapabilityRequest()
+
+ String urlString = "/api/rest/provMns/v1/NSS/subnetCapabilityQuery"
+
+ String tnNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, tnNssmfRequest)
+
+ if (tnNssmfResponse != null) {
+ String FHCapabilities= jsonUtil.getJsonValue(tnNssmfResponse, "TN_FH")
+ String MHCapabilities = jsonUtil.getJsonValue(tnNssmfResponse, "TN_MH")
+ execution.setVariable("FHCapabilities",FHCapabilities)
+ execution.setVariable("MHCapabilities",MHCapabilities)
+
+ } else {
+ logger.error("received error message from NSSMF : "+ tnNssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ String anNssmfRequest = anNssmfUtils.buildCreateANNFNSSMFSubnetCapabilityRequest()
+
+ String anNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, anNssmfRequest)
+
+ if (anNssmfResponse != null) {
+ String ANNFCapabilities = jsonUtil.getJsonValue(anNssmfResponse, "AN_NF")
+ execution.setVariable("ANNFCapabilities",ANNFCapabilities)
+
+ } else {
+ logger.error("received error message from NSSMF : "+ anNssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ }
+
+ /*
+ * prepare OOF request for RAN NSSI selection
+ */
+ def prepareOofRequestForRanNSS = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareOofRequestForRanNSS method start")
+
+ String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
+ logger.debug( "get NSSI option OOF Url: " + urlString)
+
+ //build oof request body
+ boolean ranNssiPreferReuse = execution.getVariable("ranNssiPreferReuse");
+ String requestId = execution.getVariable("msoRequestId")
+ String messageType = "NSISelectionResponse"
+ Map<String, Object> profileInfo = objectMapper.readValue(execution.getVariable("sliceProfile"), Map.class)
+ String modelUuid = execution.getVariable("modelUuid")
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelName = execution.getVariable("ranModelName")
+ String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
+ List<String> nsstInfoList = objectMapper.readValue(execution.getVariable("nsstInfoList"), List.class)
+ JsonArray capabilitiesList = new JsonArray()
+ String FHCapabilities = execution.getVariable("FHCapabilities")
+ String MHCapabilities = execution.getVariable("MHCapabilities")
+ String ANNFCapabilities = execution.getVariable("ANNFCapabilities")
+ JsonObject FH = new JsonObject()
+ JsonObject MH = new JsonObject()
+ JsonObject ANNF = new JsonObject()
+ FH.addProperty("domainType", "TN_FH")
+ FH.addProperty("capabilityDetails", FHCapabilities)
+ MH.addProperty("domainType", "TN_MH")
+ MH.addProperty("capabilityDetails", MHCapabilities)
+ ANNF.addProperty("domainType", "AN_NF")
+ ANNF.addProperty("capabilityDetails", FHCapabilities)
+ capabilitiesList.add(FH)
+ capabilitiesList.add(MH)
+ capabilitiesList.add(ANNF)
+
+ execution.setVariable("nssiSelection_Url", "/api/oof/selection/nsi/v1")
+ execution.setVariable("nssiSelection_messageType",messageType)
+ execution.setVariable("nssiSelection_correlator",requestId)
+ execution.setVariable("nssiSelection_timeout",timeout)
+
+ String oofRequest = anNssmfUtils.buildSelectRANNSSIRequest(requestId, messageType, modelUuid,modelInvariantUuid,
+ modelName, profileInfo, nsstInfoList, capabilitiesList, ranNssiPreferReuse)
+
+ execution.setVariable("nssiSelection_oofRequest",oofRequest)
+ logger.debug("Sending request to OOF: " + oofRequest)
+ }
+ /*
+ * process OOF response for RAN NSSI selection
+ */
+ def processOofResponseForRanNSS = { DelegateExecution execution ->
+ logger.debug(Prefix+"processOofResponseForRanNSS method start")
+ String oofResponse = execution.getVariable("nssiSelection_asyncCallbackResponse")
+ String requestStatus = jsonUtil.getJsonValue(oofResponse, "requestStatus")
+ if(requestStatus.equals("completed")) {
+ List<String> solution = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(oofResponse, "solutions"))
+ boolean existingNSI = jsonUtil.getJsonValue(solution.get(0), "existingNSI")
+ if(existingNSI) {
+ def sharedNSISolution = jsonUtil.getJsonValue(solution.get(0), "sharedNSISolution")
+ execution.setVariable("sharedRanNSSISolution", sharedNSISolution)
+ logger.debug("sharedRanNSSISolution from OOF "+sharedNSISolution)
+ String RANServiceInstanceId = jsonUtil.getJsonValue(solution.get(0), "sharedNSISolution.NSIId")
+ execution.setVariable("RANServiceInstanceId", RANServiceInstanceId)
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setInstanceId(RANServiceInstanceId);
+ ServiceDecomposition serviceDecomposition = execution.getVariable("ranNsstServiceDecomposition")
+ serviceDecomposition.setServiceInstance(serviceInstance);
+ execution.setVariable("ranNsstServiceDecomposition", serviceDecomposition)
+ execution.setVariable("isRspRanNssi", true)
+ }else {
+ def sliceProfiles = jsonUtil.getJsonValue(solution.get(0), "newNSISolution.sliceProfiles")
+ execution.setVariable("RanConstituentSliceProfiles", sliceProfiles)
+ logger.debug("RanConstituentSliceProfiles list from OOF "+sliceProfiles)
+ }
+ }else {
+ String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
+ logger.error("received failed status from oof "+ statusMessage)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a failed Async Response from OOF : "+statusMessage)
+ }
+
+ }
+
+ def prepareModifyAccessNssiInputs = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareModifyAccessNssiInputs method start")
+ String jobId = UUID.randomUUID().toString()
+ execution.setVariable("modifyRanNssiJobId", jobId)
+ String snssaiList = execution.getVariable("snssaiList")
+ String sliceParams = execution.getVariable("sliceParams")
+ String sliceProfileId = execution.getVariable("sliceProfileId")
+ String nsiInfo = jsonUtil.getJsonValue(sliceParams, "nsiInfo")
+ String scriptName = execution.getVariable("scriptName")
+
+ JsonObject modifySliceParams = new JsonObject()
+ modifySliceParams.addProperty("modifyAction", "allocate")
+ modifySliceParams.addProperty("snssaiList", snssaiList)
+ modifySliceParams.addProperty("sliceProfileId", sliceProfileId)
+ modifySliceParams.addProperty("nsiInfo", nsiInfo)
+ modifySliceParams.addProperty("scriptName", scriptName)
+
+ execution.setVariable("modifySliceParams", modifySliceParams.toString())
+ //create operation status in request db
+ String serviceId = execution.getVariable("RANServiceInstanceId")
+ String nsiId = execution.getVariable("nsiId")
+ logger.debug("Generated new job for Service Instance serviceId:" + serviceId + "jobId:" + jobId)
+
+ ResourceOperationStatus initStatus = new ResourceOperationStatus()
+ initStatus.setServiceId(serviceId)
+ initStatus.setOperationId(jobId)
+ initStatus.setResourceTemplateUUID(nsiId)
+ initStatus.setOperType("Modify")
+ requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
+ }
+
+ def createModifyNssiQueryJobStatus = { DelegateExecution execution ->
+ logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType("AN")
+ esrInfo.setVendor("ONAP")
+ String esrInfoString = objectMapper.writeValueAsString(esrInfo)
+ execution.setVariable("esrInfo", esrInfoString)
+ JsonObject serviceInfo = new JsonObject()
+ serviceInfo.addProperty("nssiId", execution.getVariable("RANServiceInstanceId"))
+ serviceInfo.addProperty("nsiId", execution.getVariable("nsiId"))
+ serviceInfo.addProperty("nssiName", execution.getVariable("servicename"))
+ String sST = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "sST")
+ serviceInfo.addProperty("sST", sST)
+ serviceInfo.addProperty("PLMNIdList", objectMapper.writeValueAsString(execution.getVariable("plmnIdList")))
+ serviceInfo.addProperty("globalSubscriberId", execution.getVariable("globalSubscriberId"))
+ serviceInfo.addProperty("subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
+ serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("modelInvariantUuid"))
+ serviceInfo.addProperty("serviceUuid", execution.getVariable("modelUuid"))
+ execution.setVariable("serviceInfo", serviceInfo.toString())
+ execution.setVariable("responseId", "")
+ }
+ def prepareNsstDecomposeService = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareNsstDecomposeService method start")
+ List<String> nsstInfoList = objectMapper.readValue(execution.getVariable("ranNsstInfoList"), List.class)
+ int currentIndex = execution.getVariable("currentIndex")
+ int maxIndex = execution.getVariable("maxIndex")
+ logger.debug(Prefix+"prepareNsstDecomposeService : currentIndex value - "+currentIndex+" maxIndex : "+maxIndex)
+ if(currentIndex<maxIndex) {
+ String nsstInfo = nsstInfoList.get(currentIndex)
+ String modelInvariantUuid = jsonUtil.getJsonValue(nsstInfo, "invariantUUID")
+ String modelUuid = jsonUtil.getJsonValue(nsstInfo, "UUID")
+
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ execution.setVariable("serviceInstanceId", "")
+ logger.debug("serviceModelInfo : "+serviceModelInfo)
+ currentIndex++
+ execution.setVariable("currentIndex", currentIndex)
+ }else {
+ logger.error("nsstList decomposition error ")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1000, "nsstList decomposition error ")
+ }
+
+ }
+ def processNsstDecomposition = { DelegateExecution execution ->
+ logger.debug(Prefix+"processNsstDecomposition method start")
+ ServiceDecomposition decomposedNsst = execution.getVariable("nsstServiceDecomposition")
+ logger.debug("decomposedNsst : "+decomposedNsst.toString())
+
+ String nsstType = decomposedNsst.getServiceRole() //domainType
+ String modelVersion = decomposedNsst.getModelInfo().getModelVersion()
+ String modelName = decomposedNsst.getModelInfo().getModelName()
+ String modelUuid = decomposedNsst.getModelInfo().getModelUuid()
+ String modelInvariantUuid = decomposedNsst.getModelInfo().getModelInvariantUuid()
+
+ switch(nsstType) {
+ case "AN_NF":
+ execution.setVariable("ANNF_modelInvariantUuid", modelInvariantUuid)
+ execution.setVariable("ANNF_modelUuid", modelUuid)
+ execution.setVariable("ANNF_modelVersion", modelVersion)
+ execution.setVariable("ANNF_modelName", modelName)
+ execution.setVariable("ANNF_ServiceDecomposition", decomposedNsst)
+ break
+ case "TN_FH":
+ execution.setVariable("TNFH_modelInvariantUuid", modelInvariantUuid)
+ execution.setVariable("TNFH_modelUuid", modelUuid)
+ execution.setVariable("TNFH_modelVersion", modelVersion)
+ execution.setVariable("TNFH_modelName", modelName)
+ execution.setVariable("TNFH_ServiceDecomposition", decomposedNsst)
+ break
+ case "TN_MH":
+ execution.setVariable("TNMH_modelInvariantUuid", modelInvariantUuid)
+ execution.setVariable("TNMH_modelUuid", modelUuid)
+ execution.setVariable("TNMH_modelVersion", modelVersion)
+ execution.setVariable("TNMH_modelName", modelName)
+ execution.setVariable("TNMH_ServiceDecomposition", decomposedNsst)
+ break
+ default:
+ logger.debug("No expected match found for current nsstType")
+ logger.error("No expected match found for current nsstType "+ nsstType)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current nsstType "+ nsstType)
+ }
+ boolean isAllNsstsDecomposed = false
+ int currentIndex = execution.getVariable("currentIndex")
+ int maxIndex = execution.getVariable("maxIndex")
+ if(currentIndex == maxIndex) {
+ isAllNsstsDecomposed = true
+ }
+ execution.setVariable("isAllNsstsDecomposed", isAllNsstsDecomposed)
+ }
+ /*
+ * prepare OOF request for NF RAN NSSI selection
+ */
+ def prepareOofRequestForRanNfNSS = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareOofRequestForRanNfNSS method start")
+ String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
+ logger.debug( "get NSSI option OOF Url: " + urlString)
+
+ //build oof request body
+ boolean ranNfNssiPreferReuse = execution.getVariable("ranNfNssiPreferReuse");
+ String requestId = execution.getVariable("msoRequestId")
+ String messageType = "NSSISelectionResponse"
+ List<String> ranConstituentSliceProfiles = jsonUtil.StringArrayToList(execution.getVariable("RanConstituentSliceProfiles"))
+ anNssmfUtils.createDomainWiseSliceProfiles(ranConstituentSliceProfiles, execution)
+ Map<String, Object> profileInfo = objectMapper.readValue(execution.getVariable("ranNfSliceProfile"), Map.class)
+ String modelUuid = execution.getVariable("ANNF_modelUuid")
+ String modelInvariantUuid = execution.getVariable("ANNF_modelInvariantUuid")
+ String modelName = execution.getVariable("ANNF_modelName")
+ String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
+
+ execution.setVariable("nssiSelection_Url", "/api/oof/selection/nssi/v1")
+ execution.setVariable("nssiSelection_messageType",messageType)
+ execution.setVariable("nssiSelection_correlator",requestId)
+ execution.setVariable("nssiSelection_timeout",timeout)
+
+ String oofRequest = oofUtils.buildSelectNSSIRequest(requestId, messageType, modelUuid, modelInvariantUuid, modelName, profileInfo)
+
+ execution.setVariable("nssiSelection_oofRequest",oofRequest)
+ }
+ /*
+ * process OOF response for RAN NF NSSI selection
+ */
+ def processOofResponseForRanNfNSS = { DelegateExecution execution ->
+ logger.debug(Prefix+"processOofResponseForRanNfNSS method start")
+ String oofResponse = execution.getVariable("nfNssiSelection_asyncCallbackResponse")
+ String requestStatus = jsonUtil.getJsonValue(oofResponse, "requestStatus")
+ if(requestStatus.equals("completed")) {
+ List<String> solution = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(oofResponse, "solutions"))
+ if(solution.size()>=1) {
+ String ranNfNssiId = jsonUtil.getJsonValue(solution.get(0), "NSSIId")
+ String invariantUuid = jsonUtil.getJsonValue(solution.get(0), "invariantUUID")
+ String uuid = jsonUtil.getJsonValue(solution.get(0), "UUID")
+ String nssiName = jsonUtil.getJsonValue(solution.get(0), "NSSIName")
+ execution.setVariable("RANNFServiceInstanceId", ranNfNssiId)
+ execution.setVariable("RANNFInvariantUUID", invariantUuid)
+ execution.setVariable("RANNFUUID", uuid)
+ execution.setVariable("RANNFNssiName", nssiName)
+ logger.debug("RANNFServiceInstanceId from OOF "+ranNfNssiId)
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setInstanceId(ranNfNssiId);
+ ServiceDecomposition serviceDecomposition = execution.getVariable("ANNF_ServiceDecomposition")
+ serviceDecomposition.setServiceInstance(serviceInstance);
+ execution.setVariable("ANNF_ServiceDecomposition", serviceDecomposition)
+ execution.setVariable("isRspRanNfNssi", true)
+ }else {
+ logger.debug("No solutions returned from OOF .. Create new RAN NF NSSI")
+ }
+ }else {
+ String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
+ logger.error("received failed status from oof "+ statusMessage)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a failed Async Response from OOF : "+statusMessage)
+ }
+ }
+
+ def createSliceProfilesInAai = { DelegateExecution execution ->
+ logger.debug(Prefix+"createSliceProfilesInAai method start")
+ anNssmfUtils.createSliceProfilesInAai(execution)
+ }
+
+ def processRanNfModifyRsp = { DelegateExecution execution ->
+ logger.debug(Prefix+"processRanNfModifyRsp method start")
+ anNssmfUtils.processRanNfModifyRsp(execution)
+ //create RAN NSSI
+ org.onap.aai.domain.yang.ServiceInstance ANServiceInstance = new ServiceInstance();
+ //AN instance creation
+ ANServiceInstance.setServiceInstanceId(execution.getVariable("RANServiceInstanceId"))
+ String sliceInstanceName = execution.getVariable("servicename")
+ ANServiceInstance.setServiceInstanceName(sliceInstanceName)
+ String serviceType = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "sST")
+ ANServiceInstance.setServiceType(serviceType)
+ String serviceStatus = "deactivated"
+ ANServiceInstance.setOrchestrationStatus(serviceStatus)
+ String serviceInstanceLocationid = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "plmnIdList")
+ ANServiceInstance.setServiceInstanceLocationId(serviceInstanceLocationid)
+ String serviceRole = "nssi"
+ ANServiceInstance.setServiceRole(serviceRole)
+ List<String> snssaiList = objectMapper.readValue(execution.getVariable("snssaiList"), List.class)
+ String snssai = snssaiList.get(0)
+ ANServiceInstance.setEnvironmentContext(snssai)
+ ANServiceInstance.setWorkloadContext("AN")
+
+ logger.debug("completed AN service instance build "+ ANServiceInstance.toString())
+ String msg = ""
+ try {
+
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri nssiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), execution.getVariable("RANServiceInstanceId"))
+ client.create(nssiServiceUri, ANServiceInstance)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in AnNssmfUtils.createSliceProfilesInAai " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ //end point update
+ createEndPointsInAai(execution)
+ }
+
+ def createSdnrRequest = { DelegateExecution execution ->
+ logger.debug(Prefix+"createSdnrRequest method start")
+ String callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.message.endpoint") + "/AsyncSdnrResponse/"+execution.getVariable("msoRequestId")
+ String sdnrRequest = buildSdnrAllocateRequest(execution, "allocate", "InstantiateRANSlice", callbackUrl)
+ execution.setVariable("createNSSI_sdnrRequest", sdnrRequest)
+ execution.setVariable("createNSSI_timeout", "PT10M")
+ execution.setVariable("createNSSI_correlator", execution.getVariable("msoRequestId"))
+ execution.setVariable("createNSSI_messageType", "AsyncSdnrResponse");
+ }
+
+ def processSdnrResponse = { DelegateExecution execution ->
+ logger.debug(Prefix+"processSdnrResponse method start")
+ String SDNRResponse = execution.getVariable("SDNR_asyncCallbackResponse")
+ String status = jsonUtil.getJsonValue(SDNRResponse, "status")
+ if(status.equalsIgnoreCase("success")) {
+ String nfIds = jsonUtil.getJsonValue(SDNRResponse, "nfIds")
+ execution.setVariable("ranNfIdsJson", nfIds)
+ }else {
+ String reason = jsonUtil.getJsonValue(SDNRResponse, "reason")
+ logger.error("received failed status from SDNR "+ reason)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from SDNR "+ reason)
+ }
+ logger.debug("response from SDNR "+SDNRResponse)
+ }
+
+ def updateAaiWithRANInstances = { DelegateExecution execution ->
+ logger.debug(Prefix+"updateAaiWithRANInstances method start")
+ //create RAN NSSI
+ org.onap.aai.domain.yang.ServiceInstance ANServiceInstance = new ServiceInstance();
+ org.onap.aai.domain.yang.ServiceInstance ANNFServiceInstance = new ServiceInstance();
+ //AN instance creation
+ ANServiceInstance.setServiceInstanceId(execution.getVariable("RANServiceInstanceId"))
+ String sliceInstanceName = execution.getVariable("servicename")
+ ANServiceInstance.setServiceInstanceName(sliceInstanceName)
+ String serviceType = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "sST")
+ ANServiceInstance.setServiceType(serviceType)
+ String serviceStatus = "deactivated"
+ ANServiceInstance.setOrchestrationStatus(serviceStatus)
+ String serviceInstanceLocationid = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "plmnIdList")
+ ANServiceInstance.setServiceInstanceLocationId(serviceInstanceLocationid)
+ String serviceRole = "nssi"
+ ANServiceInstance.setServiceRole(serviceRole)
+ List<String> snssaiList = objectMapper.readValue(execution.getVariable("snssaiList"), List.class)
+ String snssai = snssaiList.get(0)
+ ANServiceInstance.setEnvironmentContext(snssai)
+ ANServiceInstance.setWorkloadContext("AN")
+
+ logger.debug("completed AN service instance build "+ ANServiceInstance.toString())
+ //create RAN NF NSSI
+ ANNFServiceInstance.setServiceInstanceId(execution.getVariable("RANNFServiceInstanceId"))
+ sliceInstanceName = execution.getVariable("ANNF_modelName")
+ ANNFServiceInstance.setServiceInstanceName(sliceInstanceName)
+ ANNFServiceInstance.setServiceType(serviceType)
+ ANNFServiceInstance.setOrchestrationStatus(serviceStatus)
+ serviceInstanceLocationid = jsonUtil.getJsonValue(execution.getVariable("ranNfSliceProfile"), "plmnIdList")
+ ANNFServiceInstance.setServiceInstanceLocationId(serviceInstanceLocationid)
+ ANNFServiceInstance.setServiceRole(serviceRole)
+ snssaiList = objectMapper.readValue(execution.getVariable("snssaiList"), List.class)
+ snssai = snssaiList.get(0)
+ ANNFServiceInstance.setEnvironmentContext(snssai)
+ ANNFServiceInstance.setWorkloadContext("AN-NF")
+ logger.debug("completed AN service instance build "+ ANNFServiceInstance.toString())
+
+ String msg = ""
+ try {
+
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri nssiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), execution.getVariable("RANServiceInstanceId"))
+ client.create(nssiServiceUri, ANServiceInstance)
+
+ AAIResourceUri nssiServiceUri1 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), execution.getVariable("RANNFServiceInstanceId"))
+ client.create(nssiServiceUri1, ANNFServiceInstance)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in AnNssmfUtils.createSliceProfilesInAai " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ //end point update
+ createEndPointsInAai(execution)
+ }
+ def prepareTnFhRequest = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareTnFhRequest method start")
+
+ String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_FH", "allocate")
+ String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+
+ if (nssmfResponse != null) {
+ execution.setVariable("nssmfResponse", nssmfResponse)
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TNFH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ logger.debug("Exit prepareTnFhRequest")
+
+ }
+ def prepareTnMhRequest = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareTnMhRequest method start")
+
+ String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_MH", "allocate")
+ String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+
+ if (nssmfResponse != null) {
+ execution.setVariable("nssmfResponse", nssmfResponse)
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TNMH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ logger.debug("Exit prepareTnMhRequest")
+ }
+
+ def createFhAllocateNssiJobQuery = { DelegateExecution execution ->
+ logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
+ createTnAllocateNssiJobQuery(execution, "TN_FH")
+ }
+
+ def createMhAllocateNssiJobQuery = { DelegateExecution execution ->
+ logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
+ createTnAllocateNssiJobQuery(execution, "TN_MH")
+ }
+
+ private void createTnAllocateNssiJobQuery(DelegateExecution execution, String domainType) {
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType("TN")
+ esrInfo.setVendor("ONAP")
+ String esrInfoString = objectMapper.writeValueAsString(esrInfo)
+ execution.setVariable("esrInfo", esrInfoString)
+ JsonObject serviceInfo = new JsonObject()
+ serviceInfo.addProperty("nssiId", null)
+ serviceInfo.addProperty("nsiId", execution.getVariable("nsiId"))
+ String sST = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "sST")
+ serviceInfo.addProperty("sST", sST)
+ serviceInfo.addProperty("PLMNIdList", objectMapper.writeValueAsString(execution.getVariable("plmnIdList")))
+ serviceInfo.addProperty("globalSubscriberId", execution.getVariable("globalSubscriberId"))
+ serviceInfo.addProperty("subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
+ if(domainType.equals("TN_FH")) {
+ serviceInfo.addProperty("nssiName", execution.getVariable("TNFH_modelName"))
+ serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("TNFH_modelInvariantUuid"))
+ serviceInfo.addProperty("serviceUuid", execution.getVariable("TNFH_modelUuid"))
+ }else if(domainType.equals("TN_MH")) {
+ serviceInfo.addProperty("nssiName", execution.getVariable("TNMH_modelName"))
+ serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("TNMH_modelInvariantUuid"))
+ serviceInfo.addProperty("serviceUuid", execution.getVariable("TNMH_modelUuid"))
+ }
+ execution.setVariable("serviceInfo", serviceInfo.toString())
+ execution.setVariable("responseId", "")
+ }
+
+ def processFhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
+ logger.debug(Prefix+"processJobStatusRsp method start")
+ String jobResponse = execution.getVariable("TNFH_jobResponse")
+ logger.debug("Job status response "+jobResponse)
+ String status = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.status")
+ String nssi = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.nssi")
+ if(status.equalsIgnoreCase("finished")) {
+ execution.setVariable("TNFH_NSSI", nssi)
+ logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
+ }
+ else {
+ String statusDescription = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.statusDescription")
+ logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ }
+ }
+
+ def processMhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
+ logger.debug(Prefix+"processJobStatusRsp method start")
+ String jobResponse = execution.getVariable("TNMH_jobResponse")
+ logger.debug("Job status response "+jobResponse)
+ String status = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.status")
+ String nssi = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.nssi")
+ if(status.equalsIgnoreCase("finished")) {
+ execution.setVariable("TNMH_NSSI", nssi)
+ logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
+ }
+ else {
+ String statusDescription = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.statusDescription")
+ logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ }
+ }
+
+ def processModifyJobStatusRsp = { DelegateExecution execution ->
+ logger.debug(Prefix+"processJobStatusRsp method start")
+ String jobResponse = execution.getVariable("jobResponse")
+ logger.debug("Job status response "+jobResponse)
+ String status = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.status")
+ String nssi = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.nssi")
+ if(status.equalsIgnoreCase("finished")) {
+ logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
+ }
+ else {
+ String statusDescription = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.statusDescription")
+ logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ }
+ }
+
+ def updateAairelationships = { DelegateExecution execution ->
+ logger.debug(Prefix + "updateAairelationships Start")
+ String msg = ""
+ try {
+ def ANNF_serviceInstanceId = execution.getVariable("RANNFServiceInstanceId")
+ def TNFH_serviceInstanceId = execution.getVariable("TNFH_NSSI")
+ def TNMH_serviceInstanceId = execution.getVariable("TNMH_NSSI")
+ def AN_profileInstanceId = execution.getVariable("sliceProfileId")
+ def AN_NSSI = execution.getVariable("RANServiceInstanceId")
+ def ANNF_profileInstanceId = execution.getVariable("ANNF_sliceProfileInstanceId")
+ def TNFH_profileInstanceId = execution.getVariable("TNFH_sliceProfileInstanceId")
+ def TNMH_profileInstanceId = execution.getVariable("TNMH_sliceProfileInstanceId")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ Relationship ANNF_relationship = new Relationship()
+ Relationship TNFH_relationship = new Relationship()
+ Relationship TNMH_relationship = new Relationship()
+
+ String ANNF_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${ANNF_profileInstanceId}"
+ String TNFH_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNFH_profileInstanceId}"
+ String TNMH_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNMH_profileInstanceId}"
+
+ String ANNF_NSSI_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${ANNF_serviceInstanceId}"
+ String TNFH_NSSI_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNFH_serviceInstanceId}"
+ String TNMH_NSSI_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNMH_serviceInstanceId}"
+
+ ANNF_relationship.setRelatedLink(ANNF_relatedLink)
+ ANNF_relationship.setRelatedTo("service-instance")
+ ANNF_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
+ TNFH_relationship.setRelatedLink(TNFH_relatedLink)
+ TNFH_relationship.setRelatedTo("service-instance")
+ TNFH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
+ TNMH_relationship.setRelatedLink(TNMH_relatedLink)
+ TNMH_relationship.setRelatedTo("service-instance")
+ TNMH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
+
+ // create SliceProfile and NSSI relationship in AAI
+ anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship,ANNF_serviceInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship,TNFH_serviceInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship,TNMH_serviceInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship,AN_profileInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship,AN_profileInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship,AN_profileInstanceId)
+
+ //create AN NSSI and ANNF,TNFH,TNMH relationship in AAI
+ ANNF_relationship.setRelatedLink(ANNF_NSSI_relatedLink)
+ TNFH_relationship.setRelatedLink(TNFH_NSSI_relatedLink)
+ TNMH_relationship.setRelatedLink(TNMH_NSSI_relatedLink)
+ anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship,AN_NSSI)
+ anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship,AN_NSSI)
+ anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship,AN_NSSI)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+
+ msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+
+ /**
+ * update operation status in request db
+ *
+ */
+ def prepareOperationStatusUpdate = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareOperationStatusUpdate Start")
+
+ String serviceId = execution.getVariable("dummyServiceId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String nssiId = execution.getVariable("RANServiceInstanceId")
+ logger.debug("Service Instance serviceId:" + serviceId + " jobId:" + jobId)
+
+ ResourceOperationStatus updateStatus = new ResourceOperationStatus()
+ updateStatus.setServiceId(serviceId)
+ updateStatus.setOperationId(jobId)
+ updateStatus.setResourceTemplateUUID(nsiId)
+ updateStatus.setResourceInstanceID(nssiId)
+ updateStatus.setOperType("Allocate")
+ updateStatus.setProgress(100)
+ updateStatus.setStatus("finished")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
+
+ logger.debug(Prefix + "prepareOperationStatusUpdate Exit")
+ }
+
+ def prepareFailedOperationStatusUpdate = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareFailedOperationStatusUpdate Start")
+
+ String serviceId = execution.getVariable("dummyServiceId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String nssiId = execution.getVariable("RANServiceInstanceId")
+ logger.debug("Service Instance serviceId:" + serviceId + " jobId:" + jobId)
+
+ ResourceOperationStatus updateStatus = new ResourceOperationStatus()
+ updateStatus.setServiceId(serviceId)
+ updateStatus.setOperationId(jobId)
+ updateStatus.setResourceTemplateUUID(nsiId)
+ updateStatus.setResourceInstanceID(nssiId)
+ updateStatus.setOperType("Allocate")
+ updateStatus.setProgress(0)
+ updateStatus.setStatus("failed")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
+ }
+
+ private String buildSdnrAllocateRequest(DelegateExecution execution, String action, String rpcName, String callbackUrl) {
+
+ String requestId = execution.getVariable("msoRequestId")
+ Date date = new Date().getTime()
+ Timestamp time = new Timestamp(date)
+ Map<String,Object> sliceProfile = objectMapper.readValue(execution.getVariable("ranNfSliceProfile"), Map.class)
+ sliceProfile.put("sliceProfileId", execution.getVariable("ANNF_sliceProfileInstanceId"))
+ sliceProfile.put("maxNumberofConns", sliceProfile.get("maxNumberofPDUSessions"))
+ sliceProfile.put("uLThptPerSlice", sliceProfile.get("expDataRateUL"))
+ sliceProfile.put("dLThptPerSlice", sliceProfile.get("expDataRateDL"))
+ String sliceProfileString = objectMapper.writeValueAsString(sliceProfile)
+ JsonObject response = new JsonObject()
+ JsonObject body = new JsonObject()
+ JsonObject input = new JsonObject()
+ JsonObject commonHeader = new JsonObject()
+ JsonObject payload = new JsonObject()
+ JsonObject payloadInput = new JsonObject()
+ commonHeader.addProperty("TimeStamp", time.toString())
+ commonHeader.addProperty("APIver", "1.0")
+ commonHeader.addProperty("RequestID", requestId)
+ commonHeader.addProperty("SubRequestID", "1")
+ commonHeader.add("RequestTrack", new JsonObject())
+ commonHeader.add("Flags", new JsonObject())
+ payloadInput.addProperty("sliceProfile", sliceProfileString)
+ payloadInput.addProperty("RANNSSIId", execution.getVariable("RANServiceInstanceId"))
+ payloadInput.addProperty("NSIID", execution.getVariable("nsiId"))
+ payloadInput.addProperty("RANNFNSSIId", execution.getVariable("RANNFServiceInstanceId"))
+ payloadInput.addProperty("callbackURL", callbackUrl)
+ payloadInput.add("additionalproperties", new JsonObject())
+ payload.add("input", payloadInput)
+ input.add("CommonHeader", commonHeader)
+ input.addProperty("Action", action)
+ input.add("Payload", payload)
+ body.add("input", input)
+ response.add("body", body)
+ response.addProperty("version", "1.0")
+ response.addProperty("rpc-name", rpcName)
+ response.addProperty("correlation-id", requestId+"-1")
+ response.addProperty("type", "request")
+ return response.toString()
+ }
+
+ private void createEndPointsInAai(DelegateExecution execution) {
+ String type = "endpoint"
+ String function = "transport_EP"
+ int prefixLength = 24
+ String addressFamily = "ipv4"
+ //BH RAN end point update
+ String bh_endpoint = execution.getVariable("bh_endpoint")
+ String bh_routeId = UUID.randomUUID().toString()
+ execution.setVariable("tranportEp_ID_bh", bh_routeId)
+ String role = "CU"
+ String CU_IpAddress = jsonUtil.getJsonValue(bh_endpoint, "IpAddress")
+ String LogicalLinkId = jsonUtil.getJsonValue(bh_endpoint, "LogicalLinkId")
+ String nextHopInfo = jsonUtil.getJsonValue(bh_endpoint, "nextHopInfo")
+ NetworkRoute bh_ep = new NetworkRoute()
+ bh_ep.setRouteId(bh_routeId)
+ bh_ep.setFunction(function)
+ bh_ep.setRole(role)
+ bh_ep.setType(type)
+ bh_ep.setIpAddress(CU_IpAddress)
+ bh_ep.setLogicalInterfaceId(LogicalLinkId)
+ bh_ep.setNextHop(nextHopInfo)
+ bh_ep.setPrefixLength(prefixLength)
+ bh_ep.setAddressFamily(addressFamily)
+ //FH RAN end points update
+ //RU
+ String RU_routeId = UUID.randomUUID().toString()
+ execution.setVariable("tranportEp_ID_RU", RU_routeId)
+ role = "RU"
+ NetworkRoute RU_ep = new NetworkRoute()
+ RU_ep.setRouteId(RU_routeId)
+ RU_ep.setFunction(function)
+ RU_ep.setRole(role)
+ RU_ep.setType(type)
+ RU_ep.setIpAddress("192.168.100.4")
+ RU_ep.setLogicalInterfaceId("1234")
+ RU_ep.setNextHop("Host1")
+ RU_ep.setPrefixLength(prefixLength)
+ RU_ep.setAddressFamily(addressFamily)
+ //DU Ingress
+ String DUIN_routeId = UUID.randomUUID().toString()
+ execution.setVariable("tranportEp_ID_DUIN", DUIN_routeId)
+ role = "DU"
+ NetworkRoute DU_ep = new NetworkRoute()
+ DU_ep.setRouteId(DUIN_routeId)
+ DU_ep.setFunction(function)
+ DU_ep.setRole(role)
+ DU_ep.setType(type)
+ DU_ep.setIpAddress("192.168.100.5")
+ DU_ep.setLogicalInterfaceId("1234")
+ DU_ep.setNextHop("Host2")
+ DU_ep.setPrefixLength(prefixLength)
+ DU_ep.setAddressFamily(addressFamily)
+ //MH RAN end point update
+ //DUEG
+ String DUEG_routeId = UUID.randomUUID().toString()
+ execution.setVariable("tranportEp_ID_DUEG", DUEG_routeId)
+ NetworkRoute DUEG_ep = new NetworkRoute()
+ DU_ep.setRouteId(DUEG_routeId)
+ DU_ep.setNextHop("Host3")
+ //CUIN
+ String CUIN_routeId = UUID.randomUUID().toString()
+ execution.setVariable("tranportEp_ID_CUIN", CUIN_routeId)
+ NetworkRoute CUIN_ep = new NetworkRoute()
+ CUIN_ep.setRouteId(CUIN_routeId)
+ CUIN_ep.setFunction(function)
+ CUIN_ep.setRole(role)
+ CUIN_ep.setType(type)
+ CUIN_ep.setIpAddress("192.168.100.6")
+ CUIN_ep.setLogicalInterfaceId("1234")
+ CUIN_ep.setNextHop("Host4")
+ CUIN_ep.setPrefixLength(prefixLength)
+ CUIN_ep.setAddressFamily(addressFamily)
+ try {
+ AAIResourcesClient client = new AAIResourcesClient()
+ logger.debug("creating bh endpoint . ID : "+bh_routeId+" node details : "+bh_ep.toString())
+ AAIResourceUri networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), bh_routeId)
+ client.create(networkRouteUri, bh_ep)
+ logger.debug("creating RU endpoint . ID : "+RU_routeId+" node details : "+RU_ep.toString())
+ networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), RU_routeId)
+ client.create(networkRouteUri, RU_ep)
+ logger.debug("creating DUIN endpoint . ID : "+DUIN_routeId+" node details : "+DU_ep.toString())
+ networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), DUIN_routeId)
+ client.create(networkRouteUri, DU_ep)
+ logger.debug("creating DUEG endpoint . ID : "+DUEG_routeId+" node details : "+DU_ep.toString())
+ networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), DUEG_routeId)
+ client.create(networkRouteUri, DU_ep)
+ logger.debug("creating CUIN endpoint . ID : "+CUIN_routeId+" node details : "+CUIN_ep.toString())
+ networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), CUIN_routeId)
+ client.create(networkRouteUri, CUIN_ep)
+ //relationship b/w bh_ep and RAN NSSI
+ def AN_NSSI = execution.getVariable("RANServiceInstanceId")
+ Relationship relationship = new Relationship()
+ String relatedLink = "aai/v21/network/network-routes/network-route/${bh_routeId}"
+ relationship.setRelatedLink(relatedLink)
+ relationship.setRelatedTo("network-route")
+ relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
+ anNssmfUtils.createRelationShipInAAI(execution, relationship, AN_NSSI)
+ def ANNF_serviceInstanceId = execution.getVariable("RANNFServiceInstanceId")
+ relatedLink = "aai/v21/network/network-routes/network-route/${RU_routeId}"
+ relationship.setRelatedLink(relatedLink)
+ anNssmfUtils.createRelationShipInAAI(execution, relationship, ANNF_serviceInstanceId)
+ relatedLink = "aai/v21/network/network-routes/network-route/${DUIN_routeId}"
+ relationship.setRelatedLink(relatedLink)
+ anNssmfUtils.createRelationShipInAAI(execution, relationship, ANNF_serviceInstanceId)
+ relatedLink = "aai/v21/network/network-routes/network-route/${DUEG_routeId}"
+ relationship.setRelatedLink(relatedLink)
+ anNssmfUtils.createRelationShipInAAI(execution, relationship, ANNF_serviceInstanceId)
+ relatedLink = "aai/v21/network/network-routes/network-route/${CUIN_routeId}"
+ relationship.setRelatedLink(relatedLink)
+ anNssmfUtils.createRelationShipInAAI(execution, relationship, ANNF_serviceInstanceId)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in createEndPointsInAai " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNSSI.groovy
new file mode 100644
index 0000000000..64c36e7026
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNSSI.groovy
@@ -0,0 +1,157 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Tech Mahindra
+ * ================================================================================
+ * 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.apache.commons.collections.map.HashedMap
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.beans.nsmf.SliceTaskParams
+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.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.domain.ServiceProxy
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.OperationStatus
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.onap.so.serviceinstancebeans.ModelInfo
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import static org.apache.commons.lang3.StringUtils.*;
+import com.fasterxml.jackson.databind.ObjectMapper
+import groovy.json.JsonSlurper
+import javax.ws.rs.core.Response
+import org.onap.so.bpmn.common.scripts.OofUtils
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+
+class DoAllocateCoreNSSI extends AbstractServiceTaskProcessor {
+ String Prefix="DACNSSI_"
+ private static final Logger logger = LoggerFactory.getLogger( DoAllocateCoreNSSI.class);
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
+ JsonUtils jsonUtil = new JsonUtils()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ ObjectMapper mapper = new ObjectMapper()
+ OofUtils oofUtils = new OofUtils()
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix+" **** Enter DoAllocateCoreNSSI ::: preProcessRequest ****")
+ execution.setVariable("prefix", Prefix)
+ String msg = ""
+ //Get SliceProfile from sliceParams JSON
+ String sliceProfile = jsonUtil.getJsonValue(execution.getVariable("sliceParams"), "sliceProfile")
+ if (isBlank(sliceProfile)) {
+ msg = "Slice Profile is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("sliceProfile", sliceProfile)
+ }
+ String coreServiceInstanceId = UUID.randomUUID().toString()
+ execution.setVariable("coreServiceInstanceId", coreServiceInstanceId)
+ logger.debug(Prefix+" **** Exit DoAllocateCoreNSSI ::: preProcessRequest ****")
+ }
+ /**
+ * Query NSST name from CatalogDB
+ * @param execution
+ */
+ void getNSSTName(DelegateExecution execution){
+ logger.debug(Prefix+" **** Enter DoAllocateCoreNSSI ::: getNSSTName ****")
+ String nsstModelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ try{
+ String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution, nsstModelInvariantUuid)
+ logger.debug("***** JSON Response is: "+json)
+ String nsstName = jsonUtil.getJsonValue(json, "serviceResources.modelInfo.modelName") ?: ""
+ String networkServiceModelInfo = jsonUtil.getJsonValue(json, "serviceResources.serviceProxy.modelInfo") ?: ""
+
+ execution.setVariable("networkServiceModelInfo", networkServiceModelInfo)
+ logger.debug("***** nsstName is: "+ nsstName)
+ execution.setVariable("nsstName",nsstName)
+ }catch(BpmnError e){
+ throw e
+ } catch (Exception ex){
+ String msg = "Exception in preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix+" **** Exit DoAllocateCoreNSSI ::: getNSSTName ****")
+ }
+ void prepareOOFRequest(DelegateExecution execution){
+ logger.debug(Prefix+" **** Enter DoAllocateCoreNSSI ::: prepareOOFRequest ****")
+ //API Path
+ String apiPath = "/api/oof/selection/nssi/v1"
+ logger.debug("API path for DoAllocateCoreNSSI: "+apiPath)
+ execution.setVariable("NSSI_apiPath", apiPath)
+ //Setting correlator as requestId
+ String requestId = execution.getVariable("msoRequestId")
+ execution.setVariable("NSSI_correlator", requestId)
+ //Setting messageType for all Core slice as cn
+ String messageType = "cn"
+ execution.setVariable("NSSI_messageType", messageType)
+ //Is there any specific timeout we have to set or else we don't need to send
+ //if blank will be set default value in DoHandleOofRequest
+ String timeout = "PT30M"
+ execution.setVariable("NSSI_timeout", timeout)
+ Map<String, Object> profileInfo = mapper.readValue(execution.getVariable("sliceProfile"), Map.class)
+ String nsstModelUuid = execution.getVariable("modelUuid")
+ String nsstModelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String nsstName = execution.getVariable("nsstName")
+ String oofRequest = oofUtils.buildSelectNSSIRequest(requestId, messageType, nsstModelUuid, nsstModelInvariantUuid, nsstName, profileInfo)
+ logger.debug("**** OOfRequest for Core Slice: "+oofRequest)
+ execution.setVariable("NSSI_oofRequest", oofRequest)
+ logger.debug(Prefix+" **** Exit DoAllocateCoreNSSI ::: prepareOOFRequest ****")
+ }
+
+ void processOOFAsyncResponse(DelegateExecution execution) {
+ logger.debug(Prefix+ " **** Enter DoAllocateCoreNSSI ::: processOOFAsyncResponse ****")
+ String OOFResponse = execution.getVariable("NSSI_asyncCallbackResponse")
+ String requestStatus = jsonUtil.getJsonValue(OOFResponse, "requestStatus")
+ logger.debug("NSSI OOFResponse is: " + OOFResponse)
+ execution.setVariable("OOFResponse", OOFResponse)
+ String solutions =""
+ if(requestStatus.equals("completed")) {
+ solutions = jsonUtil.getJsonValue(OOFResponse, "solutions")
+ } else {
+ String statusMessage = jsonUtil.getJsonValue(OOFResponse, "statusMessage")
+ logger.error("received failed status from oof "+ statusMessage)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a failed Async Response from OOF : "+statusMessage)
+ }
+ execution.setVariable("solutions", solutions)
+ logger.debug(Prefix+" **** Exit DoAllocateCoreNSSI ::: processOOFAsyncResponse ****")
+ }
+
+ void prepareFailedOperationStatusUpdate(DelegateExecution execution){
+ logger.debug(Prefix + " **** Enter DoAllocateCoreNSSI ::: prepareFailedOperationStatusUpdate ****")
+ String serviceId = execution.getVariable("nssiId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operationType = execution.getVariable("operationType")
+ ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
+ resourceOperationStatus.setServiceId(serviceId)
+ resourceOperationStatus.setOperationId(jobId)
+ resourceOperationStatus.setResourceTemplateUUID(nsiId)
+ resourceOperationStatus.setOperType(operationType)
+ resourceOperationStatus.setProgress(0)
+ resourceOperationStatus.setStatus("failed")
+ resourceOperationStatus.setStatusDescription("Core NSSI Allocate Failed")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
+ logger.debug(Prefix + " **** Exit DoAllocateCoreNSSI ::: prepareFailedOperationStatusUpdate ****")
+ }
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNonSharedSlice.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNonSharedSlice.groovy
new file mode 100644
index 0000000000..2a31997cd5
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNonSharedSlice.groovy
@@ -0,0 +1,432 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Tech Mahindra
+ * ================================================================================
+ * 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 groovy.json.JsonOutput
+
+import static org.hamcrest.CoreMatchers.instanceOf
+
+import javax.json.JsonArray
+import javax.ws.rs.core.Response
+import org.apache.commons.collections.map.HashedMap
+import org.apache.commons.lang.StringEscapeUtils
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.json.JSONArray
+import org.json.JSONObject
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+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.ExternalAPIUtil
+import org.onap.so.bpmn.common.scripts.ExternalAPIUtilFactory
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.db.request.beans.OperationStatus
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.aai.domain.yang.v19.ServiceInstance
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.AAIEdgeLabel
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+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.slf4j.Logger
+import org.slf4j.LoggerFactory
+import org.springframework.http.HttpEntity
+
+import javax.ws.rs.NotFoundException
+
+class DoAllocateCoreNonSharedSlice extends AbstractServiceTaskProcessor {
+ String Prefix="DACNSNSSI_"
+ private static final Logger logger = LoggerFactory.getLogger( DoAllocateCoreNonSharedSlice.class);
+ private CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
+ private RequestDBUtil requestDBUtil = new RequestDBUtil()
+ private ExceptionUtil exceptionUtil = new ExceptionUtil()
+ private JsonUtils jsonUtil = new JsonUtils()
+
+ @Override
+ public void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix+ "**** Enter DoAllocateCoreNonSharedSlice::: preProcessRequest ****")
+ String nssiServiceInstanceId= execution.getVariable("serviceInstanceId")
+ execution.setVariable("nssiServiceInstanceId", nssiServiceInstanceId)
+ //Set orchestration-status as created
+ execution.setVariable("orchestrationStatus", "created")
+ //networkServiceName
+ String networkServiceName = jsonUtil.getJsonValue(execution.getVariable("networkServiceModelInfo"), "modelName") ?: ""
+ execution.setVariable("networkServiceName", networkServiceName.replaceAll(" Service Proxy", ""))
+ //networkServiceModelUuid
+ String networkServiceModelUuid = jsonUtil.getJsonValue(execution.getVariable("networkServiceModelInfo"), "modelUuid") ?: ""
+ execution.setVariable("networkServiceModelUuid", networkServiceModelUuid)
+ logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice::: preProcessRequest ****")
+ }
+
+ void createNSSIinAAI(DelegateExecution execution) {
+ logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: Enter createNSSIinAAI ****")
+ String msg=""
+ String serviceInstanceId= execution.getVariable("nssiServiceInstanceId")
+ logger.debug("ServiceInstanceId: "+serviceInstanceId)
+ try {
+ String serviceType = execution.getVariable("subscriptionServiceType")
+ String oStatus = execution.getVariable("orchestrationStatus")
+ //Get workload context and environment context from DB
+ String environmentContext = ""
+ String workloadContext =""
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ try{
+ String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid )
+ logger.debug("JSON Response from DB: "+json)
+ environmentContext = jsonUtil.getJsonValue(json, "serviceResources.environmentContext") ?: ""
+ workloadContext = jsonUtil.getJsonValue(json, "serviceResources.workloadContext") ?: ""
+ logger.debug("Env Context is: "+ environmentContext)
+ logger.debug("Workload Context is: "+ workloadContext)
+ } catch(BpmnError e){
+ throw e
+ } catch (Exception ex){
+ msg = "Exception in createNSSIinAAI ::: DoAllocateCoreNonSharedSlice " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ String serviceInstanceName = "nssi_"+execution.getVariable("nsstName")
+ ServiceInstance si = new ServiceInstance()
+ si.setServiceInstanceId(execution.getVariable("nssiServiceInstanceId"))
+ si.setServiceInstanceName(serviceInstanceName)
+ si.setServiceType(serviceType)
+ si.setServiceRole("nssi")
+ si.setOrchestrationStatus(oStatus)
+ si.setModelInvariantId(modelInvariantUuid)
+ si.setModelVersionId(execution.getVariable("modelUuid"))
+ si.setEnvironmentContext(environmentContext)
+ si.setWorkloadContext(workloadContext)
+ logger.debug("AAI service Instance Request Payload : "+si.toString())
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), serviceType, serviceInstanceId)
+ Response response = getAAIClient().create(uri, si)
+ if(response.getStatus()!=200) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, response.getStatus(), "AAI instance creation failed")
+ }
+ execution.setVariable("nssiServiceInstance", si)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception ex) {
+ msg = "Exception in create AAI Instance" + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix+ " Exit DoAllocateCoreNonSharedSlice ::: Enter createNSSIinAAI ****")
+ }
+
+ public void prepareServiceOrderRequest(DelegateExecution execution) {
+ logger.debug("**** Enter DoAllocateCoreNonSharedSlice ::: prepareServiceOrderRequest ****")
+ String extAPIPath = UrnPropertiesReader.getVariable("extapi.endpoint", execution) + '/serviceOrder'
+ execution.setVariable("ExternalAPIURL", extAPIPath)
+ ObjectMapper objectMapper = new ObjectMapper();
+ Map<String, Object> serviceOrder = new LinkedHashMap()
+ //ExternalId
+ serviceOrder.put("externalId", "ONAP001")
+ //Requested Start Date
+ String requestedStartDate = utils.generateCurrentTimeInUtc()
+ String requestedCompletionDate = utils.generateCurrentTimeInUtc()
+ serviceOrder.put("requestedStartDate", requestedStartDate)
+ serviceOrder.put("requestedCompletionDate", requestedCompletionDate)
+ //RelatedParty Fields
+ String relatedPartyId = execution.getVariable("globalSubscriberId")
+ String relatedPartyRole = "ONAPcustomer"
+ Map<String, String> relatedParty = new LinkedHashMap()
+ relatedParty.put("id", relatedPartyId)
+ relatedParty.put("role", relatedPartyRole)
+ List<Map<String, String>> relatedPartyList = new ArrayList()
+ relatedPartyList.add(relatedParty)
+ serviceOrder.put("relatedParty", relatedPartyList)
+ Map<String, Object> orderItem = new LinkedHashMap()
+ //orderItem id
+ String orderItemId = "1"
+ orderItem.put("id", orderItemId)
+ //order item action will always be add as we are triggering request for instantiation
+ String orderItemAction = "add"
+ orderItem.put("action", orderItemAction)
+ // service Details
+ Map<String, Object> service = new LinkedHashMap()
+ //ServiceName
+ String serviceName= "nsi_"+execution.getVariable("networkServiceName")
+ service.put("name", serviceName)
+ // Service Type
+ service.put("serviceType", execution.getVariable("serviceType"))
+ //Service State
+ service.put("serviceState", "active")
+ Map<String, String> serviceSpecification = new LinkedHashMap()
+ serviceSpecification.put("id", execution.getVariable("networkServiceModelUuid"))
+ service.put("serviceSpecification", serviceSpecification)
+ //serviceCharacteristic List
+ List serviceCharacteristicList = new ArrayList()
+ Map<String, Object> serviceCharacteristic = objectMapper.readValue(execution.getVariable("sliceProfile"), Map.class);
+ List serviceCharacteristicListMap = retrieveServiceCharacteristicsAsKeyValue(serviceCharacteristic)
+ logger.debug("serviceCharacteristicListMap "+serviceCharacteristicListMap)
+ serviceCharacteristicList.add(serviceCharacteristic)
+ //service.put("serviceCharacteristic", serviceCharacteristicList)
+ service.put("serviceCharacteristic", serviceCharacteristicListMap)
+ orderItem.put("service", service)
+ List<Map<String, String>> orderItemList = new ArrayList()
+ orderItemList.add(orderItem)
+ serviceOrder.put("orderItem", orderItemList)
+ String jsonServiceOrder = objectMapper.writeValueAsString(serviceOrder);
+ logger.debug("******* ServiceOrder :: "+jsonServiceOrder)
+ execution.setVariable("serviceOrderRequest", jsonServiceOrder)
+ logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: prepareServiceOrderRequest****")
+ }
+
+ private List retrieveServiceCharacteristicsAsKeyValue(Map serviceCharacteristics) {
+ logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: retrieveServiceCharacteristicsAsKeyValue ****")
+ List serviceCharacteristicsList = new ArrayList()
+ ObjectMapper mapperObj = new ObjectMapper();
+ Map<String, Object> serviceCharacteristicsObject = new LinkedHashMap()
+ for (Map.Entry<String, Integer> entry : serviceCharacteristics.entrySet()) {
+ Map<String, Object> ServiceCharacteristicValueObject = new LinkedHashMap<>()
+ System.out.println(entry.getKey() + ":" + entry.getValue());
+ //For G Release we are sending single value from snssaiList
+ if(entry.getKey().equals("snssaiList")) {
+ List sNssaiValue = entry.getValue()
+ serviceCharacteristicsObject.put("name", "snssai")
+ ServiceCharacteristicValueObject.put("serviceCharacteristicValue", sNssaiValue.get(0))
+ serviceCharacteristicsObject.put("value", ServiceCharacteristicValueObject)
+ }
+ }
+ serviceCharacteristicsList.add(serviceCharacteristicsObject)
+ logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: retrieveServiceCharacteristicsAsKeyValue ****")
+ return serviceCharacteristicsList
+ }
+
+ public void postNBIServiceOrder(DelegateExecution execution) {
+ logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: postNBIServiceOrder ****")
+ String msg=""
+ try {
+ String extAPIPath = execution.getVariable("ExternalAPIURL")
+ String payload = execution.getVariable("serviceOrderRequest")
+ logger.debug("externalAPIURL is: " + extAPIPath)
+ logger.debug("ServiceOrder payload is: " + payload)
+ ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create()
+ execution.setVariable("ServiceOrderId", "")
+ Response response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload)
+ int responseCode = response.getStatus()
+ execution.setVariable("PostServiceOrderResponseCode", responseCode)
+ logger.debug("Post ServiceOrder response code is: " + responseCode)
+ String extApiResponse = response.readEntity(String.class)
+ JSONObject responseObj = new JSONObject(extApiResponse)
+ execution.setVariable("PostServiceOrderResponse", extApiResponse)
+ logger.debug("ServiceOrder response body is: " + extApiResponse)
+ //Process Response
+ if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
+ //200 OK 201 CREATED 202 ACCEPTED
+ {
+ logger.debug("Post ServiceOrder Received a Good Response")
+ String serviceOrderId = responseObj.get("id")
+ execution.setVariable("ServiceOrderId", serviceOrderId)
+ logger.info("Post ServiceOrderid is: " + serviceOrderId)
+ }
+ else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Post ServiceOrder Received a bad response from extAPI serviceOrder API")
+ }
+ }catch (BpmnError e) {
+ throw e;
+ } catch (Exception ex) {
+ msg = "Exception in ServiceOrder ExtAPI" + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug("**** Exit DoAllocateCoreNonSharedSlice ::: postNBIServiceOrder ****")
+ }
+
+ public void getNBIServiceOrderProgress(DelegateExecution execution) {
+ logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: getNBIServiceOrderProgress ****")
+ String msg=""
+ try {
+ String extAPIPath = execution.getVariable("ExternalAPIURL")
+ extAPIPath += "/" + execution.getVariable("ServiceOrderId")
+ logger.debug("getNBIServiceOrderProgress externalAPIURL is: " + extAPIPath)
+ ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create()
+ Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath)
+ int responseCode = response.getStatus()
+ execution.setVariable("GetServiceOrderResponseCode", responseCode)
+ logger.debug("Get ServiceOrder response code is: " + responseCode)
+ String extApiResponse = response.readEntity(String.class)
+ JSONObject responseObj = new JSONObject(extApiResponse)
+ execution.setVariable("GetServiceOrderResponse", extApiResponse)
+ logger.debug("Create response body is: " + extApiResponse)
+ //Process Response //200 OK 201 CREATED 202 ACCEPTED
+ if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
+ {
+ logger.debug("Get Create ServiceOrder Received a Good Response")
+ String orderState = responseObj.get("state")
+ if("REJECTED".equalsIgnoreCase(orderState)) {
+ prepareFailedOperationStatusUpdate(execution)
+ return
+ }
+ JSONArray items = responseObj.getJSONArray("orderItem")
+ JSONObject item = items.get(0)
+ JSONObject service = item.get("service")
+ String networkServiceId = service.get("id")
+ if (networkServiceId == null || networkServiceId.equals("null")) {
+ prepareFailedOperationStatusUpdate(execution)
+ return
+ }
+ execution.setVariable("networkServiceId", networkServiceId)
+ String serviceOrderState = item.get("state")
+ execution.setVariable("ServiceOrderState", serviceOrderState)
+ // Get serviceOrder State and process progress
+ if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) {
+ execution.setVariable("status", "processing")
+ }
+ else if("INPROGRESS".equalsIgnoreCase(serviceOrderState)) {
+ execution.setVariable("status", "processing")
+ }
+ else if("COMPLETED".equalsIgnoreCase(serviceOrderState)) {
+ execution.setVariable("status", "completed")
+ }
+ else if("FAILED".equalsIgnoreCase(serviceOrderState)) {
+ msg = "ServiceOrder failed"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ else {
+ msg = "ServiceOrder failed"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+ else{
+ msg = "Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode
+ prepareFailedOperationStatusUpdate(execution)
+ }
+
+ }catch(Exception e){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e.getMessage())
+ }
+ logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: getNBIServiceOrderProgress ****")
+ }
+
+ /**
+ * delay 5 sec
+ */
+ public void timeDelay(DelegateExecution execution) {
+ try {
+ logger.debug(Prefix+ " **** DoAllocateCoreNonSharedSlice ::: timeDelay going to sleep for 5 sec")
+ Thread.sleep(5000)
+ logger.debug("**** DoAllocateCoreNonSharedSlice ::: timeDelay wakeup after 5 sec")
+ } catch(InterruptedException e) {
+ logger.error(Prefix+ " **** DoAllocateCoreNonSharedSlice ::: timeDelay exception" + e)
+ }
+ }
+
+
+ void updateRelationship(DelegateExecution execution) {
+ logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: updateRelationship ****")
+
+ String networkServiceInstanceId = execution.getVariable("networkServiceId")
+ String nssiId = execution.getVariable("nssiServiceInstanceId")
+ String globalCustId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("serviceType")
+ try{
+ //Update NSSI orchestration status nssiServiceInstance
+ ServiceInstance si = execution.getVariable("nssiServiceInstance")
+ si.setOrchestrationStatus("activated")
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalCustId, serviceType, networkServiceInstanceId)
+ try {
+ getAAIClient().update(uri, si)
+ } catch (Exception e) {
+ logger.info("Update OrchestrationStatus in AAI failed")
+ String msg = "Update OrchestrationStatus in AAI failed, " + e.getMessage()
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ //URI for NSSI
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId);
+
+ //URI for Network Service Instance
+ AAIResourceUri networkServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, networkServiceInstanceId)
+
+ // Update Relationship in AAI
+ Response response = getAAIClient().connect(nssiUri, networkServiceInstanceUri, AAIEdgeLabel.COMPOSED_OF);
+
+ if(response.getStatus()!=200 || response.getStatus()!=201 || response.getStatus()!=202) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, response.getStatus(), "Set association of NSSI and Network service instance has failed in AAI")
+ } else {
+ execution.setVariable("progress", 100)
+ execution.setVariable("status", "finished")
+ execution.setVariable("statusDescription", "DoAllocateCoreNonSharedNSSI success")
+ setResourceOperationStatus(execution)
+ }
+ }catch(Exception ex) {
+ String msg = "Exception while creating relationship " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: updateRelationship ****")
+ }
+
+ /**
+ * prepare ResourceOperation status
+ * @param execution
+ * @param operationType
+ */
+ private void setResourceOperationStatus(DelegateExecution execution) {
+ logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: setResourceOperationStatus ****")
+ String serviceId = execution.getVariable("nssiId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operationType = execution.getVariable("operationType")
+ ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
+ resourceOperationStatus.setServiceId(serviceId)
+ resourceOperationStatus.setOperationId(jobId)
+ resourceOperationStatus.setResourceTemplateUUID(nsiId)
+ resourceOperationStatus.setOperType(operationType)
+ resourceOperationStatus.setStatus(execution.getVariable("status"))
+ resourceOperationStatus.setProgress(execution.getVariable("progress"))
+ resourceOperationStatus.setStatusDescription(execution.getVariable("statusDescription"))
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
+ logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: setResourceOperationStatus ****")
+ }
+
+ void prepareFailedOperationStatusUpdate(DelegateExecution execution){
+ logger.debug(Prefix + " **** Enter DoAllocateCoreNonSharedSlice ::: prepareFailedOperationStatusUpdate ****")
+ String serviceId = execution.getVariable("nssiId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operationType = execution.getVariable("operationType")
+
+ ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
+ resourceOperationStatus.setServiceId(serviceId)
+ resourceOperationStatus.setOperationId(jobId)
+ resourceOperationStatus.setResourceTemplateUUID(nsiId)
+ resourceOperationStatus.setOperType(operationType)
+ resourceOperationStatus.setProgress(0)
+ resourceOperationStatus.setStatus("failed")
+ resourceOperationStatus.setStatusDescription("Core NSSI Allocate Failed")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
+ logger.debug(Prefix + " **** Exit DoAllocateCoreNonSharedSlice ::: prepareFailedOperationStatusUpdate ****")
+ }
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreSharedSlice.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreSharedSlice.groovy
new file mode 100644
index 0000000000..6367341228
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreSharedSlice.groovy
@@ -0,0 +1,658 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Tech Mahindra
+ * ================================================================================
+ * 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.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.json.JSONObject
+import org.onap.logging.filter.base.ONAPComponents
+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.RequestDBUtil
+import org.onap.so.serviceinstancebeans.CloudConfiguration
+import org.onap.so.serviceinstancebeans.LineOfBusiness
+import org.onap.so.serviceinstancebeans.ModelInfo
+import org.onap.so.serviceinstancebeans.ModelType
+import org.onap.so.serviceinstancebeans.OwningEntity
+import org.onap.so.serviceinstancebeans.Platform
+import org.onap.so.serviceinstancebeans.Project
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.rest.catalog.beans.Vnf
+import org.onap.so.serviceinstancebeans.RequestDetails
+import org.onap.so.serviceinstancebeans.RequestInfo
+import org.onap.so.serviceinstancebeans.RequestParameters
+import org.onap.so.serviceinstancebeans.SubscriberInfo
+import org.onap.aai.domain.yang.GenericVnf
+import org.onap.aai.domain.yang.RelatedToProperty
+import org.onap.aai.domain.yang.Relationship
+import org.onap.aai.domain.yang.RelationshipData
+import org.onap.aai.domain.yang.RelationshipList
+import org.onap.aai.domain.yang.ServiceInstance
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.db.request.beans.OperationStatus
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import com.fasterxml.jackson.databind.ObjectMapper
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+import javax.ws.rs.NotFoundException
+import javax.ws.rs.core.Response
+
+class DoAllocateCoreSharedSlice extends AbstractServiceTaskProcessor {
+
+ String Prefix="DACSNSSI_"
+ private static final Logger logger = LoggerFactory.getLogger(DoAllocateCoreSharedSlice.class);
+ private CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
+ private RequestDBUtil requestDBUtil = new RequestDBUtil()
+ private ExceptionUtil exceptionUtil = new ExceptionUtil()
+ private JsonUtils jsonUtil = new JsonUtils()
+ ObjectMapper mapper = new ObjectMapper();
+
+ private final Long TIMEOUT = 60 * 60 * 1000
+
+ @Override
+ public void preProcessRequest(DelegateExecution execution) {
+
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: preProcessRequest ****")
+ //Get NSSI Solutions
+ String nssisolutions = execution.getVariable("solutions")
+
+ //Get First Object
+ List<String> nssiSolutionList = jsonUtil.StringArrayToList(nssisolutions)
+
+ logger.debug("nssiSolutionList : "+nssiSolutionList)
+
+ String nssiId = jsonUtil.getJsonValue(nssiSolutionList.get(0), "NSSIId")
+ logger.debug("NSSIId : "+nssiId)
+
+ if (isBlank(nssiId)) {
+ String msg = "solution nssiId is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("nssiId", nssiId)
+ }
+
+ String sNssaiListAsString = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "snssaiList")
+ logger.debug("sNssaiListAsString "+sNssaiListAsString)
+ List<String> sNssaiList = jsonUtil.StringArrayToList(sNssaiListAsString)
+ logger.debug("sNssaiList "+sNssaiList)
+ String sNssai = sNssaiList.get(0)
+ execution.setVariable("sNssai", sNssai)
+ logger.debug("sNssai: "+sNssai)
+
+ String serviceType = execution.getVariable("subscriptionServiceType")
+ execution.setVariable("serviceType", serviceType)
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: preProcessRequest ****")
+ }
+
+ public void getNetworkInstanceAssociatedWithNssiId(DelegateExecution execution) {
+
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: getNetworkInstanceAssociatedWithNssiId ****")
+
+ //NSSI Id as service Instance Id to get from Request
+ String serviceInstanceId = execution.getVariable("serviceInstanceID")
+
+ String errorMsg = "query Network Service Instance from AAI failed"
+ AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
+ Optional<ServiceInstance> nsi = wrapper.asBean(ServiceInstance.class)
+
+ String networkServiceInstanceName = ""
+ String networkServiceInstanceId =""
+ if(nsi.isPresent()) {
+ List<Relationship> relationshipList = nsi.get().getRelationshipList()?.getRelationship()
+ List spiWithsNssaiAndOrchStatusList = new ArrayList<>()
+
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo == "service-instance") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ List<RelatedToProperty> relatedToPropertyList = relationship.getRelatedToProperty()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "service-instance.service-instance-id") {
+ logger.debug("**** service-instance.service-instance-id 1 :: getServiceInstanceRelationships :: "+ relationshipData.getRelationshipValue())
+ execution.setVariable("networkServiceInstanceId", relationshipData.getRelationshipValue())
+ }
+ }
+ for (RelatedToProperty relatedToProperty : relatedToPropertyList) {
+ if (relatedToProperty.getPropertyKey() == "service-instance.service-instance-name") {
+ execution.setVariable("networkServiceInstanceName", relatedToProperty.getPropertyValue())
+ }
+ }
+ }
+ //If related to is allotted-Resource
+ if (relatedTo == "allotted-resource") {
+ //get slice Profile Instance Id from allotted resource in list by nssi
+ List<String> sliceProfileInstanceIdList = new ArrayList<>()
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "service-instance.service-instance-id") {
+ sliceProfileInstanceIdList.add(relationshipData.getRelationshipValue())
+ }
+ }
+ for (String sliceProfileServiceInstanceId : sliceProfileInstanceIdList) {
+ String errorSliceProfileMsg = "Slice Profile Service Instance was not found in aai"
+
+ //Query Slice Profile Service Instance From AAI by sliceProfileServiceInstanceId
+ AAIResultWrapper sliceProfileInstanceWrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, sliceProfileServiceInstanceId, errorSliceProfileMsg)
+ Optional<ServiceInstance> sliceProfileServiceInstance = sliceProfileInstanceWrapper.asBean(ServiceInstance.class)
+ if (sliceProfileServiceInstance.isPresent()) {
+ String orchestrationStatus= sliceProfileServiceInstance.get().getOrchestrationStatus()
+ String sNssai = sliceProfileServiceInstance.get().getSliceProfiles().getSliceProfile().get(0).getSNssai()
+ if(sNssai.equals(execution.getVariable("sNssai"))) {
+ orchestrationStatus = execution.getVariable("oStatus")
+ //Slice Profile Service Instance to be updated in AAI
+ execution.setVariable("sliceProfileServiceInstance", sliceProfileServiceInstance)
+ }
+
+ Map<String, Object> spiWithsNssaiAndOrchStatus = new LinkedHashMap<>()
+ spiWithsNssaiAndOrchStatus.put("snssai", sNssai)
+ spiWithsNssaiAndOrchStatus.put("status", orchestrationStatus)
+ spiWithsNssaiAndOrchStatusList.add(spiWithsNssaiAndOrchStatus)
+ logger.debug("service Profile's NSSAI And Orchestration Status: "+spiWithsNssaiAndOrchStatus)
+ }
+ }
+ }
+ }
+ execution.setVariable("snssaiAndOrchStatusList", spiWithsNssaiAndOrchStatusList)
+ }
+
+ logger.debug("NSSI Id: ${serviceInstanceId}, network Service Instance Id: ${networkServiceInstanceId}, serviceName: ${networkServiceInstanceName}")
+
+ //Get ServiceInstance Relationships
+ getServiceInstanceRelationships(execution)
+
+ //Get Vnf Relationships
+ getVnfRelationships(execution)
+
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: getNetworkInstanceAssociatedWithNssiId ****")
+ }
+
+ private void getServiceInstanceRelationships(DelegateExecution execution) {
+
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: getServiceInstanceRelationships ****")
+
+ String serviceInstanceId = execution.getVariable("networkServiceInstanceId")
+
+ String errorMsg = "query Network Service Instance from AAI failed"
+ AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
+ Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
+
+ String networkServiceModelInvariantUuid = si.get().getModelInvariantId()
+ execution.setVariable("networkServiceModelInvariantUuid", networkServiceModelInvariantUuid)
+ if(si.isPresent()) {
+ List<Relationship> relationshipList = si.get().getRelationshipList()?.getRelationship()
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo == "owning-entity") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "owning-entity.owning-entity-id") {
+ execution.setVariable("owningEntityId", relationshipData.getRelationshipValue())
+ }
+ }
+ } else if (relatedTo == "generic-vnf") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ List<RelatedToProperty> relatedToPropertyList = relationship.getRelatedToProperty()
+
+ //Get VnfId
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "generic-vnf.vnf-id") {
+ execution.setVariable("vnfId", relationshipData.getRelationshipValue())
+ }
+ }
+
+ //Get Vnf Name Check If necessary
+ for (RelatedToProperty relatedToProperty : relatedToPropertyList) {
+ if (relatedToProperty.getPropertyKey() == "generic-vnf.vnf-name") {
+ execution.setVariable("vnfName", relatedToProperty.getPropertyValue())
+ }
+ }
+ } else if (relatedTo == "project") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "project.project-name") {
+ execution.setVariable("projectName", relationshipData.getRelationshipValue())
+ }
+ }
+ }
+ }
+
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: getServiceInstanceRelationships ****")
+ }
+ }
+
+ private void getVnfRelationships(DelegateExecution execution) {
+
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: getVnfRelationships ****")
+ String msg = "query Generic Vnf from AAI failed"
+ try {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, execution.getVariable('vnfId'))
+ if (!getAAIClient().exists(uri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+ AAIResultWrapper wrapper = getAAIClient().get(uri, NotFoundException.class)
+ Optional<GenericVnf> vnf = wrapper.asBean(GenericVnf.class)
+ if(vnf.isPresent()) {
+ List<Relationship> relationshipList = vnf.get().getRelationshipList()?.getRelationship()
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo == "tenant") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "tenant.tenant-id") {
+ execution.setVariable("tenantId", relationshipData.getRelationshipValue())
+ }
+ }
+ } else if (relatedTo == "cloud-region") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "cloud-region.cloud-owner") {
+ execution.setVariable("cloudOwner", relationshipData.getRelationshipValue())
+ } else if (relationshipData.getRelationshipKey() == "cloud-region.cloud-region-id") {
+ execution.setVariable("lcpCloudRegionId", relationshipData.getRelationshipValue())
+ }
+ }
+ } else if (relatedTo == "platform") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "platform.platform-name") {
+ execution.setVariable("platformName", relationshipData.getRelationshipValue())
+ }
+ }
+ } else if (relatedTo == "line-of-business") {
+ List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
+ for (RelationshipData relationshipData : relationshipDataList) {
+ if (relationshipData.getRelationshipKey() == "line-of-business.line-of-business-name") {
+ execution.setVariable("lineOfBusinessName", relationshipData.getRelationshipValue())
+ }
+ }
+ }
+ }
+ }
+ } catch(BpmnError e){
+ throw e
+ } catch (Exception ex){
+ msg = "Exception in getVnfRelationships " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: getVnfRelationships ****")
+ }
+
+
+ /**
+ * query AAI
+ * @param execution
+ * @param aaiObjectType
+ * @param instanceId
+ * @return AAIResultWrapper
+ */
+ private AAIResultWrapper queryAAI(DelegateExecution execution, AAIObjectType aaiObjectType, String instanceId, String errorMsg) {
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: queryAAI ****")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("serviceType")
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(aaiObjectType, globalSubscriberId, serviceType, instanceId)
+ if (!getAAIClient().exists(resourceUri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMsg)
+ }
+ AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: queryAAI ****")
+ return wrapper
+ }
+
+ public void getServiceVNFAndVFsFromCatalogDB(DelegateExecution execution) {
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: getServiceVNFAndVFsFromCatalogDB ****")
+ String serviceVnfs="";
+ String msg=""
+ String modelInvariantUuid = execution.getVariable("networkServiceModelInvariantUuid")
+ try{
+ CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
+ String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution, modelInvariantUuid)
+ logger.debug("***** JSON IS: "+json)
+ serviceVnfs = jsonUtil.getJsonValue(json, "serviceResources.serviceVnfs") ?: ""
+ String serviceModelInfo = jsonUtil.getJsonValue(json, "serviceResources.modelInfo") ?: ""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ execution.setVariable("serviceVnfs",serviceVnfs)
+ logger.debug("***** serviceVnfs is: "+ serviceVnfs)
+ }catch(BpmnError e){
+ throw e
+ } catch (Exception ex){
+ msg = "Exception in preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: getServiceVNFAndVFsFromCatalogDB ****")
+ }
+
+ public void prepareSOMacroRequestPayload(DelegateExecution execution) {
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: prepareSOMacroRequestPayLoad ****")
+ String json = execution.getVariable("serviceVnfs")
+ logger.debug(">>>> json "+json)
+ List<Object> vnfList = mapper.readValue(json, List.class);
+ logger.debug("vnfList: "+vnfList)
+ Map<String,Object> serviceMap = mapper.readValue(execution.getVariable("serviceModelInfo"), Map.class);
+ ModelInfo serviceModelInfo = new ModelInfo()
+ serviceModelInfo.setModelType(ModelType.service)
+ serviceModelInfo.setModelInvariantId(serviceMap.get("modelInvariantUuid"))
+ serviceModelInfo.setModelVersionId(serviceMap.get("modelUuid"))
+ serviceModelInfo.setModelName(serviceMap.get("modelName"))
+ serviceModelInfo.setModelVersion(serviceMap.get("modelVersion"))
+ logger.debug("serviceModelInfo: "+serviceModelInfo)
+ //List of Vnfs
+ List<Object> vnfModelInfoList = new ArrayList<>()
+
+ Map vnfMap = vnfList.get(0)
+ ModelInfo vnfModelInfo = vnfMap.get("modelInfo")
+ logger.debug("vnfModelInfo "+vnfModelInfo)
+
+ //List of VFModules
+ List<Map<String, Object>> vfModuleList = vnfMap.get("vfModules")
+ logger.debug("vfModuleList "+vfModuleList)
+
+ //List of VfModules
+ List<ModelInfo> vfModelInfoList = new ArrayList<>()
+
+ //Traverse VFModules List and add in vfModelInfoList
+ for (vfModule in vfModuleList) {
+ ModelInfo vfModelInfo = vfModule.get("modelInfo")
+ logger.debug("vfModelInfo "+vfModelInfo)
+ vfModelInfoList.add(vfModelInfo)
+ }
+ //RequestInfo
+ RequestInfo requestInfo = new RequestInfo()
+
+ //Dummy Product FamilyId
+ requestInfo.setProductFamilyId("test1234")
+ requestInfo.setSource("VID")
+ requestInfo.setInstanceName(execution.getVariable("networkServiceInstanceName"))
+ requestInfo.setSuppressRollback(false)
+ requestInfo.setRequestorId("NBI")
+
+ //Service Level InstanceParams
+ List<Map<String, Object>> serviceParams = new ArrayList<>()
+ Map<String, Object> serviceParamsValues = new LinkedHashMap<>()
+ serviceParams.add(serviceParamsValues)
+
+ //Cloud Configuration
+ CloudConfiguration cloudConfiguration = new CloudConfiguration()
+ cloudConfiguration.setLcpCloudRegionId(execution.getVariable("lcpCloudRegionId"))
+ cloudConfiguration.setTenantId(execution.getVariable("tenantId"))
+ cloudConfiguration.setCloudOwner(execution.getVariable("cloudOwner"))
+
+ //VFModules List
+ List<Map<String, Object>> vfModules = new ArrayList<>()
+ for (ModelInfo vfModuleModelInfo : vfModelInfoList) {
+ //Individual VFModule List
+ Map<String, Object> vfModuleValues = new LinkedHashMap<>()
+ vfModuleValues.put("modelInfo", vfModuleModelInfo)
+ vfModuleValues.put("instanceName", vfModuleModelInfo.getModelInstanceName())
+
+ //VFModule InstanceParams should be empty or this field should not be there?
+ List<Map<String, Object>> vfModuleInstanceParams = new ArrayList<>()
+ vfModuleValues.put("instanceParams", vfModuleInstanceParams)
+ }
+
+ //Vnf intsanceParams
+ Map<String, Object> sliceProfile = mapper.readValue(execution.getVariable("sliceProfile"), Map.class);
+
+ List vnfInstanceParamsList = new ArrayList<>()
+ String supportedsNssaiJson= prepareVnfInstanceParamsJson(execution)
+ vnfInstanceParamsList.add(supportedsNssaiJson)
+
+ Platform platform = new Platform()
+ platform.setPlatformName(execution.getVariable("platform"))
+
+ LineOfBusiness lineOfbusiness = new LineOfBusiness()
+ lineOfbusiness.setLineOfBusinessName(execution.getVariable("lineOfBusiness"))
+
+ //Vnf Values
+ Map<String, Object> vnfValues = new LinkedHashMap<>()
+ vnfValues.put("lineOfBusiness", lineOfbusiness)
+ vnfValues.put("platform", platform)
+ vnfValues.put("productFamilyId", "test1234")
+ vnfValues.put("cloudConfiguration", cloudConfiguration)
+ vnfValues.put("vfModules", vfModules)
+ vnfValues.put("modelInfo", vnfModelInfo)
+ vnfValues.put("instanceName", execution.getVariable("vnfInstanceName"))
+ vnfValues.put("instanceParams",vnfInstanceParamsList)
+
+ vnfModelInfoList.add(vnfValues)
+ //Service Level Resources
+ Map<String, Object> serviceResources = new LinkedHashMap<>()
+ serviceResources.put("vnfs", vnfModelInfoList)
+
+ //Service Values
+ Map<String, Object> serviceValues = new LinkedHashMap<>()
+ serviceValues.put("modelInfo", serviceModelInfo)
+ serviceValues.put("instanceName", execution.getVariable("networkServiceInstanceName"))
+ serviceValues.put("resources", serviceResources)
+ serviceValues.put("instanceParams", serviceParams)
+
+ //UserParams Values
+ Map<String, Object> userParamsValues = new LinkedHashMap<>()
+
+ Map<String, Object> homingSolution = new LinkedHashMap<>()
+ homingSolution.put("Homing_Solution", "none")
+
+ userParamsValues.put("service", serviceValues)
+
+ //UserParams
+ List<Map<String, Object>> userParams = new ArrayList<>()
+ userParams.add(homingSolution)
+ userParams.add(userParamsValues)
+
+ //Request Parameters
+ RequestParameters requestParameters = new RequestParameters()
+ requestParameters.setaLaCarte(false)
+ requestParameters.setSubscriptionServiceType(execution.getVariable("serviceType"))
+ requestParameters.setUserParams(userParams)
+
+ //SubscriberInfo
+ SubscriberInfo subscriberInfo = new SubscriberInfo()
+ subscriberInfo.setGlobalSubscriberId(execution.getVariable("globalSubscriberId"))
+
+ //Owning Entity
+ OwningEntity owningEntity = new OwningEntity()
+ owningEntity.setOwningEntityId(execution.getVariable("owningEntityId"))
+
+ //Project
+ Project project = new Project()
+ project.setProjectName(execution.getVariable("projectName"))
+
+ RequestDetails requestDetails = new RequestDetails()
+ requestDetails.setModelInfo(serviceModelInfo)
+ requestDetails.setSubscriberInfo(subscriberInfo)
+ requestDetails.setRequestInfo(requestInfo)
+ requestDetails.setRequestParameters(requestParameters)
+ requestDetails.setCloudConfiguration(cloudConfiguration)
+ requestDetails.setOwningEntity(owningEntity)
+ requestDetails.setProject(project)
+
+ Map<String, Object> requestDetailsMap = new LinkedHashMap<>()
+ requestDetailsMap.put("requestDetails", requestDetails)
+ String requestPayload = mapper.writeValueAsString(requestDetailsMap)
+
+ logger.debug("requestDetails "+requestPayload)
+ execution.setVariable("requestPayload", requestPayload)
+
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: prepareSOMacroRequestPayLoad ****")
+ }
+
+ private String prepareVnfInstanceParamsJson(DelegateExecution execution) {
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: prepareVnfInstanceParamsJson ****")
+ List instanceParamsvalues = execution.getVariable("snssaiAndOrchStatusList")
+ Map<String, Object> nSsai= new LinkedHashMap<>()
+ nSsai.put("sNssai", instanceParamsvalues)
+
+ String supportedsNssaiJson = mapper.writeValueAsString(nSsai)
+ //SupportedNssai
+ Map<String, Object> supportedNssai= new LinkedHashMap<>()
+ supportedNssai.put("supportedNssai", supportedsNssaiJson)
+ logger.debug("**** supportedsNssaiJson**** "+supportedNssai)
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: prepareVnfInstanceParamsJson ****")
+ return supportedNssai
+ }
+
+ public void sendPutRequestToSOMacro(DelegateExecution execution) {
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: sendPutRequestToSOMacro ****")
+ try {
+ String msoEndpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
+ String url = msoEndpoint+"/serviceInstantiation/v7/serviceInstances/"+execution.getVariable("networkServiceInstanceId")+"/vnfs/"+execution.getVariable("vnfId")
+
+ String requestBody = execution.getVariable("requestPayload")
+
+ String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
+ String basicAuth = UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
+ String basicAuthValue = utils.encrypt(basicAuth, msoKey)
+ String encodeString = utils.getBasicAuth(basicAuthValue, msoKey)
+
+ HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.SO)
+ httpClient.addAdditionalHeader("Authorization", encodeString)
+ httpClient.addAdditionalHeader("Accept", "application/json")
+ Response httpResponse = httpClient.put(requestBody)
+ handleSOResponse(httpResponse, execution)
+ } catch (BpmnError e) {
+ throw e
+ } catch (any) {
+ String msg = Prefix+" Exception in DoAllocateCoreSharedSlice " + any.getCause()
+ logger.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: sendPostRequestToSOMacro ****")
+ }
+
+ /**
+ * Handle SO Response for PUT and prepare update operation status
+ * @param execution
+ */
+ private void handleSOResponse(Response httpResponse, DelegateExecution execution){
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: handleSOResponse ****")
+
+ int soResponseCode = httpResponse.getStatus()
+ logger.debug("soResponseCode : "+soResponseCode)
+
+ if (soResponseCode >= 200 && soResponseCode < 204 && httpResponse.hasEntity()) {
+ String soResponse = httpResponse.readEntity(String.class)
+ String operationId = execution.getVariable("operationId")
+ def macroOperationId = jsonUtil.getJsonValue(soResponse, "operationId")
+ execution.setVariable("macroOperationId", macroOperationId)
+ execution.setVariable("isSOTimeOut", "no")
+ execution.setVariable("isSOResponseSucceed","yes")
+ }
+ else {
+ String serviceName = execution.getVariable("serviceInstanceName")
+ execution.setVariable("isSOResponseSucceed","no")
+ prepareFailedOperationStatusUpdate(execution)
+ }
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: handleSOResponse ****")
+ }
+
+ /**
+ * prepare to call sub process CheckProcessStatus
+ * @param execution
+ */
+ void prepareCallCheckProcessStatus(DelegateExecution execution){
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: prepareCallCheckProcessStatus ****")
+ def successConditions = new ArrayList<>()
+ successConditions.add("finished")
+ execution.setVariable("successConditions", successConditions)
+ def errorConditions = new ArrayList<>()
+ errorConditions.add("error")
+ execution.setVariable("errorConditions", errorConditions)
+ execution.setVariable("processServiceType", "Network service")
+ execution.setVariable("subOperationType", "PUT")
+ execution.setVariable("initProgress", 20)
+ execution.setVariable("endProgress",90)
+ execution.setVariable("timeOut", TIMEOUT)
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: prepareCallCheckProcessStatus ****")
+ }
+
+ void prepareUpdateResourceOperationStatus(DelegateExecution execution) {
+
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: prepareUpdateResourceOperationStatus ****")
+ //Prepare Update Status for PUT failure and success
+ if(execution.getVariable("isTimeOut").equals("YES")) {
+ logger.debug("TIMEOUT - SO PUT Failure")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SO PUT Failure")
+ } else {
+ execution.setVariable("progress", "100")
+ execution.setVariable("status", "finished")
+ execution.setVariable("operationContent", "AllocteCoreNSSI successful.")
+ logger.debug("prepareFailureStatus,result:${execution.getVariable("result")}, reason: ${execution.getVariable("reason")}")
+ }
+ setResourceOperationStatus(execution)
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: prepareUpdateResourceOperationStatus ****")
+ }
+
+ /**
+ * prepare ResourceOperation status
+ * @param execution
+ * @param operationType
+ */
+ private void setResourceOperationStatus(DelegateExecution execution) {
+ logger.debug(Prefix+" **** Enter DoAllocateCoreSharedSlice ::: setResourceOperationStatus ****")
+ String serviceId = execution.getVariable("nssiId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operationType = execution.getVariable("operationType")
+ ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
+ resourceOperationStatus.setServiceId(serviceId)
+ resourceOperationStatus.setOperationId(jobId)
+ resourceOperationStatus.setResourceTemplateUUID(nsiId)
+ resourceOperationStatus.setOperType(operationType)
+ resourceOperationStatus.setStatus("finished")
+ resourceOperationStatus.setProgress("100")
+ resourceOperationStatus.setStatusDescription("Core Allocate successful")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
+ logger.debug(Prefix+" **** Exit DoAllocateCoreSharedSlice ::: setResourceOperationStatus ****")
+ }
+
+ void prepareFailedOperationStatusUpdate(DelegateExecution execution){
+ logger.debug(Prefix + " **** Enter DoAllocateCoreSharedSlice ::: prepareFailedOperationStatusUpdate ****")
+ String serviceId = execution.getVariable("nssiId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String operationType = execution.getVariable("operationType")
+
+ ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
+ resourceOperationStatus.setServiceId(serviceId)
+ resourceOperationStatus.setOperationId(jobId)
+ resourceOperationStatus.setResourceTemplateUUID(nsiId)
+ resourceOperationStatus.setOperType(operationType)
+ resourceOperationStatus.setProgress(0)
+ resourceOperationStatus.setStatus("failed")
+ resourceOperationStatus.setStatusDescription("Core NSSI Allocate Failed")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
+ logger.debug(Prefix + " **** Exit DoAllocateCoreSharedSlice ::: prepareFailedOperationStatusUpdate ****")
+ }
+} \ No newline at end of file
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
index 4a8469cc8d..c4068d2d5e 100644
--- 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
@@ -2,19 +2,19 @@
* ============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.
+ # Copyright (c) 2020, 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=========================================================
*/
@@ -23,19 +23,29 @@ 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.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.common.scripts.NssmfAdapterUtils
-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.aai.domain.yang.SliceProfile
import org.onap.aaiclient.client.aai.AAIObjectType
import org.onap.aaiclient.client.aai.AAIResourcesClient
import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+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.NssiResponse
+import org.onap.so.beans.nsmf.NssmfAdapterNBIRequest
+import org.onap.so.beans.nsmf.ResponseDescriptor
+import org.onap.so.beans.nsmf.ServiceInfo
+import org.onap.so.beans.nsmf.SliceTaskInfo
+import org.onap.so.beans.nsmf.SliceTaskParamsAdapter
+import org.onap.so.beans.nsmf.TnSliceProfile
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.core.json.JsonUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
@@ -43,15 +53,15 @@ import javax.ws.rs.NotFoundException
import static org.apache.commons.lang3.StringUtils.isBlank
-class DoAllocateNSIandNSSI extends org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor{
+class DoAllocateNSIandNSSI extends AbstractServiceTaskProcessor{
- private static final Logger logger = LoggerFactory.getLogger( DoAllocateNSIandNSSI.class);
+ private static final Logger logger = LoggerFactory.getLogger(DoAllocateNSIandNSSI.class);
ExceptionUtil exceptionUtil = new ExceptionUtil()
JsonUtils jsonUtil = new JsonUtils()
- private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
+ AAIResourcesClient client = getAAIClient()
/**
* Pre Process the BPMN Flow Request
@@ -72,165 +82,77 @@ class DoAllocateNSIandNSSI extends org.onap.so.bpmn.common.scripts.AbstractServi
logger.trace("Exit preProcessRequest")
}
+ /**
+ * Process NSI options
+ * @param execution
+ */
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
- {
- Map<String, Object> nstSolution = execution.getVariable("nstSolution") as Map
- String modelUuid = nstSolution.get("UUID")
- String modelInvariantUuid = nstSolution.get("invariantUUID")
- 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")
- }
+ boolean isNSIOptionAvailable
- void updateRelationship(DelegateExecution execution) {
- logger.debug("Enter update relationship in DoAllocateNSIandNSSI()")
- 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()
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
- AAIResourcesClient resourceClient = new AAIResourcesClient()
- AAIResourceUri nsiServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), 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)
-// }
-
- AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), execution.getVariable("sliceServiceInstanceId"), 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)
- }
+ if(isBlank(sliceParams.getSuggestNsiId())) {
+ isNSIOptionAvailable = false
}
- execution.setVariable("nssiAssociated",nssiAssociated)
- execution.setVariable("nsiServiceInstanceName",nsiServiceInstance.getServiceInstanceName())
- }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)
+ else {
+ isNSIOptionAvailable = true
+ execution.setVariable('nsiServiceInstanceId', sliceParams.getSuggestNsiId())
+ execution.setVariable('nsiServiceInstanceName', sliceParams.getSuggestNsiName())
}
- logger.debug("Exit update relationship in DoAllocateNSIandNSSI()")
+ execution.setVariable("isNSIOptionAvailable", isNSIOptionAvailable)
+ logger.trace("Exit retriveSliceOption() of 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("subscriptionServiceType"), 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()")
- }
+ /**
+ * create nsi instance in aai
+ * @param execution
+ */
void createNSIinAAI(DelegateExecution execution) {
logger.debug("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)
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ //set new nsiId to sliceParams suggestNsiId
+ sliceParams.setSuggestNsiId(sliceInstanceId)
+
+ ServiceInstance nsi = new ServiceInstance()
+
+
String sliceInstanceName = "nsi_"+execution.getVariable("sliceServiceInstanceName")
- nsi.setServiceInstanceName(sliceInstanceName)
String serviceType = execution.getVariable("serviceType")
- nsi.setServiceType(serviceType)
String serviceStatus = "deactivated"
+ String modelInvariantUuid = sliceParams.getNSTInfo().invariantUUID
+ String modelUuid = sliceParams.getNSTInfo().UUID
+
+ String uuiRequest = execution.getVariable("uuiRequest")
+ String serviceInstanceLocationid = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.plmnIdList")
+ String serviceRole = "nsi"
+
+ execution.setVariable("sliceInstanceId", sliceInstanceId)
+ nsi.setServiceInstanceId(sliceInstanceId)
+ nsi.setServiceInstanceName(sliceInstanceName)
+ nsi.setServiceType(serviceType)
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)
- String msg = ""
+ String msg
try {
- AAIResourcesClient client = new AAIResourcesClient()
- AAIResourceUri nsiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), sliceInstanceId)
+ AAIResourceUri nsiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ sliceInstanceId)
client.create(nsiServiceUri, nsi)
- Relationship relationship = new Relationship()
- logger.info("Creating Allotted resource relationship, nsiServiceUri: " + nsiServiceUri.build().toString())
- relationship.setRelatedLink(nsiServiceUri.build().toString())
- AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE,
- execution.getVariable("globalSubscriberId"),execution.getVariable("subscriptionServiceType"),
- execution.getVariable("sliceServiceInstanceId"), execution.getVariable("allottedResourceId")).relationshipAPI()
- client.create(allottedResourceUri, relationship)
+ execution.setVariable("nsiServiceUri", nsiServiceUri)
} catch (BpmnError e) {
throw e
@@ -239,124 +161,565 @@ class DoAllocateNSIandNSSI extends org.onap.so.bpmn.common.scripts.AbstractServi
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)
+
+ logger.debug("Exit CreateNSIinAAI in DoAllocateNSIandNSSI()")
+ }
+
+
+ /**
+ * create relationship between nsi and service profile instance
+ * @param execution
+ */
+ void createRelationship(DelegateExecution execution) {
+ //relation ship
+ String allottedResourceId = execution.getVariable("allottedResourceId")
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ AAIResourceUri nsiServiceUri = execution.getVariable("nsiServiceUri") as AAIResourceUri
+ logger.info("Creating Allotted resource relationship, nsiServiceUri: " + nsiServiceUri)
+
+ AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(
+ AAIObjectType.ALLOTTED_RESOURCE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ sliceParams.suggestNsiId,
+ allottedResourceId)
+
+ client.connect(allottedResourceUri, nsiServiceUri)
+ }
+
+ /**
+ *
+ * @param execution
+ */
+ void updateRelationship(DelegateExecution execution) {
+ logger.debug("Enter update relationship in DoAllocateNSIandNSSI()")
+ //todo: allottedResourceId
+ String allottedResourceId = execution.getVariable("allottedResourceId")
+ //Need to check whether nsi exist : Begin
+
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ String nsiServiceInstanceID = sliceParams.getSuggestNsiId()
+ //sliceParams.setServiceId(nsiServiceInstanceID)
+
+ AAIResourceUri nsiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ nsiServiceInstanceID)
+
+ try {
+ AAIResultWrapper wrapper = client.get(nsiServiceUri, NotFoundException.class)
+ Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
+ //todo: if exists
+ if (!si.ifPresent()) {
+ 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("subscriptionServiceType"),
+ sliceParams.suggestNsiId, //nsiId
+ allottedResourceId)
+
+ client.connect(allottedResourceUri, nsiServiceUri)
+
+ execution.setVariable("sliceTaskParams", sliceParams)
+ }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)
}
- execution.setVariable("nsstModelInfoList",nsstModelInfoList)
- execution.setVariable("currentIndex",currentIndex)
- execution.setVariable("maxIndex",maxIndex)
- execution.setVariable('nsiServiceInstanceId',sliceInstanceId)
- execution.setVariable("nsiServiceInstanceName",sliceInstanceName)
- logger.debug("Exit CreateNSIinAAI in DoAllocateNSIandNSSI()")
+ logger.debug("Exit update relationship 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)
+ /**
+ * create RAN Slice Profile Instance
+ * @param execution
+ */
+ void createAnSliceProfileInstance(DelegateExecution execution) {
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ String serviceInstanceId = UUID.randomUUID().toString()
+ execution.setVariable("ranSliceProfileInstanceId", serviceInstanceId) //todo:
+
+ String serviceType = ""
+ String serviceRole = "slice-profile"
+ String oStatus = "deactivated"
+
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+ SliceTaskInfo<AnSliceProfile> sliceTaskInfo = sliceParams.anSliceTaskInfo
+ sliceTaskInfo.setSliceInstanceId(serviceInstanceId)
+
+ // create slice profile
+ ServiceInstance rspi = new ServiceInstance()
+ rspi.setServiceInstanceName(sliceTaskInfo.NSSTInfo.name)
+ rspi.setServiceType(serviceType)
+ rspi.setServiceRole(serviceRole)
+ rspi.setOrchestrationStatus(oStatus)
+ rspi.setModelInvariantId(sliceTaskInfo.NSSTInfo.invariantUUID)
+ rspi.setModelVersionId(sliceTaskInfo.NSSTInfo.UUID)
+ rspi.setInputParameters(uuiRequest)
+ rspi.setWorkloadContext(useInterval)
+ rspi.setEnvironmentContext(sNSSAI_id)
+
+ //timestamp format YYYY-MM-DD hh:mm:ss
+ rspi.setCreatedAt(new Date(System.currentTimeMillis()).format("yyyy-MM-dd HH:mm:ss", TimeZone.getDefault()))
+
+ execution.setVariable("communicationServiceInstance", rspi)
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId,
+ subscriptionServiceType,
+ serviceInstanceId)
+ client.create(uri, rspi)
+
+ execution.setVariable("sliceTaskParams", sliceParams)
}
- 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("sliceServiceInstanceName")
- String nsiname = "nsi_"+servicename
- nssiMap.put(domain,"""{
- "serviceInstanceId":"",
- "modelUuid":"${modelUuid}"
- }""")
- execution.setVariable("nssiMap",nssiMap)
+ /**
+ * create An Slice Profile
+ * @param execution
+ */
+ void createAnSliceProfile(DelegateExecution execution) {
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ //String serviceInstanceId = execution.getVariable("ranSliceProfileInstanceId")
+
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+ SliceTaskInfo<AnSliceProfile> sliceTaskInfo = sliceParams.anSliceTaskInfo
+ AnSliceProfile anSliceProfile = sliceTaskInfo.sliceProfile
+
+ String profileId = UUID.randomUUID().toString()
+ anSliceProfile.setSliceProfileId(profileId)
+
+ SliceProfile sliceProfile = new SliceProfile()
+ sliceProfile.setProfileId(profileId)
+ sliceProfile.setCoverageAreaTAList(anSliceProfile.coverageAreaTAList as String)
+ //todo:...
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE,
+ globalSubscriberId,
+ subscriptionServiceType,
+ sliceTaskInfo.sliceInstanceId,
+ profileId
+ )
+ client.create(uri, sliceProfile)
+ execution.setVariable("sliceTaskParams", sliceParams)
}
- 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()")
+ /**
+ * prepare AllocateAnNssi
+ * @param execution
+ */
+ void prepareAllocateAnNssi(DelegateExecution execution) {
+
+ //todo:
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+ SliceTaskInfo<AnSliceProfile> sliceTaskInfo = sliceParams.anSliceTaskInfo
+
+ NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
+
+ AllocateAnNssi allocateAnNssi = new AllocateAnNssi()
+ allocateAnNssi.nsstId = sliceTaskInfo.NSSTInfo.UUID
+ allocateAnNssi.nssiId = sliceTaskInfo.NSSTInfo.UUID
+ allocateAnNssi.nssiName = sliceTaskInfo.NSSTInfo.name
+ allocateAnNssi.sliceProfile = sliceTaskInfo.sliceProfile
+ allocateAnNssi.nsiInfo.nsiId = sliceParams.suggestNsiId
+
+ EsrInfo esrInfo = new EsrInfo()
+ //todo: vendor and network
+ esrInfo.setVendor(sliceTaskInfo.getVendor())
+ esrInfo.setNetworkType(sliceTaskInfo.getNetworkType())
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ //todo: service info
+ ServiceInfo serviceInfo = new ServiceInfo()
+ serviceInfo.globalSubscriberId = globalSubscriberId
+ serviceInfo.subscriptionServiceType = subscriptionServiceType
+ serviceInfo.nsiId = sliceParams.suggestNsiId
+ serviceInfo.serviceInvariantUuid = sliceTaskInfo.NSSTInfo.invariantUUID
+ serviceInfo.serviceUuid = sliceTaskInfo.NSSTInfo.UUID
+
+ nbiRequest.setServiceInfo(serviceInfo)
+ nbiRequest.setEsrInfo(esrInfo)
+ nbiRequest.setAllocateAnNssi(allocateAnNssi)
+
+ execution.setVariable("AnAllocateNssiNbiRequest", nbiRequest)
+ execution.setVariable("anBHSliceTaskInfo", sliceTaskInfo)
}
- 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()")
+ /**
+ * create RAN Slice Profile Instance
+ * @param execution
+ */
+ void createCnSliceProfileInstance(DelegateExecution execution) {
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ String serviceInstanceId = UUID.randomUUID().toString()
+ execution.setVariable("cnSliceProfileInstanceId", serviceInstanceId) //todo:
+
+ String serviceType = ""
+ String serviceRole = "slice-profile"
+ String oStatus = "deactivated"
+
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+ SliceTaskInfo<CnSliceProfile> sliceTaskInfo = sliceParams.cnSliceTaskInfo
+ sliceTaskInfo.setSliceInstanceId(serviceInstanceId)
+
+ // create slice profile
+ ServiceInstance rspi = new ServiceInstance()
+ rspi.setServiceInstanceName(sliceTaskInfo.NSSTInfo.name)
+ rspi.setServiceType(serviceType)
+ rspi.setServiceRole(serviceRole)
+ rspi.setOrchestrationStatus(oStatus)
+ rspi.setModelInvariantId(sliceTaskInfo.NSSTInfo.invariantUUID)
+ rspi.setModelVersionId(sliceTaskInfo.NSSTInfo.UUID)
+ rspi.setInputParameters(uuiRequest)
+ rspi.setWorkloadContext(useInterval)
+ rspi.setEnvironmentContext(sNSSAI_id)
+
+ //timestamp format YYYY-MM-DD hh:mm:ss
+ rspi.setCreatedAt(new Date(System.currentTimeMillis()).format("yyyy-MM-dd HH:mm:ss", TimeZone.getDefault()))
+
+ execution.setVariable("communicationServiceInstance", rspi)
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId,
+ subscriptionServiceType,
+ serviceInstanceId)
+ client.create(uri, rspi)
+ execution.setVariable("sliceTaskParams", sliceParams)
}
- void updateCurrentIndex(DelegateExecution execution){
+ /**
+ * create An Slice Profile
+ * @param execution
+ */
+ void createCnSliceProfile(DelegateExecution execution) {
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ //String serviceInstanceId = execution.getVariable("ranSliceProfileInstanceId")
+
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ SliceTaskInfo<CnSliceProfile> sliceTaskInfo = sliceParams.cnSliceTaskInfo
+ CnSliceProfile cnSliceProfile = sliceTaskInfo.sliceProfile
+
+ String profileId = UUID.randomUUID().toString()
+ cnSliceProfile.setSliceProfileId(profileId)
+
+ SliceProfile sliceProfile = new SliceProfile()
+ sliceProfile.setProfileId(profileId)
+ sliceProfile.setCoverageAreaTAList(cnSliceProfile.coverageAreaTAList as String)
+ //todo:...
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE,
+ globalSubscriberId,
+ subscriptionServiceType,
+ sliceTaskInfo.sliceInstanceId,
+ profileId
+ )
+ client.create(uri, sliceProfile)
+ execution.setVariable("sliceTaskParams", sliceParams)
+ }
- 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()")
+ /**
+ * prepare AllocateCnNssi
+ * @param execution
+ */
+ void prepareAllocateCnNssi(DelegateExecution execution) {
+
+ //todo:
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+ SliceTaskInfo<CnSliceProfile> sliceTaskInfo = sliceParams.cnSliceTaskInfo
+
+ NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
+
+ AllocateCnNssi allocateCnNssi = new AllocateCnNssi()
+ allocateCnNssi.nsstId = sliceTaskInfo.NSSTInfo.UUID
+ allocateCnNssi.nssiId = sliceTaskInfo.NSSTInfo.UUID
+ allocateCnNssi.nssiName = sliceTaskInfo.NSSTInfo.name
+ allocateCnNssi.sliceProfile = sliceTaskInfo.sliceProfile
+ allocateCnNssi.nsiInfo.nsiId = sliceParams.suggestNsiId
+
+ EsrInfo esrInfo = new EsrInfo()
+ //todo: vendor and network
+ esrInfo.setVendor(sliceTaskInfo.getVendor())
+ esrInfo.setNetworkType(sliceTaskInfo.getNetworkType())
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ //todo: service info
+ ServiceInfo serviceInfo = new ServiceInfo()
+ serviceInfo.globalSubscriberId = globalSubscriberId
+ serviceInfo.subscriptionServiceType = subscriptionServiceType
+ serviceInfo.nsiId = sliceParams.suggestNsiId
+ serviceInfo.serviceInvariantUuid = sliceTaskInfo.NSSTInfo.invariantUUID
+ serviceInfo.serviceUuid = sliceTaskInfo.NSSTInfo.UUID
+
+ nbiRequest.setServiceInfo(serviceInfo)
+ nbiRequest.setEsrInfo(esrInfo)
+ nbiRequest.setAllocateCnNssi(allocateCnNssi)
+
+ execution.setVariable("CnAllocateNssiNbiRequest", nbiRequest)
+ execution.setVariable("cnSliceTaskInfo", sliceTaskInfo)
}
+
+
+ /**
+ * create TN Slice Profile Instance
+ * @param execution
+ */
+ void createTnBHSliceProfileInstance(DelegateExecution execution) {
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ String serviceType = ""
+ String serviceRole = "slice-profile"
+ String oStatus = "deactivated"
+
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ SliceTaskInfo<TnSliceProfile> sliceTaskInfo = sliceParams.tnBHSliceTaskInfo
+ String serviceInstanceId = UUID.randomUUID().toString()
+
+ sliceTaskInfo.setSliceInstanceId(serviceInstanceId)
+ //execution.setVariable("cnSliceProfileInstanceId", serviceInstanceId) //todo:
+
+ // create slice profile
+ ServiceInstance rspi = new ServiceInstance()
+ rspi.setServiceInstanceName(sliceTaskInfo.NSSTInfo.name)
+ rspi.setServiceType(serviceType)
+ rspi.setServiceRole(serviceRole)
+ rspi.setOrchestrationStatus(oStatus)
+ rspi.setModelInvariantId(sliceTaskInfo.NSSTInfo.invariantUUID)
+ rspi.setModelVersionId(sliceTaskInfo.NSSTInfo.UUID)
+ rspi.setInputParameters(uuiRequest)
+ rspi.setWorkloadContext(useInterval)
+ rspi.setEnvironmentContext(sNSSAI_id)
+
+ //timestamp format YYYY-MM-DD hh:mm:ss
+ rspi.setCreatedAt(new Date(System.currentTimeMillis()).format("yyyy-MM-dd HH:mm:ss", TimeZone.getDefault()))
+
+ execution.setVariable("communicationServiceInstance", rspi)
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId,
+ subscriptionServiceType,
+ serviceInstanceId)
+ client.create(uri, rspi)
+
+ execution.setVariable("sliceTaskParams", sliceParams)
+ }
+
+ /**
+ * create An Slice Profile
+ * @param execution
+ */
+ void createTnBHSliceProfile(DelegateExecution execution) {
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ SliceTaskInfo<TnSliceProfile> sliceTaskInfo = sliceParams.tnBHSliceTaskInfo
+
+ TnSliceProfile tnSliceProfile = sliceTaskInfo.sliceProfile
+ String profileId = UUID.randomUUID().toString()
+ tnSliceProfile.setSliceProfileId(profileId)
+
+ SliceProfile sliceProfile = new SliceProfile()
+ sliceProfile.setProfileId(profileId)
+ //todo:...
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE,
+ globalSubscriberId,
+ subscriptionServiceType,
+ sliceTaskInfo.sliceInstanceId,
+ profileId
+ )
+ client.create(uri, sliceProfile)
+
+ execution.setVariable("sliceTaskParams", sliceParams)
+ }
+
+ /**
+ * prepare AllocateCnNssi
+ * @param execution
+ */
+ void prepareAllocateTnBHNssi(DelegateExecution execution) {
+
+ //todo:
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+ SliceTaskInfo<TnSliceProfile> sliceTaskInfo = sliceParams.tnBHSliceTaskInfo
+
+ NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
+
+ AllocateTnNssi allocateTnNssi = new AllocateTnNssi()
+ //todo: AllocateTnNssi
+ allocateTnNssi.setTransportSliceNetworks()
+ allocateTnNssi.setNetworkSliceInfos()
+
+
+ //allocateTnNssi.networkSliceInfos
+
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setVendor(sliceTaskInfo.getVendor())
+ esrInfo.setNetworkType(sliceTaskInfo.getNetworkType())
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ ServiceInfo serviceInfo = new ServiceInfo()
+ serviceInfo.globalSubscriberId = globalSubscriberId
+ serviceInfo.subscriptionServiceType = subscriptionServiceType
+ serviceInfo.nsiId = sliceParams.suggestNsiId
+ serviceInfo.serviceInvariantUuid = sliceTaskInfo.NSSTInfo.invariantUUID
+ serviceInfo.serviceUuid = sliceTaskInfo.NSSTInfo.UUID
+
+ nbiRequest.setServiceInfo(serviceInfo)
+ nbiRequest.setEsrInfo(esrInfo)
+ nbiRequest.setAllocateTnNssi(allocateTnNssi)
+
+ execution.setVariable("TnBHAllocateNssiNbiRequest", nbiRequest)
+ execution.setVariable("tnBHSliceTaskInfo", sliceTaskInfo)
+ }
+
+ /**
+ * Update relationship between
+ * 1. NSI and NSSI
+ * 2. Slice Profile and Service Profile
+ * 3. SliceProfile and NSSI
+ * 4. sliceProfile and endpoint
+ *
+ * @param execution
+ */
+ public void updateAnRelationship(DelegateExecution execution) {
+ //todo:
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ ResponseDescriptor result = execution.getVariable("anNssiAllocateResult") as ResponseDescriptor
+ String nssiId = result.getNssiId()
+ String endPointId = result.getEndPointId()
+ String nsiId = sliceParams.getSuggestNsiId()
+ String sliceProfileInstanceId = sliceParams.anSliceTaskInfo.sliceInstanceId
+ String serviceProfileInstanceId = sliceParams.serviceId
+ //nsi id
+
+ updateRelationship(execution, nsiId, nssiId)
+
+ updateRelationship(execution, serviceProfileInstanceId, sliceProfileInstanceId)
+
+ updateRelationship(execution, sliceProfileInstanceId, nssiId)
+
+ updateRelationship(execution, sliceProfileInstanceId, endPointId)
+
+ }
+
+
+ /**
+ * Update relationship between
+ * 1. NSI and NSSI
+ * 2. Slice Profile and Service Profile
+ * 3. SliceProfile and NSSI
+ *
+ * @param execution
+ */
+ public void updateCnRelationship(DelegateExecution execution) {
+ //todo:
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ NssiResponse result = execution.getVariable("cnNssiAllocateResult") as NssiResponse
+ String nssiId = result.getNssiId()
+ String nsiId = sliceParams.getSuggestNsiId()
+ String sliceProfileInstanceId = sliceParams.cnSliceTaskInfo.sliceInstanceId
+ String serviceProfileInstanceId = sliceParams.serviceId
+ //nsi id
+
+ updateRelationship(execution, nsiId, nssiId)
+
+ updateRelationship(execution, serviceProfileInstanceId, sliceProfileInstanceId)
+
+ updateRelationship(execution,sliceProfileInstanceId, nssiId)
+
+
+ }
+
+ /**
+ * Update relationship between
+ * 1. NSI and NSSI
+ * 2. Slice Profile and Service Profile
+ * 3. SliceProfile and NSSI
+ *
+ * @param execution
+ */
+ public void updateTnBHRelationship(DelegateExecution execution) {
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ NssiResponse result = execution.getVariable("tnBHNssiAllocateResult") as NssiResponse
+ String nssiId = result.getNssiId()
+ String nsiId = sliceParams.getSuggestNsiId()
+ String sliceProfileInstanceId = sliceParams.tnBHSliceTaskInfo.sliceInstanceId
+ String serviceProfileInstanceId = sliceParams.serviceId
+ //nsi id
+
+ updateRelationship(execution, nsiId, nssiId)
+
+ updateRelationship(execution, serviceProfileInstanceId, sliceProfileInstanceId)
+
+ updateRelationship(execution,sliceProfileInstanceId, nssiId)
+ }
+
+ /**
+ * sourceId -> targetId
+ * @param execution
+ * @param sourceId
+ * @param targetId
+ */
+ void updateRelationship(DelegateExecution execution, String sourceId, String targetId) {
+ //relation ship
+ Relationship relationship = new Relationship()
+
+ AAIResourceUri nsiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ targetId)
+
+ logger.info("Creating Allotted resource relationship, nsiServiceUri: " + nsiServiceUri)
+
+ relationship.setRelatedLink(nsiServiceUri.build().toString())
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ sourceId).relationshipAPI()
+ client.create(uri, relationship)
+ }
+
} \ No newline at end of file
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
index 081dddab99..9aa044a649 100644
--- 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
@@ -1,713 +1,114 @@
package org.onap.so.bpmn.infrastructure.scripts
-import org.camunda.bpm.engine.delegate.BpmnError
+import com.fasterxml.jackson.databind.ObjectMapper
import org.camunda.bpm.engine.delegate.DelegateExecution
-import org.onap.aai.domain.yang.ServiceInstance
-import org.onap.aai.domain.yang.SliceProfile
-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.SliceTaskParams
-import org.onap.so.beans.nsmf.TnSliceProfile
-import org.onap.so.beans.nsmf.UeMobilityLevel
+import org.onap.so.beans.nsmf.NssiResponse
+import org.onap.so.beans.nsmf.NssmfAdapterNBIRequest
+import org.onap.so.beans.nsmf.ResponseDescriptor
+import org.onap.so.beans.nsmf.ServiceInfo
+import org.onap.so.beans.nsmf.SliceTaskInfo
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
import org.onap.so.bpmn.common.scripts.ExceptionUtil
import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
-import org.onap.so.bpmn.core.RollbackData
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.aaiclient.client.aai.AAIObjectType
-import org.onap.aaiclient.client.aai.AAIResourcesClient
-import org.onap.aaiclient.client.aai.entities.AAIEdgeLabel
-import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
-import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
import org.slf4j.Logger
import org.slf4j.LoggerFactory
-import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.http.ResponseEntity
import static org.apache.commons.lang3.StringUtils.isBlank
+class DoAllocateNSSI extends AbstractServiceTaskProcessor {
-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();
+ private static final Logger logger = LoggerFactory.getLogger(DoAllocateNSSI.class);
ExceptionUtil exceptionUtil = new ExceptionUtil()
JsonUtils jsonUtil = new JsonUtils()
- private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
-
- /**
- * 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")
+ ObjectMapper objectMapper = new ObjectMapper()
- 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()")
- }
+ private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
+ private static final NSSMF_ALLOCATE_URL = "/api/rest/provMns/v1/NSS/SliceProfiles"
- void sendUpdateRequestNSSMF(DelegateExecution execution) {
- logger.debug("Enter sendUpdateRequestNSSMF in DoAllocateNSSI()")
- String domain = execution.getVariable("nsstDomain")
- String nssmfRequest = buildUpdateNSSMFRequest(execution, domain.toUpperCase())
+ private static final NSSMF_QUERY_JOB_STATUS_URL = "/NSS/jobs/%s"
- String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.trace("Enter preProcessRequest()")
- String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+ NssmfAdapterNBIRequest nbiRequest = execution.getVariable("nbiRequest") as NssmfAdapterNBIRequest
- if (nssmfResponse != null) {
- execution.setVariable("nssmfResponse", nssmfResponse)
- String nssiId = jsonUtil.getJsonValue(nssmfResponse, "nssiId")
- String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
- execution.setVariable("nssiId",nssiId)
- execution.setVariable("jobId",jobId)
+ //SliceTaskInfo sliceTaskInfo = execution.getVariable("sliceTaskInfo") as SliceTaskInfo
+ boolean isNSIOptionAvailable = execution.getVariable("isNSIOptionAvailable") as Boolean
+ if (isNSIOptionAvailable) {
+ nbiRequest.serviceInfo.setActionType("modify")
} else {
- logger.error("received error message from NSSMF : "+ nssmfResponse)
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ nbiRequest.serviceInfo.setActionType("allocate")
}
- logger.trace("Exit sendUpdateRequestNSSMF in DoAllocateNSSI()")
+ execution.setVariable("nbiRequest", nbiRequest)
+ logger.trace("Exit preProcessRequest")
}
+ /**
+ * send Create Request NSSMF
+ * @param execution
+ */
void sendCreateRequestNSSMF(DelegateExecution execution) {
- logger.debug("Enter sendCreateRequestNSSMF in DoAllocateNSSI()")
- //Prepare auth for NSSMF - Begin
- String domain = execution.getVariable("nsstDomain")
- String nssmfRequest = buildCreateNSSMFRequest(execution, domain.toUpperCase())
-
- String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
-
- String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
-
- if (nssmfResponse != null) {
- 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 {
- logger.error("received error message from NSSMF : "+ nssmfResponse)
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
- }
-
- logger.debug("Exit sendCreateRequestNSSMF in DoAllocateNSSI()")
+ NssmfAdapterNBIRequest nbiRequest = execution.getVariable("nbiRequest") as NssmfAdapterNBIRequest
+ String response = nssmfAdapterUtils.sendPostRequestNSSMF(execution, NSSMF_ALLOCATE_URL,
+ objectMapper.writeValueAsString(nbiRequest))
+ ResponseEntity responseEntity = objectMapper.readValue(response, ResponseEntity.class)
+ String respBody = responseEntity.getBody()
+ NssiResponse result = objectMapper.readValue(respBody, NssiResponse.class)
+ //todo: if success
+ //todo:
+ execution.setVariable("serviceInfo", nbiRequest.getServiceInfo())
+ execution.setVariable("esrInfo", nbiRequest.getEsrInfo())
}
- void getNSSMFProgresss(DelegateExecution execution) {
- logger.debug("Enter getNSSMFProgresss in DoAllocateNSSI()")
-
- String nssmfRequest = buildNSSMFProgressRequest(execution)
- String strUrl="/api/rest/provMns/v1/NSS/jobs/" + execution.getVariable("jobId")
-
- String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, strUrl, nssmfRequest)
-
- if(nssmfResponse != null){
- Boolean isNSSICreated = false
- execution.setVariable("nssmfResponse", nssmfResponse)
- Integer progress = 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 {
- logger.error("received error message from NSSMF : "+ nssmfResponse)
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
- }
- logger.debug("Exit getNSSMFProgresss in DoAllocateNSSI()")
- }
-
- void updateRelationship(DelegateExecution execution) {
- logger.debug("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.debug("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.setSNssai(sliceProfileMap.get("sNSSAI").toString())
- 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)
+ /**
+ * query nssi allocate status
+ * @param execution
+ */
+ void queryNSSIStatus(DelegateExecution execution) {
+ NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
+ NssiResponse nssiAllocateResult = execution.getVariable("nssiAllocateResult") as NssiResponse
+ String jobId = nssiAllocateResult.getJobId()
+ String nssiId = nssiAllocateResult.getNssiId()
- String snssai = serviceProfile.get("sNSSAI")
- List<String> snssaiList = Arrays.asList(snssai.split("\\|"))
- cnSliceProfile.setSnssaiList(snssaiList)
+ ServiceInfo serviceInfo = execution.getVariable("serviceInfo") as ServiceInfo
+ serviceInfo.setNssiId(nssiId)
+ EsrInfo esrInfo = execution.getVariable("esrInfo") as EsrInfo
- cnSliceProfile.setPerfReq(perfReq)
+ //nbiRequest.setResponseId(jobId)
+ nbiRequest.setServiceInfo(serviceInfo)
+ nbiRequest.setEsrInfo(esrInfo)
- 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"))
+ String endpoint = String.format(NSSMF_QUERY_JOB_STATUS_URL, jobId)
- TnSliceProfile tnSliceProfile = new TnSliceProfile()
- tnSliceProfile.setLatency(execution.getVariable("latency"))
- tnSliceProfile.setBandwidth(execution.getVariable("bandWidth"))
+ String response =
+ nssmfAdapterUtils.sendPostRequestNSSMF(execution, endpoint, objectMapper.writeValueAsString(nbiRequest))
- NsiInfo nsiInfo = new NsiInfo()
- nsiInfo.setNsiId(execution.getVariable("nsiInstanceID"))
- nsiInfo.setNsiName(execution.getVariable("nsiInstanceName"))
+ ResponseEntity responseEntity = objectMapper.readValue(response, ResponseEntity.class)
+ String result = responseEntity.getBody()
+ //todo;if success
+ ResponseDescriptor responseDescriptor = objectMapper.readValue(result, ResponseDescriptor.class)
- 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
+ //todo: handle status
+ execution.setVariable("nssiAllocateResult", responseDescriptor)
}
- 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
+ void prepareUpdateOrchestrationTask(DelegateExecution execution) {
+ //todo;update orchestration task
}
- 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")
+ void timeDelay(DelegateExecution execution) {
+ //todo: time delay
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateCommunicationService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateCommunicationService.groovy
index 26dcaa7ac4..7cdb084b7f 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateCommunicationService.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateCommunicationService.groovy
@@ -158,11 +158,11 @@ class DoCreateCommunicationService extends AbstractServiceTaskProcessor{
String sNSSAI_id = generateNSSAI(serviceInstanceId)
execution.setVariable("sNSSAI_id", sNSSAI_id)
- // 创建service
+ // create communication service
String serviceInstanceName = execution.getVariable("serviceInstanceName")
String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
String csServiceType = execution.getVariable("csServiceType")
- String aaiServiceRole = "communication-service" //待确定
+ String aaiServiceRole = "communication-service"
String oStatus = "processing"
String uuiRequest = execution.getVariable("uuiRequest")
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
index b71379449e..181e9d062a 100644
--- 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
@@ -1,28 +1,37 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, 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.onap.aai.domain.yang.AllottedResource
-
-import static org.apache.commons.lang3.StringUtils.*;
-
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.so.beans.nsmf.SliceTaskParamsAdapter
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.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.aaiclient.client.aai.AAIObjectType
import org.onap.aaiclient.client.aai.AAIResourcesClient
import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
@@ -34,13 +43,13 @@ import org.slf4j.LoggerFactory
class DoCreateSliceServiceInstance extends AbstractServiceTaskProcessor{
- private static final Logger logger = LoggerFactory.getLogger( DoCreateSliceServiceInstance.class);
+ private static final Logger logger = LoggerFactory.getLogger( DoCreateSliceServiceInstance.class)
+
JsonUtils jsonUtil = new JsonUtils()
ExceptionUtil exceptionUtil = new ExceptionUtil()
- CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
-
+ AAIResourcesClient client = getAAIClient()
/**
* Pre Process the BPMN Flow Request
* Inclouds:
@@ -48,86 +57,54 @@ class DoCreateSliceServiceInstance extends AbstractServiceTaskProcessor{
* generate the nsParameters
*/
void preProcessRequest (DelegateExecution execution) {
- String msg = ""
logger.trace("Enter preProcessRequest()")
- //Need update
- //1. Prepare service parameter.
- //2. Prepare slice profile parameters.
+ //here modelVersion is not set, we use modelUuid to decompose the service.
+ def isDebugLogEnabled = true
+ execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
- String sliceserviceInstanceId = execution.getVariable("serviceInstanceId")
- String allottedResourceId = UUID.randomUUID().toString()
- execution.setVariable("sliceserviceInstanceId", sliceserviceInstanceId)
- execution.setVariable("allottedResourceId", allottedResourceId)
+ logger.trace("Exit preProcessRequest")
+ }
+
+ /**
+ * prepare decompose service profile instance template
+ * @param execution
+ */
+ public void prepareDecomposeService(DelegateExecution execution) {
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")
}
+ /**
+ * create service-profile instance in aai
+ * @param execution
+ */
+ void createServiceProfileInstance(DelegateExecution execution) {
- 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) {
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
- ServiceDecomposition serviceDecomposition= execution.getVariable("sliceServiceDecomposition")
- String uuiRequest = execution.getVariable("uuiRequest")
+ ServiceDecomposition serviceDecomposition =
+ execution.getVariable("serviceProfileDecomposition") as ServiceDecomposition
ModelInfo modelInfo = serviceDecomposition.getModelInfo()
- String serviceRole = "e2eslice-service"
+ //String serviceRole = "e2eslice-service"
+ /**
+ * todo: ServiceProfile params changed
+ * todo: role
+ */
+ String serviceRole = "service-profile"
String serviceType = execution.getVariable("serviceType")
- Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
+ Map<String, Object> serviceProfile = sliceParams.getServiceProfile()
String ssInstanceId = execution.getVariable("serviceInstanceId")
try {
- org.onap.aai.domain.yang.ServiceInstance ss = new org.onap.aai.domain.yang.ServiceInstance()
+ ServiceInstance ss = new ServiceInstance()
ss.setServiceInstanceId(ssInstanceId)
String sliceInstanceName = execution.getVariable("serviceInstanceName")
ss.setServiceInstanceName(sliceInstanceName)
@@ -143,8 +120,11 @@ class DoCreateSliceServiceInstance extends AbstractServiceTaskProcessor{
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)
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ ssInstanceId)
client.create(uri, ss)
} catch (BpmnError e) {
throw e
@@ -157,7 +137,7 @@ class DoCreateSliceServiceInstance extends AbstractServiceTaskProcessor{
def rollbackData = execution.getVariable("RollbackData")
if (rollbackData == null) {
- rollbackData = new RollbackData();
+ rollbackData = new RollbackData()
}
//rollbackData.put("SERVICEINSTANCE", "disableRollback", disableRollback.toString())
rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true")
@@ -170,57 +150,100 @@ class DoCreateSliceServiceInstance extends AbstractServiceTaskProcessor{
}
+ /**
+ * create service profile in aai
+ * @param execution
+ */
+ void createServiceProfile(DelegateExecution execution) {
+
+ /**
+ * todo: ServiceProfile params changed
+ */
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+ Map<String, Object> serviceProfileMap = sliceParams.getServiceProfile()
- 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)
-// }
+ String serviceProfileInstanceId = execution.getVariable("serviceInstanceId")
+ String serviceProfileId = UUID.randomUUID().toString()
+ sliceParams.serviceProfile.put("profileId", serviceProfileId)
+
+ 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("")
+ serviceProfile.setExpDataRate(0)
+ serviceProfile.setTrafficDensity(0)
+ serviceProfile.setConnDensity(0)
+ try {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ serviceProfileInstanceId,
+ serviceProfileId)
+ client.create(uri, serviceProfile)
+ execution.setVariable("sliceTaskParams", sliceParams)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+
+ /**
+ * create allotted resource
+ * todo: unfinished
+ * @param execution
+ */
+ public void createAllottedResource(DelegateExecution execution) {
try {
- String allottedResourceId = execution.getVariable("allottedResourceId")
- ServiceDecomposition serviceDecomposition = execution.getVariable("sliceServiceDecomposition")
+
+ ServiceDecomposition serviceDecomposition =
+ execution.getVariable("serviceProfileDecomposition") as ServiceDecomposition
+
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)
+ for(org.onap.so.bpmn.core.domain.AllottedResource allottedResource : allottedResourceList) {
+ String allottedResourceId = UUID.randomUUID().toString()
+
AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE,
- execution.getVariable("globalSubscriberId"),execution.getVariable("subscriptionServiceType"),
- execution.getVariable("sliceserviceInstanceId"), allottedResourceId)
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ execution.getVariable("serviceInstanceId"),
+ 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()
+ AllottedResource resource = new 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)
+
+ client.create(allottedResourceUri, resource)
+
}
- //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
index ec9596e7f3..5cde856251 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
- # Copyright (c) 2019, CMCC Technologies Co., Ltd.
+ # Copyright (c) 2020, 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.
@@ -20,37 +20,36 @@
package org.onap.so.bpmn.infrastructure.scripts
-import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
-import groovy.json.JsonSlurper
import org.camunda.bpm.engine.delegate.DelegateExecution
-import org.onap.logging.filter.base.ONAPComponents
+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.NetworkType
+import org.onap.so.beans.nsmf.NssmfAdapterNBIRequest
import org.onap.so.beans.nsmf.SliceTaskParams
+import org.onap.so.beans.nsmf.SliceTaskParamsAdapter
+import org.onap.so.beans.nsmf.TnSliceProfile
+import org.onap.so.beans.nsmf.oof.SubnetCapability
+import org.onap.so.beans.nsmf.oof.SubnetType
+import org.onap.so.beans.nsmf.oof.TemplateInfo
import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
import org.onap.so.bpmn.common.scripts.OofUtils
import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.domain.AllottedResource
+import org.onap.so.bpmn.core.domain.ModelInfo
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.aaiclient.client.aai.AAIObjectType
-import org.onap.aaiclient.client.aai.AAIResourcesClient
-import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
-import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
-import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+
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
+import org.springframework.http.ResponseEntity
class DoCreateSliceServiceOption extends AbstractServiceTaskProcessor{
- private static final Logger logger = LoggerFactory.getLogger( DoCreateSliceServiceOption.class)
+ private static final Logger logger = LoggerFactory.getLogger(DoCreateSliceServiceOption.class)
ExceptionUtil exceptionUtil = new ExceptionUtil()
@@ -58,460 +57,528 @@ class DoCreateSliceServiceOption extends AbstractServiceTaskProcessor{
OofUtils oofUtils = new OofUtils()
- ObjectMapper objectMapper = new ObjectMapper()
+ private static final ObjectMapper objectMapper = new ObjectMapper()
+
+ private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
+
+ private static final String QUERY_SUB_NET_CAPABILITY = "/api/rest/provMns/v1/NSS/subnetCapabilityQuery"
+
+ private static final String QUERY_NSSI_SELECTION_CAPABILITY = "/api/rest/provMns/v1/NSS/NSSISelectionCapability"
void preProcessRequest (DelegateExecution execution) {
}
+ /**
+ * prepare the params for decompose nst
+ * @param execution
+ */
+ public void prepareDecomposeNST(DelegateExecution execution) {
- void getNSIOptionfromOOF(DelegateExecution execution) {
+ SliceTaskParamsAdapter sliceTaskParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
- String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
- logger.debug( "get NSI option OOF Url: " + urlString)
+ String modelUuid = sliceTaskParams.getNSTInfo().getUUID()
+ String modelInvariantUuid = sliceTaskParams.getNSTInfo().getInvariantUUID()
- boolean isNSISuggested = true
- 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")
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("nstServiceModelInfo", serviceModelInfo)
+ }
+
+ /**
+ * process the result of NST Decomposition
+ * @param execution
+ */
+ public void processDecompositionNST(DelegateExecution execution) {
+
+ List<TemplateInfo> nsstInfos = new ArrayList<>()
+ ServiceDecomposition nstServiceDecomposition =
+ execution.getVariable("nstServiceDecomposition") as ServiceDecomposition
+ //todo:
+ List<AllottedResource> allottedResources = nstServiceDecomposition.getAllottedResources()
+ for (AllottedResource allottedResource : allottedResources) {
+ TemplateInfo nsstInfo = new TemplateInfo()
+ nsstInfo.setUUID(allottedResource.getProvidingServiceModelUuid())
+ nsstInfo.setInvariantUUID(allottedResource.getProvidingServiceModelInvariantUuid())
+ nsstInfo.setName(allottedResource.getProvidingServiceModelName())
+ nsstInfos.add(nsstInfo)
}
- //Prepare auth for OOF - End
+ execution.setVariable("nsstInfos", nsstInfos)
- String requestId = execution.getVariable("msoRequestId")
- Map<String, Object> profileInfo = execution.getVariable("serviceProfile")
- Map<String, Object> nstSolution = execution.getVariable("nstSolution")
- logger.debug("Get NST selection from OOF: " + nstSolution.toString())
- String nstInfo = """{
- "modelInvariantId":"${nstSolution.invariantUUID}",
- "modelVersionId":"${nstSolution.UUID}",
- "modelName":"${nstSolution.NSTName}"
- }"""
+ execution.setVariable("maxNsstIndex", allottedResources.size() - 1)
+ execution.setVariable("currentNsstIndex", 0)
- String oofRequest = oofUtils.buildSelectNSIRequest(requestId, nstInfo, profileInfo)
- logger.debug("Sending request to OOF: " + oofRequest)
+ List<ServiceDecomposition> nsstServiceDecompositions = new ArrayList<>()
+ execution.setVariable("nsstServiceDecompositions", nsstServiceDecompositions)
+ }
- //send request to get NSI option - Begin
- URL url = new URL(urlString+"/api/oof/selection/nsi/v1")
- HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.OOF)
- httpClient.addAdditionalHeader("Authorization", authHeader)
- Response httpResponse = httpClient.post(oofRequest)
+ /**
+ * prepare the params for decompose nsst
+ * @param execution
+ */
+ public void prepareDecomposeNSST(DelegateExecution execution) {
- processOOFResponse(httpResponse, execution)
+ List<TemplateInfo> nsstInfos = execution.getVariable("nsstInfos") as List<TemplateInfo>
+ int index = execution.getVariable("currentNsstIndex") as Integer
+
+ String modelUuid = nsstInfos.get(index).getUUID()
+ String modelInvariantUuid = nsstInfos.get(index).getInvariantUUID()
+
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("nsstServiceModelInfo", serviceModelInfo)
- //解析sliceProfile
- logger.debug("start parseServiceProfile")
- parseServiceProfile(execution)
- logger.debug("end parseServiceProfile")
}
- private void processOOFResponse(Response httpResponse, DelegateExecution execution) {
- int responseCode = httpResponse.getStatus()
- logger.debug("OOF sync response code is: " + responseCode)
+ /**
+ * process the result of NSST Decomposition
+ * @param execution
+ */
+ public void processDecompositionNSST(DelegateExecution execution) {
- if (responseCode != 200) {
- exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
- logger.debug("Info: No NSI suggested by OOF")
- }
+ List<ServiceDecomposition> nsstServiceDecompositions =
+ execution.getVariable("nsstServiceDecompositions") as List<ServiceDecomposition>
- SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
- if (httpResponse.hasEntity()) {
- String OOFResponse = httpResponse.readEntity(String.class)
- logger.debug("NSI OOFResponse is: " + OOFResponse)
- execution.setVariable("OOFResponse", OOFResponse)
- //This needs to be changed to derive a value when we add policy to decide the solution options.
- Map OOFResponseObject = new JsonSlurper().parseText(OOFResponse)
- Map solutions = OOFResponseObject.get("solutions")
-
- String resourceSharingLevel = execution.getVariable("resourceSharingLevel")
- Boolean isSharable = resourceSharingLevel.equals("shared")
-
- if (solutions != null) {
- if (isSharable && hasSharedNSIsolutions(solutions)) {
- //sharedNSISolution
- processSharedNSISolutions(solutions, execution)
- }
- else if(solutions.containsKey("newNSISolutions")) {
- processNewNSISolutions(solutions, execution)
- }
- }
- execution.setVariable("sliceTaskParams", sliceTaskParams)
- logger.debug("sliceTaskParams: "+sliceTaskParams.convertToJson())
- }
- logger.debug("*** Completed options Call to OOF ***")
- }
+ ServiceDecomposition nsstServiceDecomposition =
+ execution.getVariable("nsstServiceDecomposition") as ServiceDecomposition
- private boolean hasSharedNSIsolutions( Map solutions){
- if(solutions.containsKey("sharedNSISolutions")){
- List sharedNSIsolutions = solutions.get("sharedNSISolutions")
- if (sharedNSIsolutions != null && !sharedNSIsolutions.isEmpty()) {
- return true
- }
- }
- return false
- }
+ nsstServiceDecompositions.add(nsstServiceDecomposition)
- private void processNewNSISolutions(Map solutions, DelegateExecution execution) {
- int index = 0
- List<Map> newNSISolutions = solutions.get("newNSISolutions")
- List<Map> NSSImap = new ArrayList<>()
- if (newNSISolutions != null && newNSISolutions.size() > 0) {
- NSSImap = newNSISolutions.get(index).get("NSSISolutions") as List<Map>
- for (Map nssi : NSSImap) {
- Map oofSliceProfile = nssi.get("sliceProfile")
- String domain = oofSliceProfile.getOrDefault("domainType","")
- logger.debug("OOF newNSISolutions SliceProfile: " +oofSliceProfile.toString()+",domain:${domain}")
- if(null != domain){
- //TODO
-// def nssiSolution = nssi.get("NSSISolution") as Map<String, ?>
-// String nssiName = nssiSolution.getOrDefault("NSSIName", "")
-// String nssiId = nssiSolution.getOrDefault("NSSIId", "")
-// saveNSSIId(nssi, sliceTaskParams)
- Map<String, Object> sliceProfile = getSliceProfile(domain, execution, oofSliceProfile)
- saveSliceProfile(execution, domain, sliceProfile)
-
- }
- }
- }
- }
+ execution.setVariable("nsstServiceDecompositions", nsstServiceDecompositions)
+
+
+
+
+ int num = execution.getVariable("maxNsstIndex") as Integer
+ int index = execution.getVariable("currentNsstIndex") as Integer
- private void processSharedNSISolutions(Map solutions, DelegateExecution execution) {
- String nsiName, nsiInstanceId, nssiId, nssiName
- SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
-
- Map sharedNSIsolution = ((List) solutions.get("sharedNSISolutions"))?.get(0)
- nsiInstanceId = sharedNSIsolution.getOrDefault("NSIId", "")
- nsiName = sharedNSIsolution.getOrDefault("NSIName", "")
- sliceTaskParams.setSuggestNsiId(nsiInstanceId)
- sliceTaskParams.setSuggestNsiName(nsiName)
-
- //Temporary modification
- List NSSIs = sharedNSIsolution.get("NSSIs")
- for(Map nssi : NSSIs){
- Map oofSliceProfile = ((List)nssi.get("sliceProfile"))?.get(0)
- String domain = oofSliceProfile.getOrDefault("domainType","")
- nssiId = nssi.getOrDefault("NSSIId","")
- nssiName = nssi.getOrDefault("NSSIName","")
- saveNSSIId(domain, nssiId, nssiName,execution)
- Map<String, Object> sliceProfile = getSliceProfile(domain, execution, oofSliceProfile)
- saveSliceProfile(execution, domain, sliceProfile)
- logger.debug("OOF sharedNSISolution SliceProfile:"+oofSliceProfile.toString()+",domain:${domain}")
- logger.debug("OOF sharedNSISolution nsiInstanceId:${nsiInstanceId}, nsiName:${nsiName}, nssiId:${nssiId}, nssiName:${nssiName}")
+ execution.setVariable("currentNsstIndex", index + 1)
+
+ if (index >= num) {
+ execution.setVariable("nsstHandleContinue", false)
+ } else {
+ execution.setVariable("nsstHandleContinue", true)
}
+
}
- private void parseServiceProfile(DelegateExecution execution) {
- logger.debug("Start parseServiceProfile")
- String serviceType = execution.getVariable("serviceType")
- Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
- SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
- // set sliceProfile for three domains
- if(!sliceTaskParams.getSliceProfileAn()){
- Map<String, Object> sliceProfileAn = getSliceProfile( "AN", execution,null)
- saveSliceProfile(execution,"AN",sliceProfileAn)
- }
+ /**
+ * set nsst info to sliceTaskParams by type
+ * @param execution
+ */
+ public void handleNsstByType(DelegateExecution execution) {
+ //todo: set to sliceTaskParams by type
- if(!sliceTaskParams.getSliceProfileTn()){
- Map<String, Object> sliceProfileTn = getSliceProfile( "TN", execution,null)
- saveSliceProfile(execution,"TN",sliceProfileTn)
- }
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ List<ServiceDecomposition> nsstServiceDecompositions =
+ execution.getVariable("nsstServiceDecompositions") as List<ServiceDecomposition>
+
+ List<SubnetCapability> subnetCapabilities = new ArrayList<>()
+
+
+
+ for (ServiceDecomposition serviceDecomposition : nsstServiceDecompositions) {
+ //todo:
+ SubnetCapability subnetCapability = new SubnetCapability()
- if(!sliceTaskParams.getSliceProfileCn()){
- Map<String, Object> sliceProfileCn = getSliceProfile( "CN", execution,null, )
- saveSliceProfile(execution,"CN",sliceProfileCn)
+ handleByType(execution, serviceDecomposition, sliceParams, subnetCapability)
+
+ subnetCapabilities.add(subnetCapability)
}
- logger.debug("Finish parseServiceProfile")
+ execution.setVariable("sliceTaskParams", sliceParams)
+ execution.setVariable("subnetCapabilities", subnetCapabilities)
}
- private void saveSliceProfile(DelegateExecution execution, String domain, Map<String, Object> sliceProfile){
- SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
- if(domain.equalsIgnoreCase("AN")){
- execution.setVariable("sliceProfileAn", sliceProfile)
- sliceTaskParams.setSliceProfileAn(sliceProfile)
- logger.debug("sliceProfileAn: " + sliceProfile)
+ private void handleByType(DelegateExecution execution, ServiceDecomposition serviceDecomposition,
+ SliceTaskParamsAdapter sliceParams, SubnetCapability subnetCapability) {
+ //todo:
+ String domainType = ""
+ ModelInfo modelInfo = serviceDecomposition.getModelInfo()
+ String vendor = serviceDecomposition.getServiceRole()
+ SubnetType subnetType
+
+ switch (domainType) {
+ case "tn_bh":
+ subnetType = SubnetType.TN_BH
+ sliceParams.tnBHSliceTaskInfo.vendor = vendor
+ sliceParams.tnBHSliceTaskInfo.subnetType = subnetType
+ sliceParams.tnBHSliceTaskInfo.networkType = subnetType.networkType
+ sliceParams.tnBHSliceTaskInfo.NSSTInfo.UUID = modelInfo.getModelUuid()
+ sliceParams.tnBHSliceTaskInfo.NSSTInfo.invariantUUID = modelInfo.getModelInvariantUuid()
+ sliceParams.tnBHSliceTaskInfo.NSSTInfo.name = modelInfo.getModelName()
+
+ break
+ case "tn_mh":
+ subnetType = SubnetType.TN_MH
+ sliceParams.tnMHSliceTaskInfo.vendor = vendor
+ sliceParams.tnMHSliceTaskInfo.subnetType = subnetType
+ sliceParams.tnMHSliceTaskInfo.networkType = subnetType.networkType
+ sliceParams.tnMHSliceTaskInfo.NSSTInfo.UUID = modelInfo.getModelUuid()
+ sliceParams.tnMHSliceTaskInfo.NSSTInfo.invariantUUID = modelInfo.getModelInvariantUuid()
+ sliceParams.tnMHSliceTaskInfo.NSSTInfo.name = modelInfo.getModelName()
+
+ break
+ case "an_nf":
+ subnetType = SubnetType.AN_NF
+ sliceParams.anSliceTaskInfo.vendor = vendor
+ sliceParams.anSliceTaskInfo.subnetType = subnetType
+ sliceParams.anSliceTaskInfo.networkType = subnetType.networkType
+ sliceParams.anSliceTaskInfo.NSSTInfo.UUID = modelInfo.getModelUuid()
+ sliceParams.anSliceTaskInfo.NSSTInfo.invariantUUID = modelInfo.getModelInvariantUuid()
+ sliceParams.anSliceTaskInfo.NSSTInfo.name = modelInfo.getModelName()
+ break
+ case "cn":
+ subnetType = SubnetType.CN
+ sliceParams.cnSliceTaskInfo.vendor = vendor
+ sliceParams.cnSliceTaskInfo.subnetType = subnetType
+ sliceParams.cnSliceTaskInfo.networkType = subnetType.networkType
+ sliceParams.cnSliceTaskInfo.NSSTInfo.UUID = modelInfo.getModelUuid()
+ sliceParams.cnSliceTaskInfo.NSSTInfo.invariantUUID = modelInfo.getModelInvariantUuid()
+ sliceParams.cnSliceTaskInfo.NSSTInfo.name = modelInfo.getModelName()
+ break
+ default:
+ subnetType = null
+ break
+
+ //todo
+
}
- else if(domain.equalsIgnoreCase("TN")){
- execution.setVariable("sliceProfileTn", sliceProfile)
- sliceTaskParams.setSliceProfileTn(sliceProfile)
- logger.debug("sliceProfileTn: " + sliceProfile)
+ if (subnetType == null) {
+ //todo: throw error
+ return
}
- else if(domain.equalsIgnoreCase("CN")){
- execution.setVariable("sliceProfileCn", sliceProfile)
- sliceTaskParams.setSliceProfileCn(sliceProfile)
- logger.debug("sliceProfileCn: " + sliceProfile)
+ String response = querySubnetCapability(execution, vendor, subnetType)
+ ResponseEntity responseEntity = objectMapper.readValue(response, ResponseEntity.class)
+
+ Map<String, Object> result = responseEntity.getBody() as Map
+ for (Map.Entry<String, Object> entry : result.entrySet()) {
+ subnetCapability.setDomainType(entry.getKey())
+ subnetCapability.setCapabilityDetails(entry.getValue())
}
}
- private void saveNSSIId(String domain, String nssiId, String nssiName, DelegateExecution execution) {
- SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
- if(domain.equalsIgnoreCase("AN")){
- sliceTaskParams.setAnSuggestNssiId(nssiId)
- sliceTaskParams.setAnSuggestNssiName(nssiName)
- }
- else if(domain.equalsIgnoreCase("CN")){
- sliceTaskParams.setCnSuggestNssiId(nssiId)
- sliceTaskParams.setCnSuggestNssiName(nssiName)
- }
- else if(domain.equalsIgnoreCase("TN")){
- sliceTaskParams.setTnSuggestNssiId(nssiId)
- sliceTaskParams.setTnSuggestNssiName(nssiName)
- }
+ /**
+ * query Subnet Capability of TN AN CN
+ * @param execution
+ */
+ private String querySubnetCapability(DelegateExecution execution, String vendor, SubnetType subnetType) {
+
+ String strRequest = objectMapper.writeValueAsString(buildQuerySubnetCapRequest(vendor, subnetType))
+
+ String response = nssmfAdapterUtils.sendPostRequestNSSMF(execution, QUERY_SUB_NET_CAPABILITY, strRequest)
+ return response
}
- private Map getSliceProfile(String domain, DelegateExecution execution, Map<String, Object> oofSliceProfile) {
- String profileMapStr
- Map<String, Object> serviceProfile = execution.getVariable("serviceProfile")
- Integer domainLatency = (Integer) serviceProfile.get("latency")/3
-
- if(domain.equalsIgnoreCase("AN")){
- profileMapStr = """ {
- "latency": ${domainLatency},
- "sNSSAI": "sNSSAI",
- "uEMobilityLevel": "uEMobilityLevel",
- "coverageAreaTAList": "coverageAreaTAList",
- "5QI": 100
- }"""
- }
- else if(domain.equalsIgnoreCase("TN")){
- profileMapStr =""" {
- "latency":${domainLatency},
- "sNSSAI":"sNSSAI",
- "e2eLatency":"latency",
- "bandwidth": 100
- }"""
- }
- else if(domain.equalsIgnoreCase("CN")){
- profileMapStr = """ {
- "areaTrafficCapDL":"areaTrafficCapDL",
- "maxNumberofUEs":"maxNumberofUEs",
- "latency":${domainLatency},
- "expDataRateUL":"expDataRateUL",
- "sNSSAI":"sNSSAI",
- "areaTrafficCapUL":"areaTrafficCapUL",
- "uEMobilityLevel":"uEMobilityLevel",
- "expDataRateDL":"expDataRateDL",
- "activityFactor":"activityFactor",
- "resourceSharingLevel":"resourceSharingLevel"
- }"""
- }
+ /**
+ * build request body for querying Subnet Capability
+ * @param vendor
+ * @param subnetTypes
+ * @param networkType
+ * @return
+ */
+ private static String buildQuerySubnetCapRequest(String vendor, SubnetType subnetType) {
+ NssmfAdapterNBIRequest request = new NssmfAdapterNBIRequest()
+
+ List<String> subnetTypes = new ArrayList<>()
+ subnetTypes.add(subnetType.subnetType)
+ Map<String, Object> paramMap = new HashMap()
+ paramMap.put("subnetTypes", subnetTypes)
+
+ request.setSubnetCapabilityQuery(objectMapper.writeValueAsString(paramMap))
+
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setVendor(vendor)
+ esrInfo.setNetworkType(subnetType.networkType)
+
+ request.setEsrInfo(esrInfo)
- logger.debug("Profile map for " + domain + " : " + profileMapStr)
- Map<String, Object> profileMaps = objectMapper.readValue(profileMapStr.trim().replaceAll(" ", ""), new TypeReference<Map<String, String>>(){})
- Map<String, Object> sliceProfile = [:]
- for (Map.Entry<String, String> profileMap : profileMaps) {
- String key = profileMap.key
- String value = profileMaps.get(key)
- if(null != oofSliceProfile && oofSliceProfile.keySet().contains(key)){
- sliceProfile.put(key, oofSliceProfile.get(key))
- logger.debug("Get from oof, key:${key}, value: ${oofSliceProfile.get(key)}")
+ String strRequest = objectMapper.writeValueAsString(request)
+
+ return strRequest
+ }
+
+ /**
+ * todo: need rewrite
+ * prepare select nsi request
+ * @param execution
+ */
+ public void preNSIRequest(DelegateExecution execution) {
+
+ String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
+ logger.debug( "get NSI option OOF Url: " + urlString)
+
+
+ String requestId = execution.getVariable("msoRequestId")
+ String messageType = "NSISelectionResponse"
+
+ execution.setVariable("nsiSelectionUrl", "/api/oof/selection/nsi/v1")
+ execution.setVariable("nsiSelection_messageType", messageType)
+ execution.setVariable("nsiSelection_correlator", requestId)
+ String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution)
+ execution.setVariable("nsiSelection_timeout", timeout)
+
+ SliceTaskParamsAdapter sliceParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ Map<String, Object> profileInfo = sliceParams.getServiceProfile()
+ TemplateInfo nstInfo = sliceParams.getNSTInfo()
+
+ List<TemplateInfo> nsstInfos = execution.getVariable("nsstInfos") as List<TemplateInfo>
+
+ List<SubnetCapability> subnetCapabilities =
+ execution.getVariable("subnetCapabilities") as List<SubnetCapability>
+
+ String oofRequest = oofUtils.buildSelectNSIRequest(requestId, nstInfo, nsstInfos,
+ messageType, profileInfo, subnetCapabilities, timeout as Integer)
+
+ execution.setVariable("nsiSelection_oofRequest", oofRequest)
+ logger.debug("Sending request to OOF: " + oofRequest)
+ }
+
+ /**
+ * todo: need rewrite
+ * process select nsi response
+ * @param execution
+ */
+ public void processNSIResp(DelegateExecution execution) {
+
+ SliceTaskParamsAdapter sliceTaskParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+
+ String OOFResponse = execution.getVariable("nsiSelection_oofResponse")
+ logger.debug("NSI OOFResponse is: " + OOFResponse)
+ execution.setVariable("OOFResponse", OOFResponse)
+ //This needs to be changed to derive a value when we add policy to decide the solution options.
+
+ Map<String, Object> resMap = objectMapper.readValue(OOFResponse, Map.class)
+ List<Map<String, Object>> nsiSolutions = (List<Map<String, Object>>) resMap.get("solutions")
+ Map<String, Object> solution = nsiSolutions.get(0)
+
+ String resourceSharingLevel = execution.getVariable("resourceSharingLevel")
+ Boolean isSharable = resourceSharingLevel == "shared"
+
+ if (solution != null) {
+ if (isSharable && solution.get("existingNSI")) {
+ //sharedNSISolution
+ processSharedNSI(solution, sliceTaskParams)
}
- else if(serviceProfile.keySet().contains(value)){
- sliceProfile.put(key, serviceProfile.get(value))
+ else if(solution.containsKey("newNSISolution")) {
+ processNewNSI(solution, sliceTaskParams)
}
- else{
- sliceProfile.put(key, profileMaps.get(key))
+ }
+ execution.setVariable("sliceTaskParams", sliceTaskParams)
+ //logger.debug("sliceTaskParams: " + sliceTaskParams.convertToJson())
+ logger.debug("*** Completed options Call to OOF ***")
+ }
+
+ private void processSharedNSI(Map<String, Object> solution, SliceTaskParamsAdapter sliceParams) {
+ Map<String, Object> sharedNSISolution = solution.get("sharedNSISolution") as Map
+
+ String nsiId = sharedNSISolution.get("NSIId")
+ String nsiName = sharedNSISolution.get("NSIName")
+ sliceParams.setSuggestNsiId(nsiId)
+ sliceParams.setSuggestNsiName(nsiName)
+ }
+
+ private void processNewNSI(Map<String, Object> solution, SliceTaskParamsAdapter sliceParams) {
+ Map<String, Object> newNSISolution = solution.get("newNSISolution") as Map
+ List<Map> sliceProfiles = newNSISolution.get("sliceProfiles") as List<Map>
+ for (Map sliceProfile : sliceProfiles) {
+ String domainType = sliceProfile.get("domainType")
+ switch (domainType.toLowerCase()) {
+ case "tn-bh":
+ sliceParams.tnBHSliceTaskInfo.sliceProfile = sliceProfile as TnSliceProfile
+ break
+ case "an-nf":
+ sliceParams.anSliceTaskInfo.sliceProfile = sliceProfile as AnSliceProfile
+ break
+ case "cn":
+ sliceParams.cnSliceTaskInfo.sliceProfile = sliceProfile as CnSliceProfile
+ break
+ default:
+ break
}
+
+ //todo
+
}
- return sliceProfile
}
- void processDecomposition(DelegateExecution execution){
- logger.debug("Start processDecomposition")
+ /**
+ * get NSSI Selection Capability for AN
+ * @param execution
+ */
+ public void getNSSISelectionCap4AN(DelegateExecution execution) {
+
+ def vendor = execution.getVariable("vendor") as String
+
+ String strRequest = buildNSSISelectionReq(vendor, NetworkType.ACCESS)
- ServiceDecomposition serviceDecomposition= execution.getVariable("serviceDecomposition")
- SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams")
- String nstName = serviceDecomposition.getModelInfo().getModelName()
- String nstId = serviceDecomposition.getModelInfo().getModelUuid()
- sliceTaskParams.setNstName(nstName)
- sliceTaskParams.setNstId(nstId)
+ String response = nssmfAdapterUtils.sendPostRequestNSSMF(execution, QUERY_NSSI_SELECTION_CAPABILITY, strRequest)
- logger.debug("End processDecomposition")
+ Map<String, Object> resMap = objectMapper.readValue(response, Map.class)
+
+ String selection = resMap.get("selection")
+
+
+ if ("NSMF".equalsIgnoreCase(selection)) {
+ execution.setVariable("NEED_AN_NSSI_SELECTION", true)
+ }
}
+ /**
+ * get NSSI Selection Capability for TN
+ * @param execution
+ */
+ public void getNSSISelectionCap4TN(DelegateExecution execution) {
- void prepareNSTDecompose(DelegateExecution execution) {
+ def vendor = execution.getVariable("vendor") as String
- String modelUuid = execution.getVariable("nstModelUuid")
- String modelInvariantUuid = execution.getVariable("nstModelInvariantUuid")
+ String strRequest = buildNSSISelectionReq(vendor, NetworkType.TRANSPORT)
- String serviceModelInfo = """{
- "modelInvariantUuid":"${modelInvariantUuid}",
- "modelUuid":"${modelUuid}",
- "modelVersion":""
- }"""
- execution.setVariable("serviceModelInfo", serviceModelInfo)
+ String response = nssmfAdapterUtils.sendPostRequestNSSMF(execution, QUERY_NSSI_SELECTION_CAPABILITY, strRequest)
+
+ Map<String, Object> resMap = objectMapper.readValue(response, Map.class)
+
+ String selection = resMap.get("selection")
+
+ if ("NSMF".equalsIgnoreCase(selection)) {
+ execution.setVariable("NEED_TN_NSSI_SELECTION", true)
+ }
}
- 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)
+ /**
+ * get NSSI Selection Capability for CN
+ * @param execution
+ */
+ public void getNSSISelectionCap4CN(DelegateExecution execution) {
+
+ def vendor = execution.getVariable("vendor") as String
+
+ String strRequest = buildNSSISelectionReq(vendor, NetworkType.CORE)
+
+ String response = nssmfAdapterUtils.sendPostRequestNSSMF(execution, QUERY_NSSI_SELECTION_CAPABILITY, strRequest)
+
+ Map<String, Object> resMap = objectMapper.readValue(response, Map.class)
+
+ String selection = resMap.get("selection")
+
+ if ("NSMF".equalsIgnoreCase(selection)) {
+ execution.setVariable("NEED_CN_NSSI_SELECTION", true)
+ }
+ }
+
+ /**
+ * build NSSI Selection Capability Request body to nssmf adapter
+ * @param vendor
+ * @param networkType
+ * @return
+ */
+ private static String buildNSSISelectionReq(String vendor, NetworkType networkType) {
+ NssmfAdapterNBIRequest request = new NssmfAdapterNBIRequest()
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setVendor(vendor)
+ esrInfo.setNetworkType(networkType)
+ request.setEsrInfo(esrInfo)
+
+ return objectMapper.writeValueAsString(request)
}
+ /**
+ * if exist nssi need to select?
+ * @param execution
+ */
+ public void handleNssiSelect(DelegateExecution execution) {
- 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()")
+ SliceTaskParamsAdapter sliceTaskParams =
+ execution.getVariable("sliceTaskParams") as SliceTaskParamsAdapter
+ //todo
}
- void getNSSTOption(DelegateExecution execution) {
- ServiceDecomposition serviceDecomposition= execution.getVariable("serviceDecomposition")
+ /**
+ * todo: need rewrite
+ * prepare select nssi request
+ * @param execution
+ */
+ public void preNSSIRequest(DelegateExecution execution) {
+
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
+
+ boolean isNSISuggested = true
+ execution.setVariable("isNSISuggested", isNSISuggested)
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)
+ String messageType = "NSISelectionResponse"
+ Map<String, Object> profileInfo = execution.getVariable("serviceProfile") as Map
+ Map<String, Object> nstSolution = execution.getVariable("nstSolution") as Map
+ logger.debug("Get NST selection from OOF: " + nstSolution.toString())
+ String nstInfo = """{
+ "modelInvariantId":"${nstSolution.invariantUUID}",
+ "modelVersionId":"${nstSolution.UUID}",
+ "modelName":"${nstSolution.NSTName}"
+ }"""
- 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)
+ execution.setVariable("nsiSelectionUrl", "/api/oof/selection/nsi/v1")
+ execution.setVariable("nsiSelection_messageType", messageType)
+ execution.setVariable("nsiSelection_correlator", requestId)
+ String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution)
+ execution.setVariable("nsiSelection_timeout", timeout)
- int responseCode = httpResponse.getStatus()
- logger.debug("OOF sync response code is: " + responseCode)
+ //todo
+ String oofRequest = oofUtils.buildSelectNSIRequest(requestId, nstInfo, messageType, profileInfo)
- if(responseCode != 200){
- exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
- }
+ execution.setVariable("nsiSelection_oofRequest", oofRequest)
+ logger.debug("Sending request to OOF: " + oofRequest)
+ }
- 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)
+ /**
+ * process select nssi response
+ * todo: unfinished
+ * @param execution
+ */
+ public void processNSSIResp(DelegateExecution execution) {
+
+ SliceTaskParams sliceTaskParams = execution.getVariable("sliceTaskParams") as SliceTaskParams
+ String OOFResponse = execution.getVariable("nsiSelection_oofResponse")
+ logger.debug("NSI OOFResponse is: " + OOFResponse)
+ execution.setVariable("OOFResponse", OOFResponse)
+ //This needs to be changed to derive a value when we add policy to decide the solution options.
+
+ Map<String, Object> resMap = objectMapper.readValue(OOFResponse, Map.class)
+ List<Map<String, Object>> nsiSolutions = (List<Map<String, Object>>) resMap.get("solutions")
+ Map<String, Object> solutions = nsiSolutions.get(0)
+
+ String resourceSharingLevel = execution.getVariable("resourceSharingLevel")
+ Boolean isSharable = resourceSharingLevel == "shared"
+
+ if (solutions != null) {
+ if (isSharable && solutions.get("existingNSI")) {
+ //sharedNSISolution
+ //processSharedNSISolutions(solutions, execution)
+ }
+ else if(solutions.containsKey("newNSISolution")) {
+ //processNewNSISolutions(solutions, execution)
}
}
- logger.debug("Prepare NSSI option completed ")
+ execution.setVariable("sliceTaskParams", sliceTaskParams)
+ logger.debug("sliceTaskParams: "+sliceTaskParams.convertToJson())
+ logger.debug("*** Completed options Call to OOF ***")
+
+ logger.debug("start parseServiceProfile")
+ //parseServiceProfile(execution)
+ logger.debug("end parseServiceProfile")
}
+
+
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateTnNssiInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateTnNssiInstance.groovy
new file mode 100644
index 0000000000..534467f6ab
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateTnNssiInstance.groovy
@@ -0,0 +1,231 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.SliceProfile
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+class DoCreateTnNssiInstance extends AbstractServiceTaskProcessor {
+
+ private static final Logger logger = LoggerFactory.getLogger(DoCreateTnNssiInstance.class);
+ JsonUtils jsonUtil = new JsonUtils()
+ TnNssmfUtils tnNssmfUtils = new TnNssmfUtils()
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ String Prefix = "DCTN_"
+
+ void preProcessRequest(DelegateExecution execution) {
+ String msg = ""
+ logger.trace("Enter preProcessRequest()")
+
+ execution.setVariable("prefix", Prefix)
+
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelUuid = execution.getVariable("modelUuid")
+ //here modelVersion is not set, we use modelUuid to decompose the service.
+ def isDebugLogEnabled = true
+ execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+
+ logger.trace("Exit preProcessRequest")
+ }
+
+
+ void createSliceProfile(DelegateExecution execution) {
+
+ String sliceserviceInstanceId = execution.getVariable("sliceServiceInstanceId")
+ String sliceProfileStr = execution.getVariable("sliceProfile")
+ String sliceProfileId = UUID.randomUUID().toString()
+ SliceProfile sliceProfile = new SliceProfile();
+ sliceProfile.setProfileId(sliceProfileId)
+ sliceProfile.setLatency(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "latency")))
+ sliceProfile.setResourceSharingLevel(jsonUtil.getJsonValue(sliceProfileStr, "resourceSharingLevel"))
+ sliceProfile.setSNssai(tnNssmfUtils.getFirstSnssaiFromSliceProfile(sliceProfileStr)) //TODO: should be list
+
+ sliceProfile.setE2ELatency(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "latency")))
+ sliceProfile.setMaxBandwidth(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "maxBandwidth")))
+
+ //TODO: new API
+ sliceProfile.setReliability(new Object())
+ try {
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, execution.getVariable
+ ("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"), sliceserviceInstanceId, sliceProfileId)
+ 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)
+ }
+ }
+
+
+ void createServiceInstance(DelegateExecution execution) {
+
+ String serviceRole = "TN"
+ String serviceType = execution.getVariable("subscriptionServiceType")
+ String ssInstanceId = execution.getVariable("sliceServiceInstanceId")
+ String sliceProfileStr = execution.getVariable("sliceProfile")
+ try {
+ org.onap.aai.domain.yang.ServiceInstance ss = new org.onap.aai.domain.yang.ServiceInstance()
+ ss.setServiceInstanceId(ssInstanceId)
+ String sliceInstanceName = execution.getVariable("sliceServiceInstanceName")
+ ss.setServiceInstanceName(sliceInstanceName)
+ ss.setServiceType(serviceType)
+ String serviceStatus = "allocated"
+ ss.setOrchestrationStatus(serviceStatus)
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelUuid = execution.getVariable("modelUuid")
+ ss.setModelInvariantId(modelInvariantUuid)
+ ss.setModelVersionId(modelUuid)
+ String serviceInstanceLocationid = tnNssmfUtils.getFirstPlmnIdFromSliceProfile(sliceProfileStr)
+ ss.setServiceInstanceLocationId(serviceInstanceLocationid)
+ String snssai = tnNssmfUtils.getFirstSnssaiFromSliceProfile(sliceProfileStr)
+ ss.setEnvironmentContext(snssai)
+ ss.setServiceRole(serviceRole)
+ AAIResourcesClient client = getAAIClient()
+ 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 DoCreateTnNssiInstance.createServiceInstance. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+
+
+ void createAllottedResource(DelegateExecution execution) {
+ String serviceInstanceId = execution.getVariable('sliceServiceInstanceId')
+
+ AAIResourcesClient resourceClient = getAAIClient()
+ AAIResourceUri ssServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)
+
+ try {
+ List<String> networkStrList = jsonUtil.StringArrayToList(execution.getVariable("transportSliceNetworks"))
+
+ for (String networkStr : networkStrList) {
+ String allottedResourceId = UUID.randomUUID().toString()
+ AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE,
+ execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"),
+ execution.getVariable("sliceserviceInstanceId"), allottedResourceId)
+ execution.setVariable("allottedResourceUri", allottedResourceUri)
+ String modelInvariantId = execution.getVariable("modelInvariantUuid")
+ String modelVersionId = execution.getVariable("modelUuid")
+
+ org.onap.aai.domain.yang.AllottedResource resource = new org.onap.aai.domain.yang.AllottedResource()
+ resource.setId(allottedResourceId)
+ resource.setType("TsciNetwork")
+ resource.setAllottedResourceName("network_" + execution.getVariable("sliceServiceInstanceName"))
+ 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());
+
+ String linkArrayStr = jsonUtil.getJsonValue(networkStr, "connectionLinks")
+ createLogicalLinksForAllocatedResource(execution, linkArrayStr, serviceInstanceId, allottedResourceId)
+ }
+
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception in createAaiAR " + ex.getMessage())
+ }
+ }
+
+ void createLogicalLinksForAllocatedResource(DelegateExecution execution,
+ String linkArrayStr, String serviceInstanceId,
+ String allottedResourceId) {
+
+ try {
+ List<String> linkStrList = jsonUtil.StringArrayToList(linkArrayStr)
+
+ for (String linkStr : linkStrList) {
+ String logicalLinkId = UUID.randomUUID().toString()
+ String epA = jsonUtil.getJsonValue(linkStr, "transportEndpointA")
+ String epB = jsonUtil.getJsonValue(linkStr, "transportEndpointB")
+ String modelInvariantId = execution.getVariable("modelInvariantUuid")
+ String modelVersionId = execution.getVariable("modelUuid")
+
+ org.onap.aai.domain.yang.LogicalLink resource = new org.onap.aai.domain.yang.LogicalLink()
+ resource.setLinkId(logicalLinkId)
+ resource.setLinkName(epA)
+ resource.setLinkName2(epB)
+ resource.setModelInvariantId(modelInvariantId)
+ resource.setModelVersionId(modelVersionId)
+
+ AAIResourceUri logicalLinkUri = AAIUriFactory.createResourceUri(AAIObjectType.LOGICAL_LINK, logicalLinkId)
+ getAAIClient().create(logicalLinkUri, resource)
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,
+ "Exception in createLogicalLinksForAllocatedResource" + ex.getMessage())
+ }
+ }
+
+ void preprocessSdncAllocateTnNssiRequest(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' +
+ 'execution=' + execution.getId() +
+ ')'
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+ logger.trace('Entered ' + method)
+
+ logger.trace("STARTED preProcessSDNCActivateRequest Process")
+ try {
+ String serviceInstanceId = execution.getVariable("sliceServiceInstanceId")
+
+ String createSDNCRequest = tnNssmfUtils.buildSDNCRequest(execution, serviceInstanceId, "create")
+
+ execution.setVariable("TNNSSMF_SDNCRequest", createSDNCRequest)
+ logger.debug("Outgoing SDNCRequest is: \n" + createSDNCRequest)
+
+ } catch (Exception e) {
+ logger.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002,
+ "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage())
+ }
+ logger.trace("COMPLETED preProcessSDNCActivateRequest Process")
+ }
+
+
+ void validateSDNCResponse(DelegateExecution execution, String response, String method) {
+ tnNssmfUtils.validateSDNCResponse(execution, response, method)
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeAllocateAccessNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeAllocateAccessNSSI.groovy
new file mode 100644
index 0000000000..2ca0da4cbb
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeAllocateAccessNSSI.groovy
@@ -0,0 +1,556 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Wipro Limited. 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 static org.apache.commons.lang3.StringUtils.isBlank
+
+import javax.ws.rs.NotFoundException
+import javax.ws.rs.core.Response
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.*
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.beans.nsmf.DeAllocateNssi
+import org.onap.so.beans.nsmf.EsrInfo
+import org.onap.so.beans.nsmf.ServiceInfo
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
+import org.onap.so.bpmn.common.scripts.OofUtils
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.UrnPropertiesReader
+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.oof.adapter.beans.payload.OofRequest
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.google.gson.JsonObject
+
+/**
+ * Internal AN NSSMF to handle NSSI Deallocation
+ */
+class DoDeAllocateAccessNSSI extends AbstractServiceTaskProcessor {
+
+ String Prefix="DoDeAllocateAccessNSSI"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ OofUtils oofUtils = new OofUtils()
+ ObjectMapper objectMapper = new ObjectMapper()
+ private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
+
+ private static final Logger logger = LoggerFactory.getLogger(DoDeAllocateAccessNSSI.class)
+ private static final String ROLE_SLICE_PROFILE = "slice-profile-instance"
+ private static final String ROLE_NSSI = "nssi"
+
+ private static final String AN_NF = "AN-NF"
+ private static final String TN_FH = "TN-FH"
+ private static final String TN_MH = "TN-MH"
+
+ @Override
+ public void preProcessRequest(DelegateExecution execution) {
+ logger.debug("${Prefix} - Start preProcessRequest")
+
+ String sliceParams = execution.getVariable("sliceParams")
+ String sNssaiList = jsonUtil.getJsonValue(sliceParams, "snssaiList")
+ String anSliceProfileId = jsonUtil.getJsonValue(sliceParams, "sliceProfileId")
+ String nsiId = jsonUtil.getJsonValue(sliceParams, "nsiId")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ String anNssiId = execution.getVariable("serviceInstanceID")
+
+ if(isBlank(sNssaiList) || isBlank(anSliceProfileId) || isBlank(nsiId)) {
+ String msg = "Input fields cannot be null : Mandatory attributes : [snssaiList, sliceProfileId, nsiId]"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ if( isBlank(anNssiId) || isBlank(globalSubscriberId) || isBlank(subscriptionServiceType)) {
+ String msg = "Missing Input fields from main process : [serviceInstanceID, globalSubscriberId, subscriptionServiceType]"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ execution.setVariable("sNssaiList", sNssaiList)
+ execution.setVariable("anSliceProfileId", anSliceProfileId)
+ execution.setVariable("nsiId", nsiId)
+ execution.setVariable("anNssiId", anNssiId)
+
+ logger.debug("${Prefix} - Preprocessing completed with sliceProfileId : ${anSliceProfileId} , nsiId : ${nsiId} , nssiId : ${anNssiId}")
+ }
+
+ /**
+ * Method to fetch AN NSSI Constituents and Slice Profile constituents
+ * @param execution
+ */
+ void getRelatedInstances(DelegateExecution execution) {
+ logger.debug("${Prefix} - Get Related Instances")
+ String anSliceProfileId = execution.getVariable("anSliceProfileId")
+ String anNssiId = execution.getVariable("anNssiId")
+
+ Map<String,ServiceInstance> relatedSPs = new HashMap<>()
+ execution.setVariable("relatedSPs", getRelatedInstancesByRole(execution, ROLE_SLICE_PROFILE, anSliceProfileId))
+ execution.setVariable("anNfSliceProfileId", getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), AN_NF))
+
+ Map<String,ServiceInstance> relatedNssis = new HashMap<>()
+ execution.setVariable("relatedNssis", getRelatedInstancesByRole(execution, ROLE_NSSI, anNssiId))
+ }
+
+
+ /**
+ * @param execution
+ */
+ void prepareOOFAnNssiTerminationRequest(DelegateExecution execution) {
+ logger.debug("Start prepareOOFTerminationRequest")
+ String requestId = execution.getVariable("msoRequestId")
+ String messageType = "AN_NSSITermination"
+ String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
+ String serviceInstanceId = execution.getVariable("nsiId")
+ String anNssiId = execution.getVariable("anNssiId")
+ String oofRequest = oofUtils.buildTerminateNxiRequest(requestId,anNssiId, ROLE_NSSI,messageType,serviceInstanceId)
+ OofRequest oofPayload = new OofRequest()
+ oofPayload.setApiPath("/api/oof/terminate/nxi/v1")
+ oofPayload.setRequestDetails(oofRequest)
+ execution.setVariable("oofAnNssiPayload", oofPayload)
+ logger.debug("Finish prepareOOFTerminationRequest")
+
+ }
+
+ void performOofAnNSSITerminationCall(DelegateExecution execution) {
+ boolean terminateAnNSSI = callOofAdapter(execution,execution.getVariable("oofAnNssiPayload"))
+ execution.setVariable("terminateAnNSSI", terminateAnNSSI)
+ }
+
+ /**
+ * @param execution
+ */
+ void prepareOOFAnNfNssiTerminationRequest(DelegateExecution execution) {
+ logger.debug("Start prepareOOFAnNfNssiTerminationRequest")
+ String requestId = execution.getVariable("msoRequestId")
+ String messageType = "AN_NF_NSSITermination"
+ String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
+ String serviceInstanceId = execution.getVariable("anNssiId")
+
+ String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"),AN_NF)
+ execution.setVariable("anNfNssiId", anNfNssiId)
+
+ String oofRequest = oofUtils.buildTerminateNxiRequest(requestId,anNfNssiId, ROLE_NSSI,messageType,serviceInstanceId)
+ OofRequest oofPayload = new OofRequest()
+ oofPayload.setApiPath("/api/oof/terminate/nxi/v1")
+ oofPayload.setRequestDetails(oofRequest)
+ execution.setVariable("oofAnNfNssiPayload", oofPayload)
+ logger.debug("Finish prepareOOFAnNfNssiTerminationRequest")
+
+ }
+
+ void performOofAnNfNSSITerminationCall(DelegateExecution execution) {
+ boolean terminateAnNfNSSI = callOofAdapter(execution,execution.getVariable("oofAnNfNssiPayload"))
+ execution.setVariable("terminateAnNfNSSI", terminateAnNfNSSI)
+ if(!terminateAnNfNSSI) {
+ execution.setVariable("modifyAction",true)
+ }
+ }
+
+ void prepareSdnrRequest(DelegateExecution execution) {
+
+ String anNfNssiId = execution.getVariable("anNfNssiId")
+ String sNssai = execution.getVariable("sNssaiList")
+ String reqId = execution.getVariable("msoRequestId")
+ String messageType = "SDNRTerminateResponse"
+ StringBuilder callbackURL = new StringBuilder(UrnPropertiesReader.getVariable("mso.workflow.message.endpoint", execution))
+ callbackURL.append("/").append(messageType).append("/").append(reqId)
+
+ JsonObject input = new JsonObject()
+ input.addProperty("RANNFNSSIId", anNfNssiId)
+ input.addProperty("callbackURL", callbackURL.toString())
+ input.addProperty("s-NSSAI", sNssai)
+
+ JsonObject Payload = new JsonObject()
+ Payload.addProperty("version", "1.0")
+ Payload.addProperty("rpc-name", "TerminateRANSlice")
+ Payload.addProperty("correlation-id", reqId)
+ Payload.addProperty("type", "request")
+
+ JsonObject wrapinput = new JsonObject()
+ wrapinput.addProperty("Action", "deallocate")
+
+ JsonObject CommonHeader = new JsonObject()
+ CommonHeader.addProperty("TimeStamp", new Date(System.currentTimeMillis()).format("yyyy-MM-ddTHH:mm:ss.sss", TimeZone.getDefault()))
+ CommonHeader.addProperty("APIver", "1.0")
+ CommonHeader.addProperty("RequestID", reqId)
+ CommonHeader.addProperty("SubRequestID", "1")
+
+ JsonObject body = new JsonObject()
+ body.add("input", wrapinput)
+
+ JsonObject sdnrRequest = new JsonObject()
+ Payload.add("input", input)
+ wrapinput.add("Payload", Payload)
+ wrapinput.add("CommonHeader", CommonHeader)
+ body.add("input", wrapinput)
+ sdnrRequest.add("body", body)
+
+ String json = sdnrRequest.toString()
+ execution.setVariable("sdnrRequest", sdnrRequest)
+ execution.setVariable("SDNR_messageType", messageType)
+ execution.setVariable("SDNR_timeout", "PT10M")
+
+ }
+
+ void processSdnrResponse(DelegateExecution execution) {
+ logger.debug("${Prefix} processing SdnrResponse")
+ Map<String, Object> resMap = objectMapper.readValue(execution.getVariable("SDNR_Response"),Map.class)
+ String status = resMap.get("status")
+ String reason = resMap.get("reason")
+ if("success".equalsIgnoreCase(status)) {
+ execution.setVariable("isAnNfTerminated", true)
+ }else {
+ execution.setVariable("isAnNfTerminated", false)
+ logger.debug("AN NF Termination failed with reason ${reason}")
+ }
+ logger.debug("${Prefix} processed SdnrResponse")
+ }
+
+ /**
+ * @param execution
+ * @param oofRequest - Request payload to be sent to adapter
+ * @return
+ */
+ boolean callOofAdapter(DelegateExecution execution, OofRequest oofRequest) {
+ logger.debug("Start callOofAdapter")
+ String requestId = execution.getVariable("msoRequestId")
+ String oofAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.oof.endpoint", execution)
+ URL requestUrl = new URL(oofAdapterEndpoint)
+ logger.debug("Calling OOF adapter : ${requestUrl} with payload : ${oofRequest}")
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(requestUrl, ONAPComponents.EXTERNAL)
+ Response httpResponse = httpClient.post(oofRequest)
+ int responseCode = httpResponse.getStatus()
+ logger.debug("OOF sync response code is: " + responseCode)
+ if(responseCode != 200){
+ logger.debug("OOF request failed with reason : " + httpResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
+ }else {
+ Map<String,Object> response = objectMapper.readValue(httpResponse.getEntity(),Map.class)
+ boolean terminateResponse = response.get("terminateResponse")
+ if(!terminateResponse) {
+ logger.debug("Terminate response is false because " + response.get("reason"))
+ }
+ return terminateResponse
+ }
+ }
+
+ void deallocateAnNfNssi(DelegateExecution execution) {
+ logger.debug("${Prefix} - call deallocateAnNfNssi ")
+ String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, anNfNssiId)
+ if (!client.exists(uri)) {
+ logger.debug("AN NF Service Instance was not found in aai : ${anNfNssiId}")
+ }else {
+ client.delete(uri)
+ }
+ }
+
+ /**
+ * Removes relationship between AN NSSI and AN_NF NSSI
+ * @param execution
+ */
+ void dissociateAnNfNssi(DelegateExecution execution) {
+ logger.debug("${Prefix} - call dissociateAnNfNssi ")
+ String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, anNfNssiId)
+ if (!client.exists(uri)) {
+ logger.debug("AN NF Service Instance was not found in aai : ${anNfNssiId}")
+ }else {
+ client.delete(uri)
+ }
+ }
+
+ /**
+ * Method to prepare request for AN NSSI modification
+ * Call Modify AN NSSI in case OOF sends Terminate NSSI=False
+ * @param execution
+ */
+ void preparejobForANNSSIModification(DelegateExecution execution) {
+
+ String modificationJobId = UUID.randomUUID().toString()
+ execution.setVariable("modificationJobId", modificationJobId)
+
+ Map<String,Object> sliceParams = objectMapper.readValue(execution.getVariable("sliceParams"), Map.class)
+ sliceParams.put("modifyAction", "deallocate")
+ execution.setVariable("modificationsliceParams", sliceParams)
+
+ String serviceId = execution.getVariable("serviceInstanceId")
+ String nsiId = execution.getVariable("nsiId")
+ logger.debug("Generated new job for Service Instance serviceId:" + serviceId + " operationId:" + modificationJobId)
+
+ ResourceOperationStatus initStatus = new ResourceOperationStatus()
+ initStatus.setServiceId(serviceId)
+ initStatus.setOperationId(modificationJobId)
+ initStatus.setResourceTemplateUUID(nsiId)
+ initStatus.setOperType("Modify-Deallocate")
+ requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
+
+ logger.debug(Prefix + "prepareInitOperationStatus Exit")
+ }
+
+ void prepareQueryJobStatus(DelegateExecution execution,String jobId,String networkType,String instanceId) {
+
+ String responseId = "1"
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType(networkType)
+ esrInfo.setVendor("ONAP")
+
+ ServiceInfo serviceInfo = new ServiceInfo()
+ serviceInfo.setNssiId(instanceId)
+ serviceInfo.setNsiId(execution.getVariable("nsiId"))
+ serviceInfo.setGlobalSubscriberId(globalSubscriberId)
+ serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
+
+ execution.setVariable("${networkType}_esrInfo", esrInfo)
+ execution.setVariable("${networkType}_responseId", responseId)
+ execution.setVariable("${networkType}_serviceInfo", serviceInfo)
+
+ }
+
+ void validateJobStatus(DelegateExecution execution,String responseDescriptor) {
+ logger.debug("validateJobStatus ${responseDescriptor}")
+ String status = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.status")
+ String statusDescription = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.statusDescription")
+ if("finished".equalsIgnoreCase(status)) {
+ execution.setVariable("isSuccess", true)
+ }else {
+ execution.setVariable("isSuccess", false)
+ }
+ }
+
+ void prepareUpdateJobStatus(DelegateExecution execution,String status,String progress,String statusDescription) {
+ String serviceId = execution.getVariable("anNssiId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+
+ ResourceOperationStatus roStatus = new ResourceOperationStatus()
+ roStatus.setServiceId(serviceId)
+ roStatus.setOperationId(jobId)
+ roStatus.setResourceTemplateUUID(nsiId)
+ roStatus.setOperType("DeAllocate")
+ roStatus.setProgress(progress)
+ roStatus.setStatus(status)
+ roStatus.setStatusDescription(statusDescription)
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, status)
+ }
+
+ void terminateTNFHNssi(DelegateExecution execution) {
+ logger.debug("Start terminateTNFHNssi in ${Prefix}")
+ String nssmfRequest = buildDeallocateNssiRequest(execution, TN_FH)
+ String nssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_FH)
+ execution.setVariable("tnFHNSSIId", nssiId)
+ String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+ if (nssmfResponse != null) {
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TN_FH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ logger.debug("Exit terminateTNFHNssi in ${Prefix}")
+ }
+
+ void terminateTNMHNssi(DelegateExecution execution) {
+ logger.debug("Start terminateTNMHNssi in ${Prefix}")
+ String nssmfRequest = buildDeallocateNssiRequest(execution, TN_MH)
+ String nssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_MH)
+ execution.setVariable("tnMHNSSIId", nssiId)
+ String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+ if (nssmfResponse != null) {
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TN_MH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ logger.debug("Exit terminateTNMHNssi in ${Prefix}")
+ }
+
+ void deleteRanNfSliceProfileInAAI(DelegateExecution execution) {
+ logger.debug("${Prefix} delete Ran NF SliceProfile In AAI")
+ String spId = execution.getVariable("anNfSliceProfileId")
+ deleteServiceInstanceInAAI(execution, spId)
+ }
+
+ void deleteTNSliceProfileInAAI(DelegateExecution execution) {
+ logger.debug("${Prefix} delete TN FH SliceProfile In AAI")
+ String fhSP = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_FH)
+ deleteServiceInstanceInAAI(execution, fhSP)
+ logger.debug("${Prefix} delete TN MH SliceProfile In AAI")
+ String mhSP = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_MH)
+ deleteServiceInstanceInAAI(execution, mhSP)
+ }
+
+ void deleteANNSSI(DelegateExecution execution) {
+ logger.debug("${Prefix} delete AN NSSI")
+ String nssiId = execution.getVariable("serviceInstanceID")
+ deleteServiceInstanceInAAI(execution, nssiId)
+ }
+
+ /**
+ * Fetches a collection of service instances with the specific role and maps it based on workload context
+ * (AN-NF,TN-FH,TN-MH)
+ * @param execution
+ * @param role - nssi/slice profile instance
+ * @param instanceId - id to which the related list to be found
+ * @return
+ */
+ private Map<String,ServiceInstance> getRelatedInstancesByRole(DelegateExecution execution,String role,String instanceId) {
+ logger.debug("${Prefix} - Fetching related ${role} from AAI")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ if( isBlank(role) || isBlank(instanceId)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Role and instanceId are mandatory")
+ }
+
+ Map<String,ServiceInstance> relatedInstances = new HashMap<>()
+
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, instanceId)
+ if (!client.exists(uri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
+ }
+ AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
+ Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
+ if(si.isPresent()) {
+ List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo.toLowerCase() == "service-instance") {
+ String relatioshipurl = relationship.getRelatedLink()
+ String serviceInstanceId =
+ relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
+ uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, serviceInstanceId)
+ if (!client.exists(uri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
+ "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
+ }
+ AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
+ Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
+ if (serviceInstance.isPresent()) {
+ ServiceInstance instance = serviceInstance.get()
+ if (role.equalsIgnoreCase(instance.getServiceRole())) {
+ relatedInstances.put(instance.getWorkloadContext(),instance)
+ }
+ }
+ }
+ }
+ }
+ logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
+ return relatedInstances
+ }
+
+ private String getInstanceIdByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
+ String instanceId = instances.get(workloadContext).getServiceInstanceId()
+ if(instanceId == null) {
+ throw new BpmnError( 2500, "${workloadContext} NSSI ID is not found.")
+ }
+ return instanceId
+ }
+
+ /**
+ * Method to handle deallocation of RAN NSSI constituents(TN_FH/TN_MH)
+ * @param execution
+ * @param serviceFunction - TN_FH/TN_MH
+ * @return
+ */
+ private String buildDeallocateNssiRequest(DelegateExecution execution,String serviceFunction) {
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ Map<String, ServiceInstance> relatedNssis = execution.getVariable("relatedNssis")
+
+ String anNssiId = execution.getVariable("anNssiId")
+ List<String> sNssaiList = execution.getVariable("sNssaiList")
+
+ Map<String, ServiceInstance> relatedSPs = execution.getVariable("relatedSPs")
+
+ DeAllocateNssi deallocateNssi = new DeAllocateNssi()
+ deallocateNssi.setNsiId(anNssiId)
+ ServiceInstance tnNssi = relatedNssis.get(serviceFunction)
+ String nssiId = tnNssi.getServiceInstanceId()
+
+ deallocateNssi.setNssiId(nssiId)
+ deallocateNssi.setScriptName(tnNssi.getServiceInstanceName())
+ deallocateNssi.setSnssaiList(sNssaiList)
+ deallocateNssi.setSliceProfileId(relatedSPs.get(serviceFunction).getServiceInstanceId())
+
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setVendor("ONAP")
+ esrInfo.setNetworkType("TN")
+
+ ServiceInfo serviceInfo = new ServiceInfo()
+ serviceInfo.setServiceInvariantUuid(tnNssi.getModelInvariantId())
+ serviceInfo.setServiceUuid(tnNssi.getModelVersionId())
+ serviceInfo.setGlobalSubscriberId(globalSubscriberId)
+ serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
+
+ JsonObject json = new JsonObject()
+ json.addProperty("deAllocateNssi", objectMapper.writeValueAsString(deallocateNssi))
+ json.addProperty("esrInfo", objectMapper.writeValueAsString(esrInfo))
+ json.addProperty("serviceInfo", objectMapper.writeValueAsString(serviceInfo))
+ return json.toString()
+
+ }
+
+ private void deleteServiceInstanceInAAI(DelegateExecution execution,String instanceId) {
+ try {
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), instanceId)
+ getAAIClient().delete(serviceInstanceUri)
+ logger.debug("${Prefix} Exited deleteServiceInstance")
+ }catch(Exception e){
+ logger.debug("Error occured within deleteServiceInstance method: " + e)
+ }
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateCoreNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateCoreNSSI.groovy
new file mode 100644
index 0000000000..49aeec8ee3
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateCoreNSSI.groovy
@@ -0,0 +1,1298 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 TIM
+ * ================================================================================
+ * 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.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.CloudRegion
+import org.onap.aai.domain.yang.Customer
+import org.onap.aai.domain.yang.ModelVer
+import org.onap.aai.domain.yang.OwningEntities
+import org.onap.aai.domain.yang.ServiceSubscription
+import org.onap.aai.domain.yang.SliceProfile
+import org.onap.aai.domain.yang.GenericVnf
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aai.domain.yang.Tenant
+import org.onap.aai.domain.yang.VfModule
+import org.onap.aaiclient.client.aai.AAIClient
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.Relationships
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.MsoUtils
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.db.request.beans.OperationStatus
+import org.onap.so.requestsdb.RequestsDbConstant
+import org.onap.so.serviceinstancebeans.CloudConfiguration
+import org.onap.so.serviceinstancebeans.LineOfBusiness
+import org.onap.so.serviceinstancebeans.ModelInfo
+import org.onap.so.serviceinstancebeans.ModelType
+import org.onap.so.serviceinstancebeans.OwningEntity
+import org.onap.so.serviceinstancebeans.Project
+import org.onap.so.serviceinstancebeans.RequestDetails
+import org.onap.so.serviceinstancebeans.RequestInfo
+import org.onap.so.serviceinstancebeans.RequestParameters
+import org.onap.so.serviceinstancebeans.Resources
+import org.onap.so.serviceinstancebeans.Service
+import org.onap.so.serviceinstancebeans.SubscriberInfo
+import org.onap.so.serviceinstancebeans.VfModules
+import org.onap.so.serviceinstancebeans.Vnfs
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import javax.ws.rs.core.Response
+
+class DoDeallocateCoreNSSI extends AbstractServiceTaskProcessor {
+ private final String PREFIX ="DoDeallocateCoreNSSI"
+
+ private ExceptionUtil exceptionUtil = new ExceptionUtil()
+ private RequestDBUtil requestDBUtil = new RequestDBUtil()
+ private MsoUtils utils = new MsoUtils()
+ private JsonUtils jsonUtil = new JsonUtils()
+
+ private static final Logger LOGGER = LoggerFactory.getLogger( DoDeallocateCoreNSSI.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start preProcessRequest")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+ if (!currentNSSI) {
+ String msg = "currentNSSI is null"
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ LOGGER.trace("***** ${PREFIX} Exit preProcessRequest")
+ }
+
+
+ /**
+ * Queries OOF for NSSI termination
+ * @param execution
+ */
+ void executeTerminateNSSIQuery(DelegateExecution execution) {
+ // TO DO: Unit test
+ LOGGER.trace("${PREFIX} Start executeTerminateNSSIQuery")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
+
+ //Prepare auth for OOF
+ def authHeader = ""
+ String basicAuth = UrnPropertiesReader.getVariable("mso.oof.auth", execution)
+ String msokey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
+
+ String basicAuthValue = encryptBasicAuth(basicAuth, msokey)
+ if (basicAuthValue != null) {
+ String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msokey)
+ String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
+ if(errorCode == null || errorCode.isEmpty()) { // No error
+ authHeader = responseAuthHeader
+ }
+ else {
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
+ }
+ } else {
+ LOGGER.error( "Unable to obtain BasicAuth - BasicAuth value null")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
+ "value null")
+ }
+
+ //Prepare send request to OOF
+ String oofRequest = buildOOFRequest(execution)
+
+ String callOOFResponse = callOOF(urlString, authHeader, oofRequest)
+ String errorCode = jsonUtil.getJsonValue(callOOFResponse, "errorCode")
+ if(errorCode == null || errorCode.isEmpty()) { // No error
+ String oofResponse = callOOFResponse
+ String isTerminateNSSI = jsonUtil.getJsonValue(oofResponse, "terminateResponse")
+
+ execution.setVariable("isTerminateNSSI", Boolean.parseBoolean(isTerminateNSSI))
+ }
+ else {
+ LOGGER.error(jsonUtil.getJsonValue(callOOFResponse, "errorMessage"))
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callOOFResponse, "errorMessage"))
+ }
+
+
+ LOGGER.trace("${PREFIX} Exit executeTerminateNSSIQuery")
+ }
+
+
+ /**
+ * Executes sync call to OOF
+ * @return OOF response
+ */
+ String callOOF(String urlString, String authHeader, String oofRequest) {
+ String errorCode = ""
+ String errorMessage = ""
+ String response = ""
+
+ try {
+ URL url = new URL(urlString + "/api/oof/terminate/nxi/v1")
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.OOF)
+ httpClient.addAdditionalHeader("Authorization", authHeader)
+ httpClient.addAdditionalHeader("Accept", "application/json")
+ httpClient.addAdditionalHeader("Content-Type", "application/json")
+
+ Response httpResponse = httpClient.post(oofRequest)
+
+ int responseCode = httpResponse.getStatus()
+ LOGGER.debug("OOF sync response code is: " + responseCode)
+
+ if (responseCode != 202) { // Accepted
+ errorCode = responseCode
+ errorMessage = "Received a Bad Sync Response from OOF."
+
+ response = "{\n" +
+ " \"errorCode\": \"${errorCode}\",\n" +
+ " \"errorMessage\": \"${errorMessage}\"\n" +
+ "}"
+ //exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
+ }
+
+ if (httpResponse.hasEntity()) {
+ response = httpResponse.readEntity(String.class)
+ }
+ else {
+ errorCode = 500
+ errorMessage = "No response received from OOF."
+
+ response = "{\n" +
+ " \"errorCode\": \"${errorCode}\",\n" +
+ " \"errorMessage\": \"${errorMessage}\"\n" +
+ "}"
+ }
+ }
+ catch(Exception e) {
+ errorCode = 400
+ errorMessage = e.getMessage()
+
+ response = "{\n" +
+ " \"errorCode\": \"${errorCode}\",\n" +
+ " \"errorMessage\": \"${errorMessage}\"\n" +
+ "}"
+ }
+
+
+ return response
+ }
+
+
+ String encryptBasicAuth(String basicAuth, String msoKey) {
+ return utils.encrypt(basicAuth, msoKey)
+ }
+
+
+ String getAuthHeader(DelegateExecution execution, String basicAuthValue, String msokey) {
+ String response = ""
+ String errorCode = ""
+ String errorMessage = ""
+
+ LOGGER.debug("Obtained BasicAuth username and password for OOF: " + basicAuthValue)
+ try {
+ response = utils.getBasicAuth(basicAuthValue, msokey)
+ } catch (Exception ex) {
+ LOGGER.error("Unable to encode username and password string: ", ex)
+
+ errorCode = "401"
+ errorMessage = "Internal Error - Unable to encode username and password string"
+
+ response = "{\n" +
+ " \"errorCode\": \"${errorCode}\",\n" +
+ " \"errorMessage\": \"${errorMessage}\"\n" +
+ "}"
+ }
+
+ return response
+ }
+
+
+
+ /**
+ * Builds OOF request
+ * @param execution
+ * @return
+ */
+ private String buildOOFRequest(DelegateExecution execution) {
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String nssiId = currentNSSI['nssiId']
+ String requestId = execution.getVariable("mso-request-id")
+
+ String request = "{\n" +
+ " \"type\": \"NSSI\",\n" +
+ " \"NxIId\": \"${nssiId}\",\n" +
+ " \"requestInfo\": {\n" +
+ " \"transactionId\": \"${requestId}\",\n" +
+ " \"requestId\": \"${requestId}\",\n" +
+ " \"sourceId\": \"so\",\n" +
+ " }\n" +
+ "}"
+
+ return request
+ }
+
+
+
+ /**
+ * Queries Network Service Instance in AAI
+ * @param execution
+ */
+ void getNetworkServiceInstance(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start getNetworkServiceInstance")
+
+ AAIResourcesClient client = getAAIClient()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String globalSubscriberId = currentNSSI['globalSubscriberId']
+ String serviceType = currentNSSI['serviceType']
+ String nssiId = currentNSSI['nssiId']
+
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+ Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, nssiUri)
+
+ if (nssiOpt.isPresent()) {
+ ServiceInstance nssi = nssiOpt.get()
+ currentNSSI['nssi'] = nssi
+
+ ServiceInstance networkServiceInstance = handleNetworkInstance(execution, nssiId, nssiUri, client)
+ currentNSSI['networkServiceInstance'] = networkServiceInstance
+ }
+ else {
+ String msg = String.format("NSSI %s not found in AAI", nssiId)
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+
+ LOGGER.trace("${PREFIX} Exit getNetworkServiceInstance")
+ }
+
+
+ /**
+ * Handles Network Service
+ * @param nssiId
+ * @param nssiUri
+ * @param client
+ * @return Network Service Instance
+ */
+ private ServiceInstance handleNetworkInstance(DelegateExecution execution, String nssiId, AAIResourceUri nssiUri, AAIResourcesClient client ) {
+ ServiceInstance networkServiceInstance = null
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ AAIResultWrapper wrapper = client.get(nssiUri)
+ Optional<Relationships> relationships = wrapper.getRelationships()
+
+ if (relationships.isPresent()) {
+ for (AAIResourceUri networkServiceInstanceUri : relationships.get().getRelatedAAIUris(AAIObjectType.SERVICE_INSTANCE)) {
+ Optional<ServiceInstance> networkServiceInstanceOpt = client.get(ServiceInstance.class, networkServiceInstanceUri)
+ if (networkServiceInstanceOpt.isPresent()) {
+ networkServiceInstance = networkServiceInstanceOpt.get()
+
+ if (networkServiceInstance.getServiceRole().equals("Network Service")) { // Network Service role
+ currentNSSI['networkServiceInstanceUri'] = networkServiceInstanceUri
+ break
+ }
+ }
+ else {
+ String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+ }
+ }
+ else {
+ String msg = String.format("No relationship presented for NSSI %s in AAI", nssiId)
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+
+ if(networkServiceInstance == null) {
+ String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+
+ return networkServiceInstance
+ }
+
+
+ /**
+ * Invokes deleteServiceOrder external API
+ * @param execution
+ */
+ void deleteServiceOrder(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start deleteServiceOrder")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ try {
+ //url:/nbi/api/v4/serviceOrder/"
+ def nbiEndpointUrl = UrnPropertiesReader.getVariable("nbi.endpoint.url", execution)
+
+ ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
+
+ String url = String.format("${nbiEndpointUrl}/api/v4/serviceOrder/%s", networkServiceInstance.getServiceInstanceId()) // Service Order ID = Network Service Instance ID
+
+ String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
+ String basicAuth = UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
+
+ String basicAuthValue = encryptBasicAuth(basicAuth, msoKey)
+ def authHeader = ""
+ if (basicAuthValue != null) {
+ String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey)
+ String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
+ if(errorCode == null || errorCode.isEmpty()) { // No error
+ authHeader = responseAuthHeader
+ }
+ else {
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
+ }
+ } else {
+ LOGGER.error( "Unable to obtain BasicAuth - BasicAuth value null")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
+ "value null")
+ }
+
+ String callDeleteServiceOrderResponse = callDeleteServiceOrder(execution, url, authHeader)
+ String errorCode = jsonUtil.getJsonValue(callDeleteServiceOrderResponse, "errorCode")
+ String deleteServcieResponse = ""
+
+ if(errorCode == null || errorCode.isEmpty()) { // No error
+ deleteServcieResponse = callDeleteServiceOrderResponse // check the response ???
+ }
+ else {
+ LOGGER.error(jsonUtil.getJsonValue(callDeleteServiceOrderResponse, "errorMessage"))
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callDeleteServiceOrderResponse, "errorMessage"))
+ }
+ } catch (any) {
+ String msg = "Exception in DoDeallocateCoreNSSI.deleteServiceOrder. " + any.getCause()
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ LOGGER.trace("${PREFIX} Exit deleteServiceOrder")
+ }
+
+
+ String callDeleteServiceOrder(DelegateExecution execution, String urlString, String authHeader) {
+ String errorCode = ""
+ String errorMessage = ""
+ String response = ""
+
+ try {
+ HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(urlString), ONAPComponents.EXTERNAL)
+ httpClient.addAdditionalHeader("Authorization", authHeader)
+ httpClient.addAdditionalHeader("Accept", "application/json")
+ Response httpResponse = httpClient.delete()
+
+ if (httpResponse.hasEntity()) {
+ response = httpResponse.readEntity(String.class)
+ }
+ else {
+ errorCode = 500
+ errorMessage = "No response received."
+
+ response = "{\n" +
+ " \"errorCode\": \"${errorCode}\",\n" +
+ " \"errorMessage\": \"${errorMessage}\"\n" +
+ "}"
+ }
+ }
+ catch (any) {
+ String msg = "Exception in DoDeallocateCoreNSSI.deleteServiceOrder. " + any.getCause()
+
+ response = "{\n" +
+ " \"errorCode\": \"7000\",\n" +
+ " \"errorMessage\": \"${msg}\"\n" +
+ "}"
+ }
+
+ return response
+ }
+
+
+ /**
+ * Queries constitute VNF from Network Service Instance
+ * @param execution
+ */
+ void getConstituteVNFFromNetworkServiceInst(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start getConstituteVNFFromNetworkServiceInst")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ AAIResourcesClient client = getAAIClient()
+
+ AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
+ AAIResultWrapper wrapper = client.get(networkServiceInstanceUri);
+ Optional<Relationships> relationships = wrapper.getRelationships()
+ if (relationships.isPresent()) {
+ for (AAIResourceUri constituteVnfUri : relationships.get().getRelatedAAIUris(AAIObjectType.GENERIC_VNF)) {
+ currentNSSI['constituteVnfUri'] = constituteVnfUri
+ Optional<GenericVnf> constituteVnfOpt = client.get(GenericVnf.class, constituteVnfUri)
+ if(constituteVnfOpt.isPresent()) {
+ GenericVnf constituteVnf = constituteVnfOpt.get()
+ currentNSSI['constituteVnf'] = constituteVnf
+ }
+ else {
+ String msg = String.format("No constitute VNF found for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+
+ break // Should be only one constitute VNF
+ }
+ }
+ else {
+ String msg = String.format("No relationship presented for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+
+ LOGGER.trace("${PREFIX} Exit getConstituteVNFFromNetworkServiceInst")
+
+ }
+
+
+ /**
+ * Retrieves NSSI associated profiles from AAI
+ * @param execution
+ */
+ void getNSSIAssociatedProfiles(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start getNSSIAssociatedProfiles")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
+
+ List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
+
+ if(associatedProfiles.isEmpty()) {
+ String msg = String.format("No associated profiles found for NSSI %s in AAI", nssi.getServiceInstanceId())
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+ else {
+ currentNSSI['associatedProfiles'] = associatedProfiles
+ }
+
+ LOGGER.trace("${PREFIX} Exit getNSSIAssociatedProfiles")
+ }
+
+
+ /**
+ * Calculates a final list of S-NSSAI
+ * @param execution
+ */
+ void calculateSNSSAI(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start calculateSNSSAI")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ List<SliceProfile> associatedProfiles = (List<SliceProfile>)currentNSSI['associatedProfiles']
+
+ String currentSNSSAI = currentNSSI['S-NSSAI']
+
+ List<String> snssais = new ArrayList<>()
+
+ for(SliceProfile associatedProfile:associatedProfiles) {
+ if(!associatedProfile.getSNssai().equals(currentSNSSAI)) { // not current S-NSSAI
+ snssais.add(associatedProfile.getSNssai())
+ }
+ else {
+ currentNSSI['sliceProfileS-NSSAI'] = associatedProfile
+ }
+ }
+
+ currentNSSI['S-NSSAIs'] = snssais
+
+ LOGGER.trace("${PREFIX} Exit calculateSNSSAI")
+ }
+
+
+ /**
+ * Invoke PUT Service Instance API
+ * @param execution
+ */
+ void invokePUTServiceInstance(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start invokePUTServiceInstance")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ try {
+ //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}/vnfs/{vnfId}"
+ def nsmfЕndpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
+
+ ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
+
+ GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
+
+ String url = String.format("${nsmfЕndpoint}/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s", networkServiceInstance.getServiceInstanceId(), constituteVnf.getVnfId())
+
+ String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
+ String basicAuth = UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
+
+ def authHeader = ""
+ String basicAuthValue = encryptBasicAuth(basicAuth, msoKey) //utils.encrypt(basicAuth, msoKey)
+ String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey) //utils.getBasicAuth(basicAuthValue, msoKey)
+
+ String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
+ if(errorCode == null || errorCode.isEmpty()) { // No error
+ authHeader = responseAuthHeader
+ }
+ else {
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
+ }
+
+ def requestDetails = ""
+ String prepareRequestDetailsResponse = prepareRequestDetails(execution)
+ errorCode = jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorCode")
+ if(errorCode == null || errorCode.isEmpty()) { // No error
+ requestDetails = prepareRequestDetailsResponse
+ }
+ else {
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorMessage"))
+ }
+
+ String callPUTServiceInstanceResponse = callPUTServiceInstance(url, authHeader, requestDetails)
+ String putServiceInstanceResponse = ""
+
+ if(errorCode == null || errorCode.isEmpty()) { // No error
+ putServiceInstanceResponse = callPUTServiceInstanceResponse // check the response ???
+ }
+ else {
+ LOGGER.error(jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
+ }
+
+ } catch (any) {
+ String msg = "Exception in DoDeallocateCoreNSSI.invokePUTServiceInstance. " + any.getCause()
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ LOGGER.trace("${PREFIX} Exit invokePUTServiceInstance")
+ }
+
+
+ String callPUTServiceInstance(String url, String authHeader, String requestDetailsStr) {
+ String errorCode = ""
+ String errorMessage = ""
+ String response
+
+ try {
+ HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
+ httpClient.addAdditionalHeader("Authorization", authHeader)
+ httpClient.addAdditionalHeader("Accept", "application/json")
+
+ Response httpResponse = httpClient.put(requestDetailsStr) // check http code ???
+
+
+ if (httpResponse.hasEntity()) {
+ response = httpResponse.readEntity(String.class)
+ }
+ else {
+ errorCode = 500
+ errorMessage = "No response received."
+
+ response = "{\n" +
+ " \"errorCode\": \"${errorCode}\",\n" +
+ " \"errorMessage\": \"${errorMessage}\"\n" +
+ "}"
+ }
+ }
+ catch (any) {
+ String msg = "Exception in DoDeallocateCoreNSSI.invokePUTServiceInstance. " + any.getCause()
+ LOGGER.error(msg)
+
+ response = "{\n" +
+ " \"errorCode\": \"7000\",\n" +
+ " \"errorMessage\": \"${msg}\"\n" +
+ "}"
+
+ }
+
+ return response
+
+ }
+
+
+ /**
+ * Prepare model info
+ * @param execution
+ * @param requestDetails
+ * @return ModelInfo
+ */
+ ModelInfo prepareModelInfo(DelegateExecution execution) {
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+ ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
+
+ ModelInfo modelInfo = new ModelInfo()
+
+ modelInfo.setModelType(ModelType.service)
+ modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
+
+ AAIResourcesClient client = getAAIClient()
+
+ AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, networkServiceInstance.getModelInvariantId(), networkServiceInstance.getModelVersionId())
+ Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
+
+ if (modelVerOpt.isPresent()) {
+ modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
+ modelInfo.setModelName(modelVerOpt.get().getModelName())
+ modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
+ }
+
+ return modelInfo
+ }
+
+
+ /**
+ * Prepares subscriber info
+ * @param execution
+ * @return SubscriberInfo
+ */
+ SubscriberInfo prepareSubscriberInfo(DelegateExecution execution) {
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String globalSubscriberId = currentNSSI['globalSubscriberId']
+
+ String subscriberName = currentNSSI['subscriberName']
+
+ SubscriberInfo subscriberInfo = new SubscriberInfo()
+ subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
+ subscriberInfo.setSubscriberName(subscriberName)
+
+ /*
+ AAIResourcesClient client = getAAIClient()
+
+ Customer customer = null
+
+ AAIResourceUri networkServiceInstanceUri = currentNSSI['networkServiceInstanceUri']
+ AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
+ Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
+ if(serviceSubscriptionRelationshipsOps.isPresent()) {
+ List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.SERVICE_SUBSCRIPTION)
+ if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
+ AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
+ Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
+
+ if(serviceSubscriptionOpt.isPresent()) {
+ currentNSSI['serviceSubscription'] = serviceSubscriptionOpt.get()
+ }
+
+ wrapper = client.get(serviceSubscriptionUri)
+ Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
+ if(customerRelationshipsOps.isPresent()) {
+ List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CUSTOMER)
+ if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
+ Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
+ if(customerOpt.isPresent()) {
+ customer = customerOpt.get()
+ subscriberInfo.setSubscriberName(customer.getSubscriberName())
+ }
+ }
+ }
+ }
+
+ } */
+
+ return subscriberInfo
+ }
+
+
+ /**
+ * Prepares Request Info
+ * @param execution
+ * @return RequestInfo
+ */
+ RequestInfo prepareRequestInfo(DelegateExecution execution, ServiceInstance networkServiceInstance) {
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String serviceId = currentNSSI['serviceId']
+
+ RequestInfo requestInfo = new RequestInfo()
+
+ requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
+ requestInfo.setSource("VID")
+ requestInfo.setProductFamilyId(serviceId)
+ requestInfo.setRequestorId("NBI")
+
+ return requestInfo
+ }
+
+
+ /**
+ * Prepares Model Info
+ * @param networkServiceInstance
+ * @param modelInfo
+ * @return ModelInfo
+ */
+ ModelInfo prepareServiceModelInfo(ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
+
+ ModelInfo serviceModelInfo = new ModelInfo()
+ serviceModelInfo.setModelType(ModelType.service)
+ serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
+
+ serviceModelInfo.setModelVersionId(modelInfo.getModelVersionId())
+ serviceModelInfo.setModelName(modelInfo.getModelName())
+ serviceModelInfo.setModelVersion(modelInfo.getModelVersion())
+
+ return serviceModelInfo
+ }
+
+
+ /**
+ * Prepares Cloud configuration
+ * @param execution
+ * @return CloudConfiguration
+ */
+ CloudConfiguration prepareCloudConfiguration(DelegateExecution execution) {
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ CloudConfiguration cloudConfiguration = new CloudConfiguration()
+
+ AAIResourcesClient client = getAAIClient()
+
+ AAIResourceUri constituteVnfUri = currentNSSI['constituteVnfUri']
+ AAIResultWrapper wrapper = client.get(constituteVnfUri)
+ Optional<Relationships> cloudRegionRelationshipsOps = wrapper.getRelationships()
+
+ if(cloudRegionRelationshipsOps.isPresent()) {
+ List<AAIResourceUri> cloudRegionRelatedAAIUris = cloudRegionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CLOUD_REGION)
+ if (!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
+ AAIResourceUri cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
+ currentNSSI['cloudRegionRelatedAAIUri'] = cloudRegionRelatedAAIUri
+
+ Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
+ CloudRegion cloudRegion = null
+ if (cloudRegionrOpt.isPresent()) {
+ cloudRegion = cloudRegionrOpt.get()
+ cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
+ for (Tenant tenant : cloudRegion.getTenants().getTenant()) {
+ cloudConfiguration.setTenantId(tenant.getTenantId())
+ break // only one is required
+ }
+
+ cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
+ }
+ }
+ }
+
+ return cloudConfiguration
+ }
+
+
+ /**
+ * Prepares a list of VF Modules
+ * @param execution
+ * @param constituteVnf
+ * @return List<VfModules>
+ */
+ List<VfModules> prepareVfModules(DelegateExecution execution, GenericVnf constituteVnf) {
+
+ AAIResourcesClient client = getAAIClient()
+
+ List<VfModules> vfModuless = new ArrayList<>()
+ for (VfModule vfModule : constituteVnf.getVfModules().getVfModule()) {
+ VfModules vfmodules = new VfModules()
+
+ ModelInfo vfModuleModelInfo = new ModelInfo()
+ vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
+ vfModuleModelInfo.setModelCustomizationId(vfModule.getModelCustomizationId())
+
+ AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, vfModule.getModelInvariantId(), vfModule.getModelVersionId())
+
+ Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
+
+ if (vfModuleModelVerOpt.isPresent()) {
+ vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
+ vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
+ vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
+
+ // No model customization ID
+ }
+ vfmodules.setModelInfo(vfModuleModelInfo)
+
+ vfmodules.setInstanceName(vfModule.getVfModuleName()) // ???
+
+ vfModuless.add(vfmodules)
+ }
+
+ return vfModuless
+ }
+
+
+ /**
+ * prepares VNF Model Info
+ * @param execution
+ * @param constituteVnf
+ * @return ModelInfo
+ */
+ ModelInfo prepareVNFModelInfo(DelegateExecution execution, GenericVnf constituteVnf) {
+ ModelInfo vnfModelInfo = new ModelInfo()
+
+ AAIResourcesClient client = getAAIClient()
+
+ vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
+ vnfModelInfo.setModelCustomizationId(constituteVnf.getModelCustomizationId())
+ vnfModelInfo.setModelInstanceName(constituteVnf.getVnfName())
+
+ AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, constituteVnf.getModelInvariantId(), constituteVnf.getModelVersionId())
+
+ Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
+
+ if (vnfModelVerOpt.isPresent()) {
+ vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
+ vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
+ vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
+
+ // No model instance name
+ }
+
+ return vnfModelInfo
+ }
+
+
+ List<Map<String, Object>> prepareInstanceParams(DelegateExecution execution) {
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ List<Map<String, Object>> instanceParams = new ArrayList<>()
+ Map<String, Object> instanceParamsMap = new HashMap<>()
+
+ // Supported S-NSSAI
+ List<String> snssais = (List<String>) currentNSSI['S-NSSAIs']
+
+ ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
+
+ String orchStatus = nssi.getOrchestrationStatus()
+
+
+ List<Map<String, String>> snssaiList = new ArrayList<>()
+
+ for(String snssai:snssais) {
+ Map<String, String> snssaisMap = new HashMap<>()
+ snssaisMap.put("snssai", snssai)
+ snssaisMap.put("status", orchStatus)
+ snssaiList.add(snssaisMap)
+ }
+
+ // Map<String, List<Map<String, String>>> supportedNssaiDetails = new HashMap<>()
+ // supportedNssaiDetails.put("sNssai", supportedNssaiDetails)
+
+ ObjectMapper mapper = new ObjectMapper()
+
+ String supportedNssaiDetailsStr = mapper.writeValueAsString(snssaiList)
+
+
+ instanceParamsMap.put("k8s-rb-profile-name", "default") // ???
+ instanceParamsMap.put("config-type", "day2") // ???
+ instanceParamsMap.put("supportedNssai", supportedNssaiDetailsStr)
+ instanceParams.add(instanceParamsMap)
+
+ // No other instance params, e.g. config-type
+
+ return instanceParams
+ }
+
+ /**
+ * Prepares Resources
+ * @param execution
+ * @return Resources
+ */
+ Resources prepareResources(DelegateExecution execution) {
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ Resources resources = new Resources()
+
+ // VNFs
+ List<Vnfs> vnfs = new ArrayList<>()
+ // VNF
+ Vnfs vnf = new Vnfs()
+
+ // Line of Business
+ LineOfBusiness lob = new LineOfBusiness()
+ lob.setLineOfBusinessName("VNF")
+ vnf.setLineOfBusiness(lob)
+
+ // Product family ID
+ GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
+ vnf.setProductFamilyId(constituteVnf.getServiceId())
+
+ // Cloud configuration
+ vnf.setCloudConfiguration(prepareCloudConfiguration(execution))
+
+ // VF Modules
+ vnf.setVfModules(prepareVfModules(execution, constituteVnf))
+
+ // Model Info
+ vnf.setModelInfo(prepareVNFModelInfo(execution, constituteVnf))
+
+ // Instance name
+ vnf.setInstanceName(constituteVnf.getVnfName())
+
+ // Instance params
+ vnf.setInstanceParams(prepareInstanceParams(execution))
+
+ // No platform data
+
+ vnfs.add(vnf)
+ resources.setVnfs(vnfs)
+
+ return resources
+ }
+
+
+ /**
+ * Prepare Service
+ * @return Service
+ */
+ Service prepareService(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
+ Service service = new Service()
+
+ // Model Info
+ service.setModelInfo(prepareServiceModelInfo(networkServiceInstance, modelInfo))
+
+ service.setInstanceName(networkServiceInstance.getServiceInstanceName())
+
+ // Resources
+ service.setResources(prepareResources(execution))
+
+ return service
+
+ }
+
+
+ /**
+ * Prepares request parameters
+ * @param execution
+ * @return RequestParameters
+ */
+ RequestParameters prepareRequestParameters(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ RequestParameters requestParameters = new RequestParameters()
+
+ ServiceSubscription serviceSubscription = (ServiceSubscription)currentNSSI['serviceSubscription']
+
+ if(serviceSubscription != null) {
+ requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
+ }
+
+ // User params
+ List<Map<String, Object>> userParams = new ArrayList<>()
+
+ Map<String, Object> userParam = new HashMap<>()
+ userParam.put("Homing_Solution", "none")
+ userParams.add(userParam)
+
+ // Service
+ Map<String, Object> serviceMap = new HashMap<>()
+ serviceMap.put("service", prepareService(execution, networkServiceInstance, modelInfo))
+ userParams.add(serviceMap)
+ requestParameters.setUserParams(userParams)
+
+ // No other user params
+
+ return requestParameters
+ }
+
+
+ /**
+ * Prepare Owning Entity
+ * @param execution
+ * @return OwningEntity
+ */
+ OwningEntity prepareOwningEntity(DelegateExecution execution) {
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ AAIResourcesClient client = getAAIClient()
+
+ AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
+
+ OwningEntity owningEntity = new OwningEntity()
+ AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
+ Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
+ if (owningEntityRelationshipsOps.isPresent()) {
+ List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.OWNING_ENTITY)
+
+ if (!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
+ Optional<org.onap.aai.domain.yang.OwningEntity> owningEntityOpt = client.get(org.onap.aai.domain.yang.OwningEntity.class, owningEntityRelatedAAIUris.get(0)) // Many-To-One relation
+ if (owningEntityOpt.isPresent()) {
+ owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
+ owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
+
+ }
+ }
+ }
+
+ return owningEntity
+ }
+
+
+ /**
+ * Prepares Project
+ * @param execution
+ * @return Project
+ */
+ Project prepareProject(DelegateExecution execution) {
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ AAIResourcesClient client = getAAIClient()
+
+ Project project = new Project()
+
+ AAIResourceUri cloudRegionRelatedAAIUri = (AAIResourceUri)currentNSSI['cloudRegionRelatedAAIUri']
+
+ if (cloudRegionRelatedAAIUri != null) {
+ AAIResultWrapper wrapper = client.get(cloudRegionRelatedAAIUri)
+ Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
+ if (cloudRegionOps.isPresent()) {
+ List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedAAIUris(AAIObjectType.PROJECT)
+ if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
+ Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.Project.class, projectAAIUris.get(0))
+ if (projectOpt.isPresent()) {
+ project.setProjectName(projectOpt.get().getProjectName())
+ }
+ }
+ }
+ }
+
+ return project
+ }
+
+
+ /**
+ * Prepares RequestDetails object
+ * @param execution
+ * @return
+ */
+ String prepareRequestDetails(DelegateExecution execution) {
+ String errorCode = ""
+ String errorMessage = ""
+ String response
+
+ RequestDetails requestDetails = new RequestDetails()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
+
+ try {
+ // Model Info
+ ModelInfo modelInfo = prepareModelInfo(execution)
+ requestDetails.setModelInfo(modelInfo)
+
+ // Subscriber Info
+ requestDetails.setSubscriberInfo(prepareSubscriberInfo(execution))
+
+ // Request Info
+ requestDetails.setRequestInfo(prepareRequestInfo(execution, networkServiceInstance))
+
+ // Request Parameters
+ requestDetails.setRequestParameters(prepareRequestParameters(execution, networkServiceInstance, modelInfo))
+
+ // Cloud configuration
+ requestDetails.setCloudConfiguration(prepareCloudConfiguration(execution))
+
+ // Owning entity
+ requestDetails.setOwningEntity(prepareOwningEntity(execution))
+
+ // Project
+ requestDetails.setProject(prepareProject(execution))
+
+ ObjectMapper mapper = new ObjectMapper()
+
+ response = mapper.writeValueAsString(requestDetails)
+ }
+ catch (any) {
+ String msg = "Exception in DoDeallocateCoreNSSI.prepareRequestDetails. " + any.getCause()
+ LOGGER.error(msg)
+
+ response = "{\n" +
+ " \"errorCode\": \"7000\",\n" +
+ " \"errorMessage\": \"${msg}\"\n" +
+ "}"
+
+ }
+
+ return response
+ }
+
+
+ /**
+ * Removes NSSI association with NSI
+ * @param execution
+ */
+ void removeNSSIAssociationWithNSI(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start removeNSSIAssociationWithNSI")
+
+ AAIResourcesClient client = getAAIClient()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String nssiId = currentNSSI['nssiId']
+ String nsiId = currentNSSI['nsiId']
+
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+ AAIResourceUri nsiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nsiId)
+
+ try {
+ client.disconnect(nssiUri, nsiUri)
+ }catch(Exception e){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while NSSI association with NSI disconnect call: " + e.getMessage())
+ }
+
+ LOGGER.trace("${PREFIX} Exit removeNSSIAssociationWithNSI")
+ }
+
+
+ /**
+ * Removes Slice Profile association with NSSI
+ * @param execution
+ */
+ void removeSPAssociationWithNSSI(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start removeSPAssociationWithNSSI")
+
+ AAIResourcesClient client = getAAIClient()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
+
+ String nssiId = currentNSSI['nssiId']
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+
+ List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
+
+ String currentSNSSAI = currentNSSI['S-NSSAI']
+
+ associatedProfiles.removeIf({ associatedProfile -> (associatedProfile.getSNssai().equals(currentSNSSAI)) })
+
+ try {
+ getAAIClient().update(nssiUri, nssi)
+ }catch(Exception e){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI update call: " + e.getMessage())
+ }
+
+ LOGGER.trace("${PREFIX} Exit removeSPAssociationWithNSSI")
+ }
+
+
+ /**
+ * Deletes Slice Profile Instance
+ * @param execution
+ */
+ void deleteSliceProfileInstance(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start deleteSliceProfileInstance")
+
+ AAIResourcesClient client = getAAIClient()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ SliceProfile sliceProfileContainsSNSSAI = (SliceProfile)currentNSSI['sliceProfileS-NSSAI']
+
+ String globalSubscriberId = currentNSSI['globalSubscriberId']
+ String serviceType = currentNSSI['serviceType']
+ String nssiId = currentNSSI['nssiId']
+
+ // global-customer-id, service-type, service-instance-id, profile-id
+ AAIResourceUri sliceProfileUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, globalSubscriberId, serviceType, nssiId, sliceProfileContainsSNSSAI.getProfileId())
+
+ try {
+ getAAIClient().delete(sliceProfileUri)
+ }catch(Exception e){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
+ }
+
+ LOGGER.trace("${PREFIX} Exit deleteSliceProfileInstance")
+ }
+
+
+ /**
+ * Delets NSSI Service Instance
+ * @param execution
+ */
+ void deleteNSSIServiceInstance(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start deleteNSSIServiceInstance")
+
+ AAIResourcesClient client = getAAIClient()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String nssiId = currentNSSI['nssiId']
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+
+ try {
+ getAAIClient().delete(nssiUri)
+ }catch(Exception e){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while NSSI Service Instance delete call: " + e.getMessage())
+ }
+
+ LOGGER.trace("${PREFIX} Exit deleteNSSIServiceInstance")
+ }
+
+
+ /**
+ * Updates operation status
+ * @param execution
+ */
+ void updateServiceOperationStatus(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start updateServiceOperationStatus")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ OperationStatus operationStatus = new OperationStatus()
+ operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
+ operationStatus.setOperationId(currentNSSI['operationId'] as String)
+ operationStatus.setOperation(currentNSSI['operationType'] as String)
+ operationStatus.setResult(RequestsDbConstant.Status.FINISHED)
+
+ requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
+
+ LOGGER.trace("${PREFIX} Exit updateServiceOperationStatus")
+ }
+
+
+ /**
+ * Returns AAI client
+ * @return AAI client
+ */
+ AAIResourcesClient getAAIClient() {
+ return new AAIResourcesClient()
+ }
+
+}
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 547cb6cad7..0c795b3bd1 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
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper
import org.camunda.bpm.engine.delegate.DelegateExecution
import org.onap.logging.filter.base.ONAPComponents
import org.onap.so.beans.nsmf.DeAllocateNssi
+import org.onap.so.beans.nsmf.ServiceInfo
import org.onap.so.beans.nsmf.EsrInfo
import org.onap.so.beans.nsmf.JobStatusRequest
import org.onap.so.beans.nsmf.JobStatusResponse
@@ -44,7 +45,7 @@ import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
import org.onap.so.db.request.beans.OperationStatus
import org.slf4j.Logger
import org.slf4j.LoggerFactory
-
+import org.json.JSONObject
import javax.ws.rs.core.Response
@@ -126,7 +127,7 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
}
LOGGER.debug("*****${PREFIX} Exit processDecomposition *****")
}
-
+
/**
* send deallocate request to nssmf
* @param execution
@@ -140,61 +141,106 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
String nssiId = currentNSSI['nssiServiceInstanceId']
String nsiId = currentNSSI['nsiServiceInstanceId']
String scriptName = execution.getVariable("scriptName")
+ boolean modifyAction = execution.getVariable("terminateNSI")
+ String serviceInvariantUuid = currentNSSI['modelInvariantId']
+ String serviceUuid = currentNSSI['modelVersionId']
+ String globalSubscriberId = currentNSSI['globalSubscriberId']
+ String subscriptionServiceType = execution.getVariable("serviceType")
+
DeAllocateNssi deAllocateNssi = new DeAllocateNssi()
deAllocateNssi.setNsiId(nsiId)
deAllocateNssi.setNssiId(nssiId)
deAllocateNssi.setTerminateNssiOption(0)
deAllocateNssi.setSnssaiList(Arrays.asList(snssai))
deAllocateNssi.setScriptName(scriptName)
-
- NssiDeAllocateRequest deAllocateRequest = new NssiDeAllocateRequest()
- deAllocateRequest.setDeAllocateNssi(deAllocateNssi)
- deAllocateRequest.setEsrInfo(getEsrInfo(currentNSSI))
-
- ObjectMapper mapper = new ObjectMapper()
- String nssmfRequest = mapper.writeValueAsString(deAllocateRequest)
-
- String urlStr = String.format("/api/rest/provMns/v1/NSS/SliceProfiles/%s",profileId)
+ deAllocateNssi.setSliceProfileId(profileId)
+ deAllocateNssi.setModifyAction(modifyAction)
+
+ ServiceInfo serviceInfo = new ServiceInfo()
+ serviceInfo.setServiceInvariantUuid(serviceInvariantUuid)
+ serviceInfo.setServiceUuid(serviceUuid)
+ serviceInfo.setGlobalSubscriberId(globalSubscriberId)
+ serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
+
+ EsrInfo esrInfo = getEsrInfo(currentNSSI)
+
+ execution.setVariable("deAllocateNssi",deAllocateNssi)
+ execution.setVariable("esrInfo",esrInfo)
+ execution.setVariable("serviceInfo",serviceInfo)
+ String nssmfRequest = """
+ {
+ "deAllocateNssi": "${execution.getVariable("deAllocateNssi") as JSONObject}",
+ "esrInfo": ${execution.getVariable("esrInfo") as JSONObject},
+ "serviceInfo": ${execution.getVariable("serviceInfo") as JSONObject}
+ }
+ """
+
+ String urlStr = String.format("/api/rest/provMns/v1/NSS/nssi/%s",nssiId)
NssiResponse nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlStr, nssmfRequest, NssiResponse.class)
if (nssmfResponse != null) {
- currentNSSI['jobId']= nssmfResponse.getJobId() ?: ""
- currentNSSI['jobProgress'] = 0
- execution.setVariable("currentNSSI", currentNSSI)
-
- LOGGER.debug("*****${PREFIX} Exit sendRequestToNSSMF *****")
- } else {
+ currentNSSI['jobId']= nssmfResponse.getJobId() ?: ""
+ currentNSSI['jobProgress'] = 0
+ execution.setVariable("currentNSSI", currentNSSI)
+ }
+ else {
exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
}
-
+ LOGGER.debug("*****${PREFIX} Exit sendRequestToNSSMF *****")
}
- /**
+/**
* send to nssmf query progress
* @param execution
*/
- void getJobStatus(DelegateExecution execution)
+ void prepareJobStatusRequest(DelegateExecution execution)
{
def currentNSSI = execution.getVariable("currentNSSI")
String jobId = currentNSSI['jobId']
String nssiId = currentNSSI['nssiServiceInstanceId']
String nsiId = currentNSSI['nsiServiceInstanceId']
+ String serviceInvariantUuid = currentNSSI['modelInvariantId']
+ String serviceUuid = currentNSSI['modelVersionId']
+ String globalSubscriberId = currentNSSI['globalSubscriberId']
+ String subscriptionServiceType = execution.getVariable("serviceType")
+ String sST = currentNSSI['sST']
+ String PLMNIdList = currentNSSI['PLMNIdList']
+ String nssiName = currentNSSI['nssiName']
+
+ execution.setVariable("responseId", "3")
+ execution.setVariable("esrInfo", getEsrInfo(currentNSSI))
+ execution.setVariable("jobId", jobId)
+
+ Map<String, ?> serviceInfoMap = new HashMap<>()
+ serviceInfoMap.put("nssiId", nssiId)
+ serviceInfoMap.put("nsiId", nsiId)
+ serviceInfoMap.put("nssiName", nssiName)
+ serviceInfoMap.put("sST", sST)
+ serviceInfoMap.put("PLMNIdList", PLMNIdList)
+ serviceInfoMap.put("globalSubscriberId", globalSubscriberId)
+ serviceInfoMap.put("subscriptionServiceType", subscriptionServiceType)
+ serviceInfoMap.put("serviceInvariantUuid", serviceInvariantUuid)
+ serviceInfoMap.put("serviceUuid", serviceUuid)
+
+ execution.setVariable("serviceInfo", serviceInfoMap)
+ }
- JobStatusRequest jobStatusRequest = new JobStatusRequest()
- jobStatusRequest.setNssiId(nssiId)
- jobStatusRequest.setNsiId(nsiId)
- jobStatusRequest.setEsrInfo(getEsrInfo(currentNSSI))
-
- ObjectMapper mapper = new ObjectMapper()
- String nssmfRequest = mapper.writeValueAsString(jobStatusRequest)
-
- String urlStr = String.format("/api/rest/provMns/v1/NSS/jobs/%s", jobId)
-
- JobStatusResponse jobStatusResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlStr, nssmfRequest, JobStatusResponse.class)
-
- if (jobStatusResponse != null) {
- def progress = jobStatusResponse?.getResponseDescriptor()?.getProgress()
+
+ /**
+ * send to nssmf query progress
+ * @param execution
+ */
+ void handleJobStatus(DelegateExecution execution)
+ {
+ try
+ {
+ String jobStatusResponse = execution.getVariable("responseDescriptor")
+ String status = jsonUtil.getJsonValue(jobStatusResponse,"status")
+ def statusDescription = jsonUtil.getJsonValue(jobStatusResponse,"statusDescription")
+ def progress = jsonUtil.getJsonValue(jobStatusResponse,"progress")
+ if(!status.equalsIgnoreCase("failed"))
+ {
if(!progress)
{
LOGGER.error("job progress is null or empty!")
@@ -206,61 +252,60 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
execution.setVariable("isNSSIDeAllocated", (currentProgress == 100))
execution.setVariable("isNeedUpdateDB", (oldProgress != currentProgress))
currentNSSI['jobProgress'] = currentProgress
-
- def statusDescription = jobStatusResponse?.getResponseDescriptor()?.getStatusDescription()
+ currentNSSI['status'] = status
currentNSSI['statusDescription'] = statusDescription
LOGGER.debug("job status result: nsiId = ${nsiId}, nssiId=${nssiId}, oldProgress=${oldProgress}, progress = ${currentProgress}" )
-
- } else {
+ }
+ else {
+ execution.setVariable("isNeedUpdateDB", "true")
exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
}
-
+ }
+ catch (any)
+ {
+ String msg = "Received a Bad Response from NSSMF." cause-"+any.getCause()"
+ LOGGER.error(any.printStackTrace())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
}
private EsrInfo getEsrInfo(def currentNSSI)
{
String domaintype = currentNSSI['domainType']
String vendor = currentNSSI['vendor']
-
+
EsrInfo info = new EsrInfo()
info.setNetworkType(NetworkType.fromString(domaintype))
info.setVendor(vendor)
return info
}
- /**
+ /**
* handle job status
* prepare update requestdb
* @param execution
*/
- void handleJobStatus(DelegateExecution execution)
+ void prepareUpdateOperationStatus(DelegateExecution execution)
{
def currentNSSI = execution.getVariable("currentNSSI")
int currentProgress = currentNSSI["jobProgress"]
def proportion = currentNSSI['proportion']
def statusDes = currentNSSI["statusDescription"]
int progress = (currentProgress as int) == 0 ? 0 : (currentProgress as int) / 100 * (proportion as int)
-
+ def status = currentNSSI['status']
+
OperationStatus operationStatus = new OperationStatus()
operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
operationStatus.setOperationId(currentNSSI['operationId'] as String)
operationStatus.setOperation("DELETE")
- operationStatus.setResult("processing")
+ operationStatus.setResult(status as String)
operationStatus.setProgress(progress as String)
operationStatus.setOperationContent(statusDes as String)
requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
LOGGER.debug("update operation, currentProgress=${currentProgress}, proportion=${proportion}, progress = ${progress}" )
}
-
- void timeDelay(DelegateExecution execution) {
- try {
- Thread.sleep(10000);
- } catch(InterruptedException e) {
- LOGGER.error("Time Delay exception" + e)
- }
- }
-
+
/**
* delete slice profile from aai
* @param execution
@@ -291,4 +336,4 @@ class DoDeallocateNSSI extends AbstractServiceTaskProcessor
}
LOGGER.debug("*****${PREFIX} Exist delSliceProfileFromAAI *****")
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateTnNssi.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateTnNssi.groovy
new file mode 100644
index 0000000000..7681bf9346
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateTnNssi.groovy
@@ -0,0 +1,169 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 groovy.json.JsonSlurper
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+class DoDeallocateTnNssi extends AbstractServiceTaskProcessor {
+ String Prefix = "TNDEALLOC_"
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ TnNssmfUtils tnNssmfUtils = new TnNssmfUtils()
+ JsonSlurper jsonSlurper = new JsonSlurper()
+ ObjectMapper objectMapper = new ObjectMapper()
+ private static final Logger logger = LoggerFactory.getLogger(DoDeallocateTnNssi.class)
+
+
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug("Start preProcessRequest")
+
+ execution.setVariable("startTime", System.currentTimeMillis())
+ String msg = tnNssmfUtils.getExecutionInputParams(execution)
+ logger.debug("Deallocate TN NSSI input parameters: " + msg)
+
+ execution.setVariable("prefix", Prefix)
+
+ tnNssmfUtils.setSdncCallbackUrl(execution, true)
+ logger.debug("SDNC Callback URL: " + execution.getVariable("sdncCallbackUrl"))
+
+ String sliceServiceInstanceId = execution.getVariable("serviceInstanceID")
+ execution.setVariable("sliceServiceInstanceId", sliceServiceInstanceId)
+
+ String sliceServiceInstanceName = execution.getVariable("servicename")
+ execution.setVariable("sliceServiceInstanceName", sliceServiceInstanceName)
+
+
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelUuid = execution.getVariable("modelUuid")
+ //here modelVersion is not set, we use modelUuid to decompose the service.
+ def isDebugLogEnabled = true
+ execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ logger.debug("Finish preProcessRequest")
+ }
+
+ void preprocessSdncDeallocateTnNssiRequest(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preprocessSdncDeallocateTnNssiRequest(' +
+ 'execution=' + execution.getId() + ')'
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+ logger.trace('Entered ' + method)
+
+ try {
+ String serviceInstanceId = execution.getVariable("serviceInstanceID")
+
+ String sdncRequest = tnNssmfUtils.buildSDNCRequest(execution, serviceInstanceId, "deallocate")
+
+ execution.setVariable("TNNSSMF_SDNCRequest", sdncRequest)
+ logger.debug("Outgoing SDNCRequest is: \n" + sdncRequest)
+
+ } catch (Exception e) {
+ logger.debug("Exception Occured Processing preprocessSdncDeallocateTnNssiRequest. Exception is:\n" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage())
+ }
+ logger.trace("COMPLETED preprocessSdncDeallocateTnNssiRequest Process")
+ }
+
+
+ void validateSDNCResponse(DelegateExecution execution, String response, String method) {
+ tnNssmfUtils.validateSDNCResponse(execution, response, method)
+ }
+
+ void deleteServiceInstance(DelegateExecution execution) {
+ try {
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ execution.getVariable("serviceInstanceID"))
+ client.delete(uri)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in DoDeallocateTnNssi.deleteServiceInstance. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+
+ public void updateAAIOrchStatus(DelegateExecution execution) {
+ logger.debug("Start updateAAIOrchStatus")
+ String tnNssiId = execution.getVariable("serviceInstanceID")
+ String orchStatus = execution.getVariable("orchestrationStatus")
+
+ try {
+ ServiceInstance si = new ServiceInstance()
+ si.setOrchestrationStatus(orchStatus)
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, tnNssiId)
+ client.update(uri, si)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in CreateSliceService.updateAAIOrchStatus " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ logger.debug("Finish updateAAIOrchStatus")
+ }
+
+ void prepareUpdateJobStatus(DelegateExecution execution,
+ String status,
+ String progress,
+ String statusDescription) {
+ String serviceId = execution.getVariable("serviceInstanceID")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+
+ ResourceOperationStatus roStatus = new ResourceOperationStatus()
+ roStatus.setServiceId(serviceId)
+ roStatus.setOperationId(jobId)
+ roStatus.setResourceTemplateUUID(nsiId)
+ roStatus.setOperType("Deallocate")
+ roStatus.setProgress(progress)
+ roStatus.setStatus(status)
+ roStatus.setStatusDescription(statusDescription)
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, status)
+ }
+}
+
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 5354d52fce..2f78c3d551 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
@@ -25,16 +25,20 @@ import org.onap.aai.domain.yang.AllottedResource
import org.onap.aai.domain.yang.AllottedResources
import org.onap.aai.domain.yang.Relationship
import org.onap.aai.domain.yang.ServiceInstance
-import org.onap.aai.domain.yang.SliceProfiles
+import org.onap.aai.domain.yang.ServiceProfile
+import org.onap.aai.domain.yang.ServiceProfiles
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.aaiclient.client.aai.AAIObjectType
import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
import org.slf4j.Logger
import org.slf4j.LoggerFactory
-
+import javax.ws.rs.core.Response
import javax.ws.rs.NotFoundException
import static org.apache.commons.lang3.StringUtils.isBlank
@@ -52,6 +56,7 @@ import static org.apache.commons.lang3.StringUtils.isBlank
class DoDeleteSliceService extends AbstractServiceTaskProcessor {
private final String PREFIX ="DoDeleteSliceService"
ExceptionUtil exceptionUtil = new ExceptionUtil()
+ OofUtils oofUtils = new OofUtils()
private static final Logger LOGGER = LoggerFactory.getLogger( DoDeleteSliceService.class)
@Override
@@ -96,17 +101,47 @@ class DoDeleteSliceService extends AbstractServiceTaskProcessor {
{
LOGGER.trace(" *****${PREFIX} Start queryE2ESliceSeriveFromAAI *****")
String serviceInstanceId = execution.getVariable("serviceInstanceId")
-
+ try
+ {
String errorMsg = "query e2e slice service from aai failed"
AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
Optional<ServiceInstance> si =wrapper.asBean(ServiceInstance.class)
if(si.isPresent())
{
String snssai = si.get()?.getEnvironmentContext()
+ ServiceProfiles serviceProfiles = si.get()?.getServiceProfiles()
+ ServiceProfile serviceProfile = serviceProfiles.getServiceProfile().get(0)
+ String serviceProfileId = serviceProfile ? serviceProfile.getProfileId() : ""
execution.setVariable("snssai", snssai ?: "")
- LOGGER.info("serviceInstanceId: ${serviceInstanceId}, snssai: ${snssai}")
+ execution.setVariable("serviceProfileId",serviceProfileId)
+ List<ServiceInstance> sliceProfileList = []
+ List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo.toLowerCase() == "service-instance") {
+ String relatioshipurl = relationship.getRelatedLink()
+ String instanceId = relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
+ AAIResultWrapper wrapper1 = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, instanceId, errorMsg)
+ Optional<ServiceInstance> serviceInstance = wrapper1.asBean(ServiceInstance.class)
+ if (serviceInstance.isPresent()) {
+ ServiceInstance instance = serviceInstance.get()
+ if ("slice-profile-instance".equalsIgnoreCase(instance.getServiceRole())) {
+ sliceProfileList.add(instance)
+ }
+ }
+ }
+ }
+ execution.setVariable("sliceProfileList",sliceProfileList)
+ LOGGER.info("serviceInstanceId: ${serviceInstanceId}, snssai: ${snssai}, sliceProfileList: ${sliceProfileList}")
}
LOGGER.trace(" *****${PREFIX} Exit queryE2ESliceSeriveFromAAI *****")
+ }
+ catch (any)
+ {
+ String msg = "query E2E slice service from aai failed! cause-"+any.getCause()
+ LOGGER.error(any.printStackTrace())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
}
/**
@@ -169,7 +204,15 @@ class DoDeleteSliceService extends AbstractServiceTaskProcessor {
if (relatedTo == "service-instance")
{
String relatedLink = relationship.getRelatedLink()?:""
- String nssiId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
+ String instanceId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
+ AAIResultWrapper wrapper1 = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, instanceId, errorMsg)
+ Optional<ServiceInstance> serviceInstance = wrapper1.asBean(ServiceInstance.class)
+ if (serviceInstance.isPresent()) {
+ ServiceInstance instance = serviceInstance.get()
+ if ("nssi".equalsIgnoreCase(instance.getServiceRole())) {
+ nssiId = instance.getServiceInstanceId()
+ }
+ }
nssiIdList.add(nssiId)
msg+="${nssiId}, "
}
@@ -227,12 +270,24 @@ class DoDeleteSliceService extends AbstractServiceTaskProcessor {
{
LOGGER.trace(" *****${PREFIX} Start getCurrentNSSI *****")
List<ServiceInstance> nssiInstanceList = execution.getVariable("nssiInstanceList")
+ List<ServiceInstance> sliceProfileList = execution.getVariable("sliceProfileList")
int currentIndex = execution.getVariable("currentNSSIIndex") as int
+ String profileId = ""
ServiceInstance nssi = nssiInstanceList?.get(currentIndex)
+ for(ServiceInstance sliceProfileInstance : sliceProfileList) {
+ if(sliceProfileInstance.getWorkloadContext().equalsIgnoreCase(nssi.getWorkloadContext()))
+ {
+ profileId = sliceProfileInstance.getServiceInstanceId()
+ }
+ }
def currentNSSI = [:]
currentNSSI['nssiServiceInstanceId'] = nssi?.getServiceInstanceId()
currentNSSI['modelInvariantId'] = nssi?.getModelInvariantId()
currentNSSI['modelVersionId'] = nssi?.getModelVersionId()
+ currentNSSI['nssiName'] = nssi?.getServiceInstanceName()
+ currentNSSI['sST'] = nssi?.getServiceType()
+ currentNSSI['PLMNIdList'] = nssi?.getServiceInstanceLocationId()
+ currentNSSI['profileId'] = profileId
currentNSSI['snssai'] = execution.getVariable("snssai") ?: ""
currentNSSI['nsiServiceInstanceId'] = execution.getVariable("nsiId") ?: ""
currentNSSI['operationId'] = execution.getVariable("operationId") ?: ""
@@ -271,30 +326,6 @@ class DoDeleteSliceService extends AbstractServiceTaskProcessor {
LOGGER.trace(" *****${PREFIX} Exit parseNextNSSI *****")
}
-
- /**
- * query sliceProfile from AAI
- * save profileId
- * @param execution
- */
- void querySliceProfileFromAAI(DelegateExecution execution)
- {
- LOGGER.trace(" *****${PREFIX} Start querySliceProfileFromAAI *****")
- def currentNSSI = execution.getVariable("currentNSSI")
- String nssiId = currentNSSI['nssiServiceInstanceId']
- String errorMsg = "query slice profile failed"
- AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SLICE_PROFILE_ALL, nssiId, errorMsg)
- Optional<SliceProfiles> sliceProfiles =wrapper.asBean(SliceProfiles.class)
- if(sliceProfiles.isPresent())
- {
- String profileId = sliceProfiles.get().getSliceProfile()?.get(0)?.getProfileId()
- currentNSSI['profileId'] = profileId ?: ""
- LOGGER.info("nssiId: ${nssiId}, profileId: ${profileId}")
- }
- execution.setVariable("currentNSSI", currentNSSI)
- LOGGER.trace(" *****${PREFIX} Exit querySliceProfileFromAAI *****")
- }
-
/**
* query AAI
* @param execution
@@ -317,4 +348,57 @@ class DoDeleteSliceService extends AbstractServiceTaskProcessor {
return wrapper
}
+ void terminateNSIQuery(DelegateExecution execution)
+ {
+ logger.debug("Start terminateNSIQuery")
+
+ String requestId = execution.getVariable("msoRequestId")
+ String nxlId = currentNSSI['nsiServiceInstanceId']
+ String nxlType = "NSI"
+ String messageType = "nsiTerminationResponse"
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+
+ 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")
+ }
+
+ URL requestUrl = new URL(oofUrl + "/api/oof/terminate/nxi/v1")
+ String oofRequest = oofUtils.buildTerminateNxiRequest(requestId, nxlId, nxlType, messageType, serviceInstanceId)
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(requestUrl, 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.")
+ }
+ try {
+ Map<String, String> resMap = httpResponse.readEntity(Map.class)
+ boolean terminateResponse = resMap.get("terminateResponse")
+ execution.setVariable("terminateNSI", terminateResponse)
+ } catch (Exception ex) {
+ logger.debug( "Failed to get terminate Response suggested by OOF.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Failed to get terminate Response suggested by OOF.")
+ }
+ logger.debug("Finish terminateNSIQuery")
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyAccessNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyAccessNSSI.groovy
new file mode 100644
index 0000000000..2e7e728b44
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyAccessNSSI.groovy
@@ -0,0 +1,656 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, Wipro Limited.
+ #
+ # 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.delegate.BpmnError
+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.common.scripts.NssmfAdapterUtils
+import org.onap.so.bpmn.common.scripts.OofUtils
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.sql.Timestamp
+import java.util.List
+import static org.apache.commons.lang3.StringUtils.isBlank
+import com.google.gson.JsonObject
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.google.gson.JsonArray
+import org.onap.so.beans.nsmf.AllocateTnNssi
+import org.onap.so.beans.nsmf.EsrInfo
+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.aai.domain.yang.Relationship
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aai.domain.yang.SliceProfile
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import javax.ws.rs.NotFoundException
+
+class DoModifyAccessNSSI extends AbstractServiceTaskProcessor {
+
+ String Prefix="MASS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ OofUtils oofUtils = new OofUtils()
+ ObjectMapper objectMapper = new ObjectMapper();
+ AnNssmfUtils anNssmfUtils = new AnNssmfUtils()
+ private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
+
+ private static final Logger logger = LoggerFactory.getLogger(DoModifyAccessNSSI.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix + "preProcessRequest Start")
+ execution.setVariable("prefix", Prefix)
+ execution.setVariable("startTime", System.currentTimeMillis())
+ def msg
+ try {
+
+ logger.debug("input variables : msoRequestId - "+execution.getVariable("msoRequestId")+
+ " globalSubscriberId - "+execution.getVariable("globalSubscriberId")+
+ " serviceInstanceID - "+execution.getVariable("serviceInstanceID")+
+ " nsiId - "+execution.getVariable("nsiId")+
+ " networkType - "+execution.getVariable("networkType")+
+ " subscriptionServiceType - "+execution.getVariable("subscriptionServiceType")+
+ " jobId - "+execution.getVariable("jobId")+
+ " sliceParams - "+execution.getVariable("sliceParams")+
+ " servicename - "+ execution.getVariable("servicename"))
+
+ //validate slice subnet inputs
+
+ String sliceParams = execution.getVariable("sliceParams")
+ String modifyAction = jsonUtil.getJsonValue(sliceParams, "modifyAction")
+ if (isBlank(modifyAction)) {
+ msg = "Input modifyAction is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("modifyAction", modifyAction)
+ switch(modifyAction) {
+ case "allocate":
+ execution.setVariable("isModifyallocate", true)
+ break
+ case "deallocate":
+ execution.setVariable("isModifydeallocate", true)
+ break
+ case "reconfigure":
+ execution.setVariable("isModifyreconfigure", true)
+ String resourceConfig = jsonUtil.getJsonValue(sliceParams, "resourceConfig")
+ execution.setVariable("additionalProperties", resourceConfig)
+ break
+ default:
+ logger.debug("Invalid modify Action")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid modify Action : "+modifyAction)
+ }
+ }
+ List<String> snssaiList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceParams, "snssaiList"))
+ String sliceProfileId = jsonUtil.getJsonValue(sliceParams, "sliceProfileId")
+ if (isBlank(sliceProfileId) || (snssaiList.empty)) {
+ msg = "Mandatory fields are empty"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("sliceProfileId", sliceProfileId)
+ execution.setVariable("snssaiList", snssaiList)
+ }
+ String nsiName = jsonUtil.getJsonValue(sliceParams, "nsiInfo.nsiName")
+ String scriptName = jsonUtil.getJsonValue(sliceParams, "scriptName")
+ execution.setVariable("nsiName", nsiName)
+ execution.setVariable("scriptName", scriptName)
+ execution.setVariable("job_timeout", 10)
+ execution.setVariable("ranNssiPreferReuse", false)
+ } catch(BpmnError e) {
+ throw e
+ } catch(Exception ex) {
+ msg = "Exception in DoModifyAccessNSSI.preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "preProcessRequest Exit")
+ }
+
+ def getSliceProfile = { DelegateExecution execution ->
+ logger.debug(Prefix + "getSliceProfiles Start")
+ String instanceId = execution.getVariable("sliceProfileId")
+ ServiceInstance sliceProfileInstance = getServiceInstance(execution, instanceId)
+ SliceProfile ranSliceProfile = sliceProfileInstance.getSliceProfiles().getSliceProfile().get(0)
+ logger.debug("RAN slice profile : "+ranSliceProfile.toString())
+ execution.setVariable("RANSliceProfile", ranSliceProfile)
+ execution.setVariable("ranSliceProfileInstance", sliceProfileInstance)
+ }
+
+ /*
+ * Function to subnet capabilities from nssmf adapter
+ */
+ def getSubnetCapabilities = { DelegateExecution execution ->
+ logger.debug(Prefix+"getSubnetCapabilities method start")
+
+ String tnNssmfRequest = anNssmfUtils.buildCreateTNNSSMFSubnetCapabilityRequest()
+
+ String urlString = "/api/rest/provMns/v1/NSS/subnetCapabilityQuery"
+
+ String tnNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, tnNssmfRequest)
+
+ if (tnNssmfResponse != null) {
+ String FHCapabilities= jsonUtil.getJsonValue(tnNssmfResponse, "TN_FH")
+ String MHCapabilities = jsonUtil.getJsonValue(tnNssmfResponse, "TN_MH")
+ execution.setVariable("FHCapabilities",FHCapabilities)
+ execution.setVariable("MHCapabilities",MHCapabilities)
+
+ } else {
+ logger.error("received error message from NSSMF : "+ tnNssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ String anNssmfRequest = anNssmfUtils.buildCreateANNFNSSMFSubnetCapabilityRequest()
+
+ String anNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, anNssmfRequest)
+
+ if (anNssmfResponse != null) {
+ String ANNFCapabilities = jsonUtil.getJsonValue(anNssmfResponse, "AN_NF")
+ execution.setVariable("ANNFCapabilities",ANNFCapabilities)
+
+ } else {
+ logger.error("received error message from NSSMF : "+ anNssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ }
+
+
+ /*
+ * prepare OOF request for RAN NSSI selection
+ */
+ def prepareOofRequestForRanNSS = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareOofRequestForRanNSS method start")
+
+ String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
+ logger.debug( "get NSSI option OOF Url: " + urlString)
+
+ //build oof request body
+ boolean ranNssiPreferReuse = execution.getVariable("ranNssiPreferReuse");
+ String requestId = execution.getVariable("msoRequestId")
+ String messageType = "NSISelectionResponse"
+ Map<String, Object> profileInfo = objectMapper.readValue(execution.getVariable("RANSliceProfile"), Map.class)
+ ServiceInstance ranSliceProfileInstance = objectMapper.readValue(execution.getVariable("ranSliceProfileInstance"), ServiceInstance.class)
+ String modelUuid = ranSliceProfileInstance.getModelVersionId()
+ String modelInvariantUuid = ranSliceProfileInstance.getModelInvariantId()
+ String modelName = execution.getVariable("servicename")
+ String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
+ List<String> nsstInfoList = new ArrayList<>()
+ JsonArray capabilitiesList = new JsonArray()
+ String FHCapabilities = execution.getVariable("FHCapabilities")
+ String MHCapabilities = execution.getVariable("MHCapabilities")
+ String ANNFCapabilities = execution.getVariable("ANNFCapabilities")
+ JsonObject FH = new JsonObject()
+ JsonObject MH = new JsonObject()
+ JsonObject ANNF = new JsonObject()
+ FH.addProperty("domainType", "TN_FH")
+ FH.addProperty("capabilityDetails", FHCapabilities)
+ MH.addProperty("domainType", "TN_MH")
+ MH.addProperty("capabilityDetails", MHCapabilities)
+ ANNF.addProperty("domainType", "AN_NF")
+ ANNF.addProperty("capabilityDetails", FHCapabilities)
+ capabilitiesList.add(FH)
+ capabilitiesList.add(MH)
+ capabilitiesList.add(ANNF)
+
+ execution.setVariable("nssiSelection_Url", "/api/oof/selection/nsi/v1")
+ execution.setVariable("nssiSelection_messageType",messageType)
+ execution.setVariable("nssiSelection_correlator",requestId)
+ execution.setVariable("nssiSelection_timeout",timeout)
+ String oofRequest = anNssmfUtils.buildSelectRANNSSIRequest(requestId, messageType, modelUuid,modelInvariantUuid,
+ modelName, profileInfo, nsstInfoList, capabilitiesList, ranNssiPreferReuse)
+
+ execution.setVariable("nssiSelection_oofRequest",oofRequest)
+ logger.debug("Sending request to OOF: " + oofRequest)
+ }
+
+ /*
+ * process OOF response for RAN NSSI selection
+ */
+ def processOofResponseForRanNSS = { DelegateExecution execution ->
+ logger.debug(Prefix+"processOofResponseForRanNSS method start")
+ String oofResponse = execution.getVariable("nssiSelection_asyncCallbackResponse")
+ String requestStatus = jsonUtil.getJsonValue(oofResponse, "requestStatus")
+ if(requestStatus.equals("completed")) {
+ List<String> solution = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(oofResponse, "solutions"))
+ boolean existingNSI = jsonUtil.getJsonValue(solution.get(0), "existingNSI")
+ if(!existingNSI) {
+ def sliceProfiles = jsonUtil.getJsonValue(solution.get(0), "newNSISolution.sliceProfiles")
+ execution.setVariable("RanConstituentSliceProfiles", sliceProfiles)
+ List<String> ranConstituentSliceProfiles = jsonUtil.StringArrayToList(sliceProfiles)
+ anNssmfUtils.createDomainWiseSliceProfiles(ranConstituentSliceProfiles, execution)
+ logger.debug("RanConstituentSliceProfiles list from OOF "+sliceProfiles)
+ }else {
+ String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
+ logger.error("failed to get slice profiles from oof "+ statusMessage)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"failed to get slice profiles from oof "+statusMessage)
+ }
+ }else {
+ String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
+ logger.error("received failed status from oof "+ statusMessage)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a failed Async Response from OOF : "+statusMessage)
+ }
+
+ }
+ def getNssisFromAai = { DelegateExecution execution ->
+ logger.debug(Prefix+"getNssisFromAai method start")
+ String instanceId = execution.getVariable("serviceInstanceID")
+ String role = "nssi"
+ Map<String,ServiceInstance> ranConstituentNssis = getRelatedInstancesByRole(execution, role, instanceId)
+ logger.debug("getNssisFromAai ranConstituentNssis : "+ranConstituentNssis.toString())
+ ranConstituentNssis.each { key, val ->
+ switch(key) {
+ case "AN-NF":
+ execution.setVariable("ANNF_NSSI", val.getServiceInstanceId())
+ execution.setVariable("ANNF_nssiName", val.getServiceInstanceName())
+ break
+ case "TN-FH":
+ execution.setVariable("TNFH_NSSI", val.getServiceInstanceId())
+ execution.setVariable("TNFH_nssiName", val.getServiceInstanceName())
+ break
+ case "TN-MH":
+ execution.setVariable("TNMH_NSSI", val.getServiceInstanceId())
+ execution.setVariable("TNMH_nssiName", val.getServiceInstanceName())
+ break
+ default:
+ logger.error("No expected match found for current domainType "+ key)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current domainType "+ key)
+ }
+ }
+
+ }
+ def createSliceProfiles = { DelegateExecution execution ->
+ logger.debug(Prefix+"createSliceProfiles method start")
+ anNssmfUtils.createSliceProfilesInAai(execution)
+ }
+ def updateRelationshipInAai = { DelegateExecution execution ->
+ logger.debug(Prefix+"updateRelationshipInAai method start")
+ String msg = ""
+ try {
+ def ANNF_serviceInstanceId = execution.getVariable("ANNF_NSSI")
+ def TNFH_serviceInstanceId = execution.getVariable("TNFH_NSSI")
+ def TNMH_serviceInstanceId = execution.getVariable("TNMH_NSSI")
+ def AN_profileInstanceId = execution.getVariable("sliceProfileId")
+ def ANNF_profileInstanceId = execution.getVariable("ANNF_sliceProfileInstanceId")
+ def TNFH_profileInstanceId = execution.getVariable("TNFH_sliceProfileInstanceId")
+ def TNMH_profileInstanceId = execution.getVariable("TNMH_sliceProfileInstanceId")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ Relationship ANNF_relationship = new Relationship()
+ Relationship TNFH_relationship = new Relationship()
+ Relationship TNMH_relationship = new Relationship()
+
+ String ANNF_relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${ANNF_profileInstanceId}"
+ String TNFH_relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNFH_profileInstanceId}"
+ String TNMH_relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNMH_profileInstanceId}"
+
+ ANNF_relationship.setRelatedLink(ANNF_relatedLink)
+ ANNF_relationship.setRelatedTo("service-instance")
+ ANNF_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
+ TNFH_relationship.setRelatedLink(TNFH_relatedLink)
+ TNFH_relationship.setRelatedTo("service-instance")
+ TNFH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
+ TNMH_relationship.setRelatedLink(TNMH_relatedLink)
+ TNMH_relationship.setRelatedTo("service-instance")
+ TNMH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
+
+ // create SliceProfile and NSSI relationship in AAI
+ anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship,ANNF_serviceInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship,TNFH_serviceInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship,TNMH_serviceInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship,AN_profileInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship,AN_profileInstanceId)
+ anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship,AN_profileInstanceId)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+
+ msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+
+ def processRanNfModifyRsp = { DelegateExecution execution ->
+ logger.debug(Prefix+"processRanNfModifyRsp method start")
+ anNssmfUtils.processRanNfModifyRsp(execution)
+ }
+
+ def prepareTnFhRequest = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareTnFhRequest method start")
+
+ String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_FH", "modify-allocate")
+ String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+
+ if (nssmfResponse != null) {
+ execution.setVariable("nssmfResponse", nssmfResponse)
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TNFH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ logger.debug("Exit prepareTnFhRequest")
+
+ }
+ def prepareTnMhRequest = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareTnMhRequest method start")
+
+ String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_MH", "modify-allocate")
+ String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+
+ if (nssmfResponse != null) {
+ execution.setVariable("nssmfResponse", nssmfResponse)
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TNMH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ logger.debug("Exit prepareTnMhRequest")
+ }
+
+ def createFhAllocateNssiJobQuery = { DelegateExecution execution ->
+ logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
+ createTnAllocateNssiJobQuery(execution, "TN_FH")
+ }
+
+ def createMhAllocateNssiJobQuery = { DelegateExecution execution ->
+ logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
+ createTnAllocateNssiJobQuery(execution, "TN_MH")
+ }
+
+ private void createTnAllocateNssiJobQuery(DelegateExecution execution, String domainType) {
+ EsrInfo esrInfo = new EsrInfo()
+ esrInfo.setNetworkType("TN")
+ esrInfo.setVendor("ONAP")
+ String esrInfoString = objectMapper.writeValueAsString(esrInfo)
+ execution.setVariable("esrInfo", esrInfoString)
+ JsonObject serviceInfo = new JsonObject()
+
+ serviceInfo.addProperty("nsiId", execution.getVariable("nsiId"))
+ String sST = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "sST")
+ serviceInfo.addProperty("sST", sST)
+ serviceInfo.addProperty("PLMNIdList", objectMapper.writeValueAsString(execution.getVariable("plmnIdList")))
+ serviceInfo.addProperty("globalSubscriberId", execution.getVariable("globalSubscriberId"))
+ serviceInfo.addProperty("subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
+ serviceInfo.addProperty("serviceInvariantUuid", null)
+ serviceInfo.addProperty("serviceUuid", null)
+ if(domainType.equals("TN_FH")) {
+ serviceInfo.addProperty("nssiId", execution.getVariable("TNFH_NSSI"))
+ serviceInfo.addProperty("nssiName", execution.getVariable("TNFH_nssiName"))
+ }else if(domainType.equals("TN_MH")) {
+ serviceInfo.addProperty("nssiId", execution.getVariable("TNMH_NSSI"))
+ serviceInfo.addProperty("nssiName", execution.getVariable("TNMH_nssiName"))
+ }
+ execution.setVariable("serviceInfo", serviceInfo.toString())
+ execution.setVariable("responseId", "")
+ }
+
+ def processFhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
+ logger.debug(Prefix+"processJobStatusRsp method start")
+ String jobResponse = execution.getVariable("TNFH_jobResponse")
+ logger.debug("Job status response "+jobResponse)
+ String status = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.status")
+ String nssi = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.nssi")
+ if(status.equalsIgnoreCase("finished")) {
+ logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
+ }
+ else {
+ String statusDescription = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.statusDescription")
+ logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ }
+ }
+
+ def processMhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
+ logger.debug(Prefix+"processJobStatusRsp method start")
+ String jobResponse = execution.getVariable("TNMH_jobResponse")
+ logger.debug("Job status response "+jobResponse)
+ String status = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.status")
+ String nssi = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.nssi")
+ if(status.equalsIgnoreCase("finished")) {
+ logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
+ }
+ else {
+ String statusDescription = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.statusDescription")
+ logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
+ }
+ }
+
+ def getSliceProfilesFromAai = { DelegateExecution execution ->
+ logger.debug(Prefix+"getSliceProfilesFromAai method start")
+ String instanceId = execution.getVariable("sliceProfileId")
+ String role = "slice-profile-instance"
+ Map<String,ServiceInstance> ranConstituentSliceProfiles = getRelatedInstancesByRole(execution, role, instanceId)
+ logger.debug("getSliceProfilesFromAai ranConstituentSliceProfiles : "+ranConstituentSliceProfiles.toString())
+ ranConstituentSliceProfiles.each { key, val ->
+ switch(key) {
+ case "AN-NF":
+ execution.setVariable("ANNF_sliceProfileInstanceId", val.getServiceInstanceId())
+ break
+ case "TN-FH":
+ execution.setVariable("TNFH_sliceProfileInstanceId", val.getServiceInstanceId())
+ break
+ case "TN-MH":
+ execution.setVariable("TNMH_sliceProfileInstanceId", val.getServiceInstanceId())
+ break
+ default:
+ logger.error("No expected match found for current domainType "+ key)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current domainType "+ key)
+ }
+ }
+ }
+
+ def prepareTnFhDeallocateRequest = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareTnFhDeallocateRequest method start")
+ String nssmfRequest = anNssmfUtils.buildDeallocateNssiRequest(execution, "TN_FH")
+ String nssiId = execution.getVariable("TNFH_NSSI")
+ execution.setVariable("tnFHNSSIId", nssiId)
+ String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+ if (nssmfResponse != null) {
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TN_FH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ }
+
+ def prepareTnMhDeallocateRequest = { DelegateExecution execution ->
+ logger.debug(Prefix+"prepareTnFhDeallocateRequest method start")
+ String nssmfRequest = anNssmfUtils.buildDeallocateNssiRequest(execution, "TN_FH")
+ String nssiId = execution.getVariable("TNFH_NSSI")
+ execution.setVariable("tnFHNSSIId", nssiId)
+ String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
+ String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
+ if (nssmfResponse != null) {
+ String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
+ execution.setVariable("TN_MH_jobId",jobId)
+ } else {
+ logger.error("received error message from NSSMF : "+ nssmfResponse)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
+ }
+ }
+
+ def createFhDeAllocateNssiJobQuery = { DelegateExecution execution ->
+ logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
+ createTnAllocateNssiJobQuery(execution, "TN_FH")
+ }
+
+ def createMhDeAllocateNssiJobQuery = { DelegateExecution execution ->
+ logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
+ createTnAllocateNssiJobQuery(execution, "TN_MH")
+ }
+ def deleteFhSliceProfile = { DelegateExecution execution ->
+ logger.debug(Prefix+"deleteFhSliceProfile method start")
+ deleteServiceInstanceInAAI(execution,execution.getVariable("TNFH_sliceProfileInstanceId"))
+ }
+ def deleteMhSliceProfile = { DelegateExecution execution ->
+ logger.debug(Prefix+"deleteMhSliceProfile method start")
+ deleteServiceInstanceInAAI(execution,execution.getVariable("TNMH_sliceProfileInstanceId"))
+ }
+ def deleteAnSliceProfile = { DelegateExecution execution ->
+ logger.debug(Prefix+"deleteAnSliceProfile method start")
+ deleteServiceInstanceInAAI(execution,execution.getVariable("ANNF_sliceProfileInstanceId"))
+ }
+ /**
+ * update operation status in request db
+ *
+ */
+ def prepareOperationStatusUpdate = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareOperationStatusUpdate Start")
+
+ String serviceId = execution.getVariable("serviceInstanceID")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String nssiId = execution.getVariable("serviceInstanceID")
+ logger.debug("Service Instance serviceId:" + serviceId + " jobId:" + jobId)
+
+ ResourceOperationStatus updateStatus = new ResourceOperationStatus()
+ updateStatus.setServiceId(serviceId)
+ updateStatus.setOperationId(jobId)
+ updateStatus.setResourceTemplateUUID(nsiId)
+ updateStatus.setResourceInstanceID(nssiId)
+ updateStatus.setOperType("Modify")
+ updateStatus.setProgress(100)
+ updateStatus.setStatus("finished")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
+
+ logger.debug(Prefix + "prepareOperationStatusUpdate Exit")
+ }
+
+ def prepareFailedOperationStatusUpdate = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareFailedOperationStatusUpdate Start")
+
+ String serviceId = execution.getVariable("serviceInstanceID")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ String nssiId = execution.getVariable("serviceInstanceID")
+ logger.debug("Service Instance serviceId:" + serviceId + " jobId:" + jobId)
+
+ ResourceOperationStatus updateStatus = new ResourceOperationStatus()
+ updateStatus.setServiceId(serviceId)
+ updateStatus.setOperationId(jobId)
+ updateStatus.setResourceTemplateUUID(nsiId)
+ updateStatus.setResourceInstanceID(nssiId)
+ updateStatus.setOperType("Modify")
+ updateStatus.setProgress(0)
+ updateStatus.setStatus("failed")
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
+ }
+
+ /**
+ * @param execution
+ * @param role - nssi/slice profile instance
+ * @param instanceId - id to which the related list to be found
+ * @return
+ */
+ private Map<String,ServiceInstance> getRelatedInstancesByRole(DelegateExecution execution,String role,String instanceId) {
+ logger.debug("${Prefix} - Fetching related ${role} from AAI")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+
+ Map<String,ServiceInstance> relatedInstances = new HashMap<>()
+
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, instanceId)
+ if (!client.exists(uri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
+ }
+ AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
+ Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
+ if(si.isPresent()) {
+ List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
+ for (Relationship relationship : relationshipList) {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo.toLowerCase() == "service-instance") {
+ String relatioshipurl = relationship.getRelatedLink()
+ String serviceInstanceId =
+ relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
+
+ AAIResourcesClient client01 = new AAIResourcesClient()
+ AAIResourceUri uri01 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, serviceInstanceId)
+ if (!client.exists(uri01)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
+ "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
+ }
+ AAIResultWrapper wrapper01 = client01.get(uri01, NotFoundException.class)
+ Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
+ if (serviceInstance.isPresent()) {
+ ServiceInstance instance = serviceInstance.get()
+ if (role.equalsIgnoreCase(instance.getServiceRole())) {
+ relatedInstances.put(instance.getWorkloadContext(),instance)
+ }
+ }
+ }
+ }
+ }
+ logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
+ return relatedInstances
+ }
+
+ private ServiceInstance getServiceInstance(DelegateExecution execution, String instanceId) {
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ ServiceInstance serviceInstance = new ServiceInstance()
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, instanceId)
+ if (!client.exists(uri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
+ }
+ AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
+ Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
+
+ if(si.isPresent()) {
+ serviceInstance = si
+ }
+ return serviceInstance
+ }
+ private void deleteServiceInstanceInAAI(DelegateExecution execution,String instanceId) {
+ try {
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), instanceId)
+ getAAIClient().delete(serviceInstanceUri)
+ logger.debug("${Prefix} Exited deleteServiceInstance")
+ }catch(Exception e){
+ logger.debug("Error occured within deleteServiceInstance method: " + e)
+ }
+ }
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyCoreNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyCoreNSSI.groovy
new file mode 100644
index 0000000000..6c12a656f4
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyCoreNSSI.groovy
@@ -0,0 +1,732 @@
+package org.onap.so.bpmn.infrastructure.scripts
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.CloudRegion
+import org.onap.aai.domain.yang.Customer
+import org.onap.aai.domain.yang.GenericVnf
+import org.onap.aai.domain.yang.ModelVer
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aai.domain.yang.ServiceSubscription
+import org.onap.aai.domain.yang.SliceProfile
+import org.onap.aai.domain.yang.Tenant
+import org.onap.aai.domain.yang.VfModule
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.AAIEdgeLabel
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.Relationships
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.MsoUtils
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.HttpClient
+import org.onap.so.db.request.beans.OperationStatus
+import org.onap.so.requestsdb.RequestsDbConstant
+import org.onap.so.serviceinstancebeans.CloudConfiguration
+import org.onap.so.serviceinstancebeans.ModelInfo
+import org.onap.so.serviceinstancebeans.ModelType
+import org.onap.so.serviceinstancebeans.OwningEntity
+import org.onap.so.serviceinstancebeans.Project
+import org.onap.so.serviceinstancebeans.RequestDetails
+import org.onap.so.serviceinstancebeans.RequestInfo
+import org.onap.so.serviceinstancebeans.RequestParameters
+import org.onap.so.serviceinstancebeans.Resources
+import org.onap.so.serviceinstancebeans.Service
+import org.onap.so.serviceinstancebeans.SubscriberInfo
+import org.onap.so.serviceinstancebeans.VfModules
+import org.onap.so.serviceinstancebeans.Vnfs
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import javax.ws.rs.core.Response
+
+class DoModifyCoreNSSI extends AbstractServiceTaskProcessor {
+
+ private final String PREFIX ="DoModifyCoreNSSI"
+
+ private ExceptionUtil exceptionUtil = new ExceptionUtil()
+ private RequestDBUtil requestDBUtil = new RequestDBUtil()
+ private MsoUtils utils = new MsoUtils()
+ private JsonUtils jsonUtil = new JsonUtils()
+
+ private static final Logger LOGGER = LoggerFactory.getLogger( DoModifyCoreNSSI.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start preProcessRequest")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+ if (!currentNSSI) {
+ String msg = "currentNSSI is null"
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ LOGGER.trace("***** ${PREFIX} Exit preProcessRequest")
+ }
+
+
+ /**
+ * Queries Network Service Instance in AAI
+ * @param execution
+ */
+ void getNetworkServiceInstance(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start getNetworkServiceInstance")
+
+ AAIResourcesClient client = getAAIClient()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String globalSubscriberId = currentNSSI['globalSubscriberId']
+ String serviceType = currentNSSI['serviceType']
+ String nssiId = currentNSSI['nssiServiceInstanceId']
+
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId) //AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nssiId)
+ Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, nssiUri)
+
+ if (nssiOpt.isPresent()) {
+ ServiceInstance nssi = nssiOpt.get()
+ execution.setVariable("nssi", nssi)
+
+ execution.setVariable("nssiUri", nssiUrl)
+
+ // Network Service Instance
+ AAIResultWrapper wrapper = client.get(nssiUri);
+ Optional<Relationships> relationships = wrapper.getRelationships()
+ if (relationships.isPresent()) {
+ for(AAIResourceUri networkServiceInstanceUri: relationships.get().getRelatedAAIUris(AAIObjectType.SERVICE_INSTANCE)){ // ???
+ Optional<ServiceInstance> networkServiceInstanceOpt = client.get(ServiceInstance.class, networkServiceInstanceUri)
+ if(networkServiceInstanceOpt.isPresent()) {
+ ServiceInstance networkServiceInstance = networkServiceInstanceOpt.get()
+
+ if(networkServiceInstance.getServiceRole().equals("Network Service")) { // Network Service
+ execution.setVariable("networkServiceInstance", networkServiceInstance)
+
+ execution.setVariable("networkServiceInstanceUri", networkServiceInstanceUri)
+ break // Should be only one Network Service Instance
+ }
+ }
+ else {
+ String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+
+ }
+ }
+ else {
+ String msg = String.format("No relationship presented for NSSI %s in AAI", nssiId)
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+ }
+ else {
+ String msg = String.format("NSSI %s not found in AAI", nssiId)
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+
+
+ LOGGER.trace("***** ${PREFIX} Exit getNetworkServiceInstance")
+ }
+
+
+ /**
+ * Queries constitute VNF from Network Service Instance
+ * @param execution
+ */
+ void getConstituteVNFFromNetworkServiceInst(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start getConstituteVNFFromNetworkServiceInst")
+
+ AAIResourcesClient client = getAAIClient()
+
+ AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)execution.getVariable("networkServiceInstanceUri")
+ AAIResultWrapper wrapper = client.get(networkServiceInstanceUri);
+ Optional<Relationships> relationships = wrapper.getRelationships()
+ if (relationships.isPresent()) {
+ for (AAIResourceUri constituteVnfUri : relationships.get().getRelatedAAIUris(AAIObjectType.GENERIC_VNF)) { // ???
+ execution.setVariable("constituteVnfUri", constituteVnfUri)
+ Optional<GenericVnf> constituteVnfOpt = client.get(GenericVnf.class, constituteVnfUri)
+ if(constituteVnfOpt.isPresent()) {
+ GenericVnf constituteVnf = constituteVnfOpt.get()
+ execution.setVariable("constituteVnf", constituteVnf)
+ }
+ else {
+ String msg = String.format("No constitute VNF found for Network Service Instance %s in AAI", ((ServiceInstance)execution.getVariable("networkServiceInstance")).getServiceInstanceId())
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+
+ execution.setVariable("networkServiceInstanceUri", networkServiceInstanceUri)
+ break // Should be only one constitute VNF
+ }
+ }
+ else {
+ String msg = String.format("No relationship presented for Network Service Instance %s in AAI", ((ServiceInstance)execution.getVariable("networkServiceInstance")).getServiceInstanceId())
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+
+ LOGGER.trace("${PREFIX} Exit getConstituteVNFFromNetworkServiceInst")
+
+ }
+
+
+ /**
+ * Retrieves NSSI associated profiles from AAI
+ * @param execution
+ */
+ void getNSSIAssociatedProfiles(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start getNSSIAssociatedProfiles")
+
+ AAIResourcesClient client = getAAIClient()
+
+ ServiceInstance nssi = (ServiceInstance)execution.getVariable("nssi")
+
+ List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
+
+ if(associatedProfiles.isEmpty()) {
+ String msg = String.format("No associated profiles found for NSSI %s in AAI", nssi.getServiceInstanceId())
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
+ }
+ else {
+ execution.setVariable("associatedProfiles", associatedProfiles)
+ }
+
+ LOGGER.trace("${PREFIX} Exit getNSSIAssociatedProfiles")
+ }
+
+
+ /**
+ * Calculates a final list of S-NSSAI
+ * @param execution
+ */
+ void calculateSNSSAI(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start calculateSNSSAI")
+
+ List<SliceProfile> associatedProfiles = (List<SliceProfile>)execution.getVariable("associatedProfiles")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String currentSNSSAI = currentNSSI['S-NSSAI']
+
+ List<String> snssais = new ArrayList<>()
+
+ if((Boolean)execution.getVariable("isCreateSliceProfileInstance" ).equals(Boolean.TRUE)) { // Slice Profile Instance has to be created
+ for (SliceProfile associatedProfile : associatedProfiles) {
+ snssais.add(associatedProfile.getSNssai())
+ }
+
+ snssais.add(currentSNSSAI)
+ }
+ else { // Slice profile instance has to be deleted
+ for (SliceProfile associatedProfile : associatedProfiles) {
+ if (!associatedProfile.getSNssai().equals(currentNSSI)) { // not current S-NSSAI
+ snssais.add(associatedProfile.getSNssai())
+ }
+ }
+ }
+
+ execution.setVariable("S-NSSAIs", snssais)
+
+ LOGGER.trace("${PREFIX} Exit calculateSNSSAI")
+ }
+
+
+ /**
+ * Invoke PUT Service Instance API
+ * @param execution
+ */
+ void invokePUTServiceInstance(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start invokePUTServiceInstance")
+
+ try {
+ //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}/vnfs/{vnfId}"
+ def nsmfЕndpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
+
+ ServiceInstance networkServiceInstance = (ServiceInstance)execution.getVariable("networkServiceInstance")
+
+ GenericVnf constituteVnf = (GenericVnf)execution.getVariable("constituteVnf")
+
+ String url = String.format("${nsmfЕndpoint}/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s", networkServiceInstance.getServiceInstanceId(), constituteVnf.getVnfId()) // ???
+
+ String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
+ String basicAuth = UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
+ String basicAuthValue = utils.encrypt(basicAuth, msoKey)
+ String encodeString = utils.getBasicAuth(basicAuthValue, msoKey)
+
+ HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
+ httpClient.addAdditionalHeader("Authorization", encodeString)
+ httpClient.addAdditionalHeader("Accept", "application/json")
+
+ RequestDetails requestDetails = prepareRequestDetails(execution)
+ ObjectMapper mapper = new ObjectMapper()
+ String requestDetailsStr = mapper.writeValueAsString(requestDetails)
+
+ Response httpResponse = httpClient.put(requestDetailsStr) // check http code ???
+ } catch (any) {
+ String msg = "Exception in DoDeallocateCoreNSSI.deleteServiceOrder. " + any.getCause()
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ LOGGER.trace("${PREFIX} Exit invokePUTServiceInstance")
+ }
+
+
+ /**
+ * Prepare model info
+ * @param execution
+ * @param requestDetails
+ * @return
+ */
+ private ModelInfo prepareModelInfo(DelegateExecution execution) {
+ ModelInfo modelInfo = new ModelInfo()
+
+ modelInfo.setModelType(ModelType.service)
+ modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
+
+ AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, networkServiceInstance.getModelInvariantId()) // model of Network Service Instance ???
+ Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
+
+ if (modelVerOpt.isPresent()) {
+ modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
+ modelInfo.setModelName(modelVerOpt.get().getModelName())
+ modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
+ }
+
+
+ return modelInfo
+ }
+
+
+ /**
+ * Prepares RequestDetails object
+ * @param execution
+ * @return
+ */
+ private RequestDetails prepareRequestDetails(DelegateExecution execution) {
+ RequestDetails requestDetails = new RequestDetails()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String globalSubscriberId = currentNSSI['globalSubscriberId']
+
+ ServiceInstance networkServiceInstance = (ServiceInstance)execution.getVariable("networkServiceInstance")
+
+
+ AAIResourcesClient client = getAAIClient()
+
+ // Model Info
+ requestDetails.setModelInfo(prepareModelInfo(execution))
+
+ // Subscriber Info
+ SubscriberInfo subscriberInfo = new SubscriberInfo()
+ subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
+
+ Customer customer = null
+ ServiceSubscription serviceSubscription = null
+
+ AAIResourceUri networkServiceInstanceUri = execution.getVariable("networkServiceInstanceUri")
+ AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
+ Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
+ if(serviceSubscriptionRelationshipsOps.isPresent()) {
+ List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.SERVICE_SUBSCRIPTION)
+ if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
+ AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
+ Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
+ if(serviceSubscriptionOpt.isPresent()) {
+ serviceSubscription = serviceSubscriptionOpt.get()
+ }
+
+ wrapper = client.get(serviceSubscriptionUri)
+ Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
+ if(customerRelationshipsOps.isPresent()) {
+ List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CUSTOMER)
+ if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
+ Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
+ if(customerOpt.isPresent()) {
+ customer = customerOpt.get()
+ subscriberInfo.setSubscriberName(customer.getSubscriberName())
+ }
+ }
+ }
+ }
+
+ }
+ requestDetails.setSubscriberInfo(subscriberInfo)
+
+ // Request Info
+ RequestInfo requestInfo = new RequestInfo()
+ requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
+
+ /* No found data to provide ???
+ requestInfo.setSource()
+ requestInfo.setSuppressRollback()
+ requestInfo.setRequestorId()
+ requestInfo.setProductFamilyId()
+ */
+
+ requestDetails.setRequestInfo(requestInfo)
+
+
+ // Request Parameters
+ RequestParameters requestParameters = new RequestParameters()
+
+ // No found data to provide ??? requestParameters.setaLaCarte()
+ requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
+
+ // User params
+ List<Map<String, Object>> userParams = new ArrayList<>()
+ // Service
+ Service service = new Service()
+ // Model Info
+ ModelInfo serviceModelInfo = new ModelInfo()
+ serviceModelInfo.setModelType(ModelType.service)
+ serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
+
+ serviceModelInfo.setModelVersionId(modelInfo.get().getModelVersionId())
+ serviceModelInfo.setModelName(modelInfo.get().getModelName())
+ serviceModelInfo.setModelVersion(modelInfo.get().getModelVersion())
+
+ service.setModelInfo(serviceModelInfo)
+
+ // Resources
+ Resources resources = new Resources()
+
+ CloudRegion cloudRegion = null
+ AAIResourceUri cloudRegionRelatedAAIUri = null
+ // VNFs
+ List<Vnfs> vnfs = new ArrayList<>()
+ // VNF
+ Vnfs vnf = new Vnfs()
+
+ // Cloud configuration
+ CloudConfiguration cloudConfiguration = new CloudConfiguration()
+
+ AAIResourceUri constituteVnfUri = (AAIResourceUri)execution.getVariable("constituteVnfUri")
+ wrapper = client.get(constituteVnfUri)
+ Optional<Relationships> constituteVnfOps = wrapper.getRelationships()
+ if(constituteVnfOps.isPresent()) {
+ List<AAIResourceUri> cloudRegionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CLOUD_REGION)
+ if(!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
+ cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
+ Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
+ if(cloudRegionrOpt.isPresent()) {
+ cloudRegion = cloudRegionrOpt.get()
+ cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
+ for(Tenant tenant:cloudRegion.getTenants()) {
+ cloudConfiguration.setTenantId(tenant.getTenantId())
+ break // only one is required
+ }
+
+ cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
+ }
+ }
+ }
+
+ vnf.setCloudConfiguration(cloudConfiguration)
+
+ // VF Modules
+ GenericVnf constituteVnf = execution.getVariable("constituteVnf")
+ List<VfModules> vfModuless = new ArrayList<>()
+ for(VfModule vfModule:constituteVnf.getVfModules()) {
+ VfModules vfmodules = new VfModules()
+
+ ModelInfo vfModuleModelInfo = new ModelInfo()
+ vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
+
+ AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, vfModule.getModelInvariantId()) // ???
+ Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
+
+ if (vfModuleModelVerOpt.isPresent()) {
+ vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
+ vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
+ vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
+
+ // No model customization ID
+ }
+ vfmodules.setModelInfo(vfModuleModelInfo)
+
+ vfmodules.setInstanceName(vfModule.getVfModuleName()) // ???
+
+ vfModuless.add(vfmodules)
+ }
+ vnf.setVfModules(vfModuless)
+
+ // Model Info
+ ModelInfo vnfModelInfo = new ModelInfo()
+ vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
+ AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, constituteVnf.getModelInvariantId()) // ???
+ Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
+
+ if (vnfModelVerOpt.isPresent()) {
+ vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
+ vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
+ vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
+
+ // No model customization ID
+ // No model instance name
+ }
+
+ vnf.setModelInfo(vnfModelInfo)
+
+ // Instance name
+ vnf.setInstanceName(constituteVnf.getVnfInstanceId())
+
+ // Instance params
+ List<Map<String, Object>> instanceParams = new ArrayList<>()
+ Map<String, Object> supporrtedNSSAIMap = new HashMap<>()
+
+ // Supported S-NSSAI
+ List<String> snssais = ( List<String>)execution.getVariable("S-NSSAIs")
+ supporrtedNSSAIMap.put("supporrtedNSSAI", snssais) // remaining S-NSSAIs ??? there is no status for each s-nssai
+ instanceParams.add(supporrtedNSSAIMap)
+
+ // No other instance params, e.g. config-type
+
+ vnf.setInstanceParams(instanceParams)
+
+ // No platform data
+
+ vnfs.add(vnf)
+ resources.setVnfs(vnfs)
+
+ service.setResources(resources)
+
+ Map<String, Object> serviceMap = new HashMap<>()
+ serviceMap.put("service", service)
+ userParams.add(serviceMap)
+ requestParameters.setUserParams(userParams)
+
+ // No other user params
+
+ requestDetails.setRequestParameters(requestParameters)
+
+ // No other request params
+
+ // Cloud configuration
+ requestDetails.setCloudConfiguration(cloudConfiguration)
+
+ // Owning entity
+ OwningEntity owningEntity = new OwningEntity()
+ wrapper = client.get(networkServiceInstanceUri)
+ Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
+ if(owningEntityRelationshipsOps.isPresent()) {
+ List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.OWNING_ENTITY)
+
+ if(!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
+ Optional<org.onap.aai.domain.yang.OwningEntity> owningEntityOpt = client.get(org.onap.aai.domain.yang.OwningEntity.class, owningEntityRelatedAAIUris.get(0)) // Many-To-One relation
+ if(owningEntityOpt.isPresent()) {
+ owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
+ owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
+ requestDetails.setOwningEntity(owningEntity)
+ }
+ }
+ }
+
+ // Project
+ Project project = new Project()
+ if(cloudRegionRelatedAAIUri != null) {
+ wrapper = client.get(cloudRegionRelatedAAIUri)
+ Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
+ if(cloudRegionOps.isPresent()) {
+ List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedAAIUris(AAIObjectType.PROJECT)
+ if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
+ Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.Project.class, projectAAIUris.get(0))
+ if(projectOpt.isPresent()) {
+ project.setProjectName(projectOpt.get().getProjectName())
+ }
+ }
+ }
+ }
+ requestDetails.setProject(project)
+
+ return requestDetails
+ }
+
+
+ /**
+ * Creates Slice Profile Instance
+ * @param execution
+ */
+ void createSliceProfileInstance(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start createSliceProfileInstance")
+
+ String sliceProfileID = execution.getVariable("sliceProfileID")
+ 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.setExpDataRate(0)
+ sliceProfile.setTrafficDensity(0)
+ sliceProfile.setConnDensity(0)
+ sliceProfile.setSNssai(sliceProfileMap.get("sNSSAI").toString())
+ 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(sliceProfileID)
+ sliceProfile.setE2ELatency(0)
+
+ try {
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, sliceProfileID)
+ client.create(uri, sliceProfile)
+
+ execution.setVariable("createdSliceProfile", sliceProfile)
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile create call:" + ex.getMessage())
+ }
+
+ LOGGER.trace("${PREFIX} Exit createSliceProfileInstance")
+ }
+
+
+ /**
+ * Creates Slice Profile association with NSSI
+ * @param execution
+ */
+ void associateSliceProfileInstanceWithNSSI(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start associateSliceProfileInstanceWithNSSI")
+
+ String sliceProfileID = execution.getVariable("sliceProfileID")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ String nssiId = currentNSSI['nssiServiceInstanceId']
+
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+ AAIResourceUri sliceProfileUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, sliceProfileID)
+
+ try {
+ SliceProfile createdSliceProfile = (SliceProfile)execution.getVariable("createdSliceProfile")
+ ServiceInstance nssi = (ServiceInstance)execution.getVariable("nssi")
+ List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
+ associatedProfiles.add(createdSliceProfile)
+
+ getAAIClient().update(nssiUri, nssi)
+
+ getAAIClient().connect(sliceProfileUri, nsiUri, AAIEdgeLabel.BELONGS_TO)
+ }catch(Exception e){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI disconnect call: " + e.getMessage())
+ }
+
+ LOGGER.trace("${PREFIX} Exit associateSliceProfileInstanceWithNSSI")
+ }
+
+
+ /**
+ * Removes Slice Profile association with NSSI
+ * @param execution
+ */
+ void removeSPAssociationWithNSSI(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start removeSPAssociationWithNSSI")
+
+ AAIResourcesClient client = getAAIClient()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ ServiceInstance nssi = (ServiceInstance)execution.getVariable("nssi")
+
+ String nssiId = currentNSSI['nssiServiceInstanceId']
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+
+ List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
+
+ String currentSNSSAI = currentNSSI['S-NSSAI']
+
+ associatedProfiles.removeIf({ associatedProfile -> (associatedProfile.getSNssai().equals(currentSNSSAI)) })
+
+ try {
+ getAAIClient().update(nssiUri, nssi)
+ }catch(Exception e){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI update call: " + e.getMessage())
+ }
+
+ LOGGER.trace("${PREFIX} Exit removeSPAssociationWithNSSI")
+ }
+
+
+ /**
+ * Deletes Slice Profile Instance
+ * @param execution
+ */
+ void deleteSliceProfileInstance(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start deleteSliceProfileInstance")
+
+ AAIResourcesClient client = getAAIClient()
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ ServiceInstance nssi = (ServiceInstance)execution.getVariable("nssi")
+
+ List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
+
+ String currentSNSSAI = currentNSSI['S-NSSAI']
+
+ AAIResourceUri sliceProfileUri = null
+
+ for(SliceProfile associatedProfile:associatedProfiles) {
+ if(!associatedProfile.getSNssai().equals(currentNSSI)) { // not current S-NSSAI
+ sliceProfileUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, associatedProfile.getProfileId())
+ break
+ }
+ }
+
+ try {
+ getAAIClient().delete(sliceProfileUri)
+ }catch(Exception e){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
+ }
+
+ LOGGER.trace("${PREFIX} Exit deleteSliceProfileInstance")
+ }
+
+
+ /**
+ * Updates operation status
+ * @param execution
+ */
+ void updateServiceOperationStatus(DelegateExecution execution) {
+ LOGGER.trace("${PREFIX} Start updateServiceOperationStatus")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+
+ OperationStatus operationStatus = new OperationStatus()
+ operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
+ operationStatus.setOperationId(currentNSSI['operationId'] as String)
+ operationStatus.setOperation(currentNSSI['operationType'] as String)
+ operationStatus.setResult(RequestsDbConstant.Status.FINISHED)
+
+ requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
+
+ LOGGER.trace("${PREFIX} Exit updateServiceOperationStatus")
+ }
+
+
+ /**
+ * Returns AAI client
+ * @return AAI client
+ */
+ AAIResourcesClient getAAIClient() {
+ return new AAIResourcesClient()
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyRanNfNssi.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyRanNfNssi.groovy
new file mode 100644
index 0000000000..6fdfbe3218
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyRanNfNssi.groovy
@@ -0,0 +1,193 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, Wipro Limited.
+ #
+ # 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.delegate.BpmnError
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+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.json.JsonUtils
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.google.gson.JsonObject
+import java.sql.Timestamp
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+import org.onap.so.bpmn.core.UrnPropertiesReader
+
+class DoModifyRanNfNssi extends AbstractServiceTaskProcessor {
+
+ String Prefix="MANNFNSS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ ObjectMapper objectMapper = new ObjectMapper();
+ AnNssmfUtils anNssmfUtils = new AnNssmfUtils()
+
+ private static final Logger logger = LoggerFactory.getLogger(DoModifyRanNfNssi.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix + "preProcessRequest Start")
+ execution.setVariable("prefix", Prefix)
+ execution.setVariable("startTime", System.currentTimeMillis())
+ def msg
+ try {
+
+ logger.debug("input variables : msoRequestId - "+execution.getVariable("msoRequestId")+
+ " globalSubscriberId - "+execution.getVariable("globalSubscriberId")+
+ " serviceInstanceID - "+execution.getVariable("serviceInstanceID")+
+ " subscriptionServiceType - "+execution.getVariable("subscriptionServiceType")+
+ " sliceProfileId - "+execution.getVariable("sliceProfileId")+
+ " snssaiList - "+execution.getVariable("snssaiList")+
+ " modifyAction - "+execution.getVariable("modifyAction"))
+
+ //validate RAN NF slice subnet inputs
+
+ String modifyAction = execution.getVariable("modifyAction")
+ if (isBlank(modifyAction)) {
+ msg = "Input modifyAction is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("modifyAction", modifyAction)
+ switch(modifyAction) {
+ case "allocate":
+ String sliceProfile = execution.getVariable("additionalProperties")
+ execution.setVariable("sliceProfile", sliceProfile)
+ break
+ case "reconfigure":
+ String resourceConfig = execution.getVariable("additionalProperties")
+ execution.setVariable("resourceConfig", resourceConfig)
+ break
+ default:
+ logger.debug("Invalid modify Action")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid modify Action : "+modifyAction)
+ }
+ }
+ List<String> snssaiList = objectMapper.readValue(execution.getVariable("snssaiList"), List.class)
+ String sliceProfileId = execution.getVariable("sliceProfileId")
+ if (isBlank(sliceProfileId) || (snssaiList.empty)) {
+ msg = "Mandatory fields are empty"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("sliceProfileId", sliceProfileId)
+ execution.setVariable("snssaiList", snssaiList)
+ execution.setVariable("snssai", snssaiList.get(0))
+ }
+
+ } catch(BpmnError e) {
+ throw e
+ } catch(Exception ex) {
+ msg = "Exception in DoModifyAccessNssi.preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "preProcessRequest Exit")
+ }
+
+ def createSdnrRequest = { DelegateExecution execution ->
+ logger.debug(Prefix+"createSdnrRequest method start")
+ String callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.message.endpoint") + "/AsyncSdnrResponse/"+execution.getVariable("msoRequestId")
+ String modifyAction = execution.getVariable("modifyAction")
+ String sdnrRequest = buildSdnrAllocateRequest(execution, modifyAction, "InstantiateRANSlice", callbackUrl)
+ execution.setVariable("createNSSI_sdnrRequest", sdnrRequest)
+ execution.setVariable("createNSSI_timeout", "PT10M")
+ execution.setVariable("createNSSI_correlator", execution.getVariable("msoRequestId"))
+ execution.setVariable("createNSSI_messageType", "AsyncSdnrResponse");
+ }
+
+ def processSdnrResponse = { DelegateExecution execution ->
+ logger.debug(Prefix+"processSdnrResponse method start")
+ String SDNRResponse = execution.getVariable("SDNR_asyncCallbackResponse")
+ String status = jsonUtil.getJsonValue(SDNRResponse, "status")
+ if(status.equalsIgnoreCase("success")) {
+ String nfIds = jsonUtil.getJsonValue(SDNRResponse, "nfIds")
+ execution.setVariable("ranNfIdsJson", nfIds)
+ }else {
+ String reason = jsonUtil.getJsonValue(SDNRResponse, "reason")
+ logger.error("received failed status from SDNR "+ reason)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from SDNR "+ reason)
+ }
+ logger.debug("response from SDNR "+SDNRResponse)
+ }
+
+ private String buildSdnrAllocateRequest(DelegateExecution execution, String action, String rpcName, String callbackUrl) {
+
+ String requestId = execution.getVariable("msoRequestId")
+ Date date = new Date().getTime()
+ Timestamp time = new Timestamp(date)
+ String sliceProfileString
+ JsonObject response = new JsonObject()
+ JsonObject body = new JsonObject()
+ JsonObject input = new JsonObject()
+ JsonObject commonHeader = new JsonObject()
+ JsonObject payload = new JsonObject()
+ JsonObject payloadInput = new JsonObject()
+ if(action.equals("allocate")) {
+ Map<String,Object> sliceProfile = objectMapper.readValue(execution.getVariable("sliceProfile"), Map.class)
+ sliceProfile.put("sliceProfileId", execution.getVariable("sliceProfileId"))
+ sliceProfile.put("maxNumberofConns", sliceProfile.get("maxNumberofPDUSessions"))
+ sliceProfile.put("uLThptPerSlice", sliceProfile.get("expDataRateUL"))
+ sliceProfile.put("dLThptPerSlice", sliceProfile.get("expDataRateDL"))
+ sliceProfileString = objectMapper.writeValueAsString(sliceProfile)
+ action = "modify-"+action
+ payloadInput.add("additionalproperties", new JsonObject())
+ }else if(action.equals("deallocate")) {
+ action = "modify-"+action
+ Map<String,Object> sliceProfile = new HashMap<>()
+ sliceProfile.put("sliceProfileId", execution.getVariable("sliceProfileId"))
+ sliceProfile.put("sNSSAI", execution.getVariable("snssai"))
+ sliceProfileString = objectMapper.writeValueAsString(sliceProfile)
+ payloadInput.add("additionalproperties", new JsonObject())
+ }else if(action.equals("reconfigure")) {
+ Map<String,Object> sliceProfile = new HashMap<>()
+ sliceProfile.put("sliceProfileId", execution.getVariable("sliceProfileId"))
+ sliceProfile.put("sNSSAI", execution.getVariable("snssai"))
+ sliceProfileString = objectMapper.writeValueAsString(sliceProfile)
+ JsonObject resourceconfig = new JsonObject()
+ resourceconfig.addProperty("resourceConfig", execution.getVariable("resourceConfig"))
+ payloadInput.add("additionalproperties", resourceconfig)
+ }
+ commonHeader.addProperty("TimeStamp", time.toString())
+ commonHeader.addProperty("APIver", "1.0")
+ commonHeader.addProperty("RequestID", requestId)
+ commonHeader.addProperty("SubRequestID", "1")
+ commonHeader.add("RequestTrack", new JsonObject())
+ commonHeader.add("Flags", new JsonObject())
+ payloadInput.addProperty("sliceProfile", sliceProfileString)
+ payloadInput.addProperty("RANNFNSSIId", execution.getVariable("serviceInstanceID"))
+ payloadInput.addProperty("callbackURL", callbackUrl)
+ payload.add("input", payloadInput)
+ input.add("CommonHeader", commonHeader)
+ input.addProperty("Action", action)
+ input.add("Payload", payload)
+ body.add("input", input)
+ response.add("body", body)
+ response.addProperty("version", "1.0")
+ response.addProperty("rpc-name", rpcName)
+ response.addProperty("correlation-id", requestId+"-1")
+ response.addProperty("type", "request")
+ return response.toString()
+ }
+
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyTnNssi.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyTnNssi.groovy
new file mode 100644
index 0000000000..0b7a5ff59b
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyTnNssi.groovy
@@ -0,0 +1,401 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 groovy.json.JsonSlurper
+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.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+public class DoModifyTnNssi extends AbstractServiceTaskProcessor {
+ String Prefix = "TNMOD_"
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ TnNssmfUtils tnNssmfUtils = new TnNssmfUtils()
+ JsonSlurper jsonSlurper = new JsonSlurper()
+ ObjectMapper objectMapper = new ObjectMapper()
+ private static final Logger logger = LoggerFactory.getLogger(DoModifyTnNssi.class)
+
+
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug("Start preProcessRequest")
+ execution.setVariable("prefix", Prefix)
+ String msg = ""
+
+ try {
+ execution.setVariable("startTime", System.currentTimeMillis())
+ msg = tnNssmfUtils.getExecutionInputParams(execution)
+ logger.debug("Modify TN NSSI input parameters: " + msg)
+
+ execution.setVariable("prefix", Prefix)
+
+ tnNssmfUtils.setSdncCallbackUrl(execution, true)
+ logger.debug("SDNC Callback URL: " + execution.getVariable("sdncCallbackUrl"))
+
+ String additionalPropJsonStr = execution.getVariable("sliceParams")
+
+ String sliceServiceInstanceId = execution.getVariable("serviceInstanceID")
+ execution.setVariable("sliceServiceInstanceId", sliceServiceInstanceId)
+
+ String sliceServiceInstanceName = execution.getVariable("servicename")
+ execution.setVariable("sliceServiceInstanceName", sliceServiceInstanceName)
+
+ String operationId = UUID.randomUUID().toString()
+ execution.setVariable("operationId", operationId)
+
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelUuid = execution.getVariable("modelUuid")
+ //here modelVersion is not set, we use modelUuid to decompose the service.
+ def isDebugLogEnabled = true
+ execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+
+ //additional properties
+ String sliceProfile = jsonUtil.getJsonValue(additionalPropJsonStr, "sliceProfile")
+ if (isBlank(sliceProfile)) {
+ msg = "Input sliceProfile is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("sliceProfile", sliceProfile)
+ }
+
+ String transportSliceNetworks = jsonUtil.getJsonValue(additionalPropJsonStr, "transportSliceNetworks")
+ if (isBlank(transportSliceNetworks)) {
+ msg = "Input transportSliceNetworks is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("transportSliceNetworks", transportSliceNetworks)
+ }
+ logger.debug("transportSliceNetworks: " + transportSliceNetworks)
+
+ String nsiInfo = jsonUtil.getJsonValue(additionalPropJsonStr, "nsiInfo")
+ if (isBlank(nsiInfo)) {
+ msg = "Input nsiInfo is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("nsiInfo", nsiInfo)
+ }
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug("Finish preProcessRequest")
+ }
+
+
+ void deleteServiceInstance(DelegateExecution execution) {
+ try {
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ execution.getVariable("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"),
+ execution.getVariable("serviceInstanceID"))
+ client.delete(uri)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in DoDeallocateTnNssi.deleteServiceInstance. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+
+
+ void getExistingServiceInstance(DelegateExecution execution) {
+ String serviceInstanceId = execution.getVariable("serviceInstanceID")
+
+ AAIResourcesClient resourceClient = getAAIClient()
+ AAIResourceUri ssServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)
+
+ try {
+ if (resourceClient.exists(ssServiceuri)) {
+ execution.setVariable("ssi_resourceLink", ssServiceuri.build().toString())
+ org.onap.aai.domain.yang.ServiceInstance ss =
+ resourceClient.get(org.onap.aai.domain.yang.ServiceInstance.class, ssServiceuri)
+ org.onap.aai.domain.yang.SliceProfile sliceProfile = ss.getSliceProfiles().getSliceProfile().get(0)
+ execution.setVariable("sliceProfileId", sliceProfile.getProfileId())
+
+ org.onap.aai.domain.yang.AllottedResources ars = ss.getAllottedResources()
+ List<org.onap.aai.domain.yang.AllottedResource> arList = ars.getAllottedResource()
+ List<String> arIdList = new ArrayList<>()
+ for (org.onap.aai.domain.yang.AllottedResource ar : arList) {
+ String arId = ar.getId()
+ arIdList.add(arId)
+ }
+ execution.setVariable("arIdList", arIdList)
+ } 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)
+ }
+
+ }
+
+ public void updateTnNssiInAAI(DelegateExecution execution) {
+ getExistingServiceInstance(execution)
+
+ updateServiceInstance(execution)
+ updateSliceProfile(execution)
+ updateAllottedResource(execution)
+ }
+
+ void updateServiceInstance(DelegateExecution execution) {
+ String serviceRole = "TN"
+ String serviceType = execution.getVariable("subscriptionServiceType")
+ String sliceProfileStr = execution.getVariable("sliceProfile")
+ String ssInstanceId = execution.getVariable("sliceServiceInstanceId")
+ try {
+ org.onap.aai.domain.yang.ServiceInstance ss = new org.onap.aai.domain.yang.ServiceInstance()
+ ss.setServiceInstanceId(ssInstanceId)
+ String sliceInstanceName = execution.getVariable("sliceServiceInstanceName")
+ ss.setServiceInstanceName(sliceInstanceName)
+ ss.setServiceType(serviceType)
+ String serviceStatus = "modified"
+ ss.setOrchestrationStatus(serviceStatus)
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelUuid = execution.getVariable("modelUuid")
+ ss.setModelInvariantId(modelInvariantUuid)
+ ss.setModelVersionId(modelUuid)
+ String serviceInstanceLocationid = tnNssmfUtils.getFirstPlmnIdFromSliceProfile(sliceProfileStr)
+ ss.setServiceInstanceLocationId(serviceInstanceLocationid)
+ String snssai = tnNssmfUtils.getFirstSnssaiFromSliceProfile(sliceProfileStr)
+ ss.setEnvironmentContext(snssai)
+ ss.setServiceRole(serviceRole)
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), ssInstanceId)
+ client.update(uri, ss)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in DoCreateTnNssiInstance.createServiceInstance. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+
+ void updateSliceProfile(DelegateExecution execution) {
+
+ String sliceserviceInstanceId = execution.getVariable("sliceServiceInstanceId")
+ String sliceProfileStr = execution.getVariable("sliceProfile")
+ String sliceProfileId = execution.getVariable("sliceProfileId")
+ SliceProfile sliceProfile = new SliceProfile();
+ sliceProfile.setProfileId(sliceProfileId)
+ sliceProfile.setLatency(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "latency")))
+ sliceProfile.setResourceSharingLevel(jsonUtil.getJsonValue(sliceProfileStr, "resourceSharingLevel"))
+ sliceProfile.setSNssai(tnNssmfUtils.getFirstSnssaiFromSliceProfile(sliceProfileStr)) //TODO: should be list
+
+ sliceProfile.setE2ELatency(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "latency")))
+ sliceProfile.setMaxBandwidth(Integer.parseInt(jsonUtil.getJsonValue(sliceProfileStr, "maxBandwidth")))
+
+ //TODO: new API
+ sliceProfile.setReliability(new Object())
+ try {
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, execution.getVariable
+ ("globalSubscriberId"),
+ execution.getVariable("subscriptionServiceType"), sliceserviceInstanceId, sliceProfileId)
+ client.update(uri, sliceProfile)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in updateSliceProfile. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ }
+
+ void updateAllottedResource(DelegateExecution execution) {
+ String serviceInstanceId = execution.getVariable('serviceInstanceID')
+
+ List<String> arIdList = execution.getVariable("arIdList")
+ try {
+ for (String arId : arIdList) {
+ AAIResourceUri arUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE,
+ execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"),
+ serviceInstanceId, arId)
+
+ getAAIClient().delete(arUri)
+ }
+
+ List<String> networkStrList = jsonUtil.StringArrayToList(execution.getVariable("transportSliceNetworks"))
+
+ for (String networkStr : networkStrList) {
+ String allottedResourceId = UUID.randomUUID().toString()
+ AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE,
+ execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"),
+ execution.getVariable("sliceserviceInstanceId"), allottedResourceId)
+ execution.setVariable("allottedResourceUri", allottedResourceUri)
+ String modelInvariantId = execution.getVariable("modelInvariantUuid")
+ String modelVersionId = execution.getVariable("modelUuid")
+
+ org.onap.aai.domain.yang.AllottedResource resource = new org.onap.aai.domain.yang.AllottedResource()
+ resource.setId(allottedResourceId)
+ resource.setType("TsciNetwork")
+ resource.setAllottedResourceName("network_" + execution.getVariable("sliceServiceInstanceName"))
+ resource.setModelInvariantId(modelInvariantId)
+ resource.setModelVersionId(modelVersionId)
+ getAAIClient().create(allottedResourceUri, resource)
+
+ String linkArrayStr = jsonUtil.getJsonValue(networkStr, "connectionLinks")
+ createLogicalLinksForAllocatedResource(execution, linkArrayStr, serviceInstanceId, allottedResourceId)
+ }
+
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception in createAaiAR " + ex.getMessage())
+ }
+ }
+
+ void createLogicalLinksForAllocatedResource(DelegateExecution execution,
+ String linkArrayStr, String serviceInstanceId,
+ String allottedResourceId) {
+
+ try {
+ List<String> linkStrList = jsonUtil.StringArrayToList(linkArrayStr)
+
+ for (String linkStr : linkStrList) {
+ String logicalLinkId = UUID.randomUUID().toString()
+ String epA = jsonUtil.getJsonValue(linkStr, "transportEndpointA")
+ String epB = jsonUtil.getJsonValue(linkStr, "transportEndpointB")
+ String modelInvariantId = execution.getVariable("modelInvariantUuid")
+ String modelVersionId = execution.getVariable("modelUuid")
+
+ org.onap.aai.domain.yang.LogicalLink resource = new org.onap.aai.domain.yang.LogicalLink()
+ resource.setLinkId(logicalLinkId)
+ resource.setLinkName(epA)
+ resource.setLinkName2(epB)
+ resource.setModelInvariantId(modelInvariantId)
+ resource.setModelVersionId(modelVersionId)
+
+ AAIResourceUri logicalLinkUri = AAIUriFactory.createResourceUri(AAIObjectType.LOGICAL_LINK, logicalLinkId)
+ getAAIClient().create(logicalLinkUri, resource)
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,
+ "Exception in createLogicalLinksForAllocatedResource" + ex.getMessage())
+ }
+ }
+
+
+ void preprocessSdncModifyTnNssiRequest(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preprocessSdncModifyTnNssiRequest(' +
+ 'execution=' + execution.getId() + ')'
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+ logger.trace('Entered ' + method)
+
+ try {
+ String serviceInstanceId = execution.getVariable("serviceInstanceID")
+
+ String sdncRequest = tnNssmfUtils.buildSDNCRequest(execution, serviceInstanceId, "modify")
+
+ execution.setVariable("TNNSSMF_SDNCRequest", sdncRequest)
+ logger.debug("Outgoing SDNCRequest is: \n" + sdncRequest)
+
+ } catch (Exception e) {
+ logger.debug("Exception Occured Processing preprocessSdncModifyTnNssiRequest. Exception is:\n" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage())
+ }
+ logger.trace("COMPLETED preprocessSdncModifyTnNssiRequest Process")
+ }
+
+
+ void validateSDNCResponse(DelegateExecution execution, String response, String method) {
+ tnNssmfUtils.validateSDNCResponse(execution, response, method)
+ }
+
+
+ void updateAAIOrchStatus(DelegateExecution execution) {
+ logger.debug("Start updateAAIOrchStatus")
+ String sliceServiceInstanceId = execution.getVariable("sliceServiceInstanceId")
+ String orchStatus = execution.getVariable("orchestrationStatus")
+
+ try {
+ ServiceInstance si = new ServiceInstance()
+ si.setOrchestrationStatus(orchStatus)
+ AAIResourcesClient client = getAAIClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, sliceServiceInstanceId)
+ client.update(uri, si)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in CreateSliceService.updateAAIOrchStatus " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ logger.debug("Finish updateAAIOrchStatus")
+ }
+
+ void prepareUpdateJobStatus(DelegateExecution execution,
+ String status,
+ String progress,
+ String statusDescription) {
+ String serviceId = execution.getVariable("serviceInstanceID")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+
+ ResourceOperationStatus roStatus = new ResourceOperationStatus()
+ roStatus.setServiceId(serviceId)
+ roStatus.setOperationId(jobId)
+ roStatus.setResourceTemplateUUID(nsiId)
+ roStatus.setOperType("Modify")
+ roStatus.setProgress(progress)
+ roStatus.setStatus(status)
+ roStatus.setStatusDescription(statusDescription)
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, status)
+ }
+
+}
+
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/PNFSoftwareUpgrade.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/GenericPnfSoftwareUpgrade.groovy
index 8e7a4f727d..89902209a0 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/PNFSoftwareUpgrade.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/GenericPnfSoftwareUpgrade.groovy
@@ -31,8 +31,8 @@ import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder
import org.onap.so.bpmn.core.WorkflowException
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.*
-class PNFSoftwareUpgrade extends AbstractServiceTaskProcessor {
- private static final Logger logger = LoggerFactory.getLogger(PNFSoftwareUpgrade.class)
+class GenericPnfSoftwareUpgrade extends AbstractServiceTaskProcessor {
+ private static final Logger logger = LoggerFactory.getLogger(GenericPnfSoftwareUpgrade.class)
ExceptionUtil exceptionUtil = new ExceptionUtil()
String prefix = "PnfSwUpgrade_"
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ModifySliceSubnet.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ModifySliceSubnet.groovy
new file mode 100644
index 0000000000..47489b7b84
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ModifySliceSubnet.groovy
@@ -0,0 +1,173 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, Wipro Limited.
+ #
+ # 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.delegate.BpmnError
+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.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class ModifySliceSubnet extends AbstractServiceTaskProcessor {
+ String Prefix="MSS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+
+ private static final Logger logger = LoggerFactory.getLogger(ModifySliceSubnet.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix + "preProcessRequest Start")
+ execution.setVariable("prefix", Prefix)
+ execution.setVariable("startTime", System.currentTimeMillis())
+ def msg
+ try {
+ // get request input
+ String subnetInstanceReq = execution.getVariable("bpmnRequest")
+ logger.debug(subnetInstanceReq)
+
+ String requestId = execution.getVariable("mso-request-id")
+ execution.setVariable("msoRequestId", requestId)
+ logger.debug("Input Request:" + subnetInstanceReq + " reqId:" + requestId)
+
+ //subscriberInfo
+ String globalSubscriberId = jsonUtil.getJsonValue(subnetInstanceReq, "globalSubscriberId")
+ if (isBlank(globalSubscriberId)) {
+ msg = "Input globalSubscriberId' is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("globalSubscriberId", globalSubscriberId)
+ }
+
+ //NSSI Info
+ String serviceInstanceID = jsonUtil.getJsonValue(subnetInstanceReq, "serviceInstanceID")
+ if (isBlank(serviceInstanceID)) {
+ msg = "Input serviceInstanceID is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("serviceInstanceID", serviceInstanceID)
+ }
+
+ String servicename = jsonUtil.getJsonValue(subnetInstanceReq, "name")
+ execution.setVariable("servicename", servicename)
+
+ String nsiId = jsonUtil.getJsonValue(subnetInstanceReq, "additionalProperties.nsiInfo.nsiId")
+ if (isBlank(nsiId)) {
+ msg = "Input nsiId is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("nsiId", nsiId)
+ }
+
+ String networkType = jsonUtil.getJsonValue(subnetInstanceReq, "networkType")
+ if (isBlank(networkType)) {
+ msg = "Input networkType is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else
+ {
+ execution.setVariable("networkType", networkType.toUpperCase())
+ }
+
+ //requestParameters, subscriptionServiceType is 5G
+ String subscriptionServiceType = jsonUtil.getJsonValue(subnetInstanceReq, "subscriptionServiceType")
+ if (isBlank(subscriptionServiceType)) {
+ msg = "Input subscriptionServiceType is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("subscriptionServiceType", subscriptionServiceType)
+ }
+
+ String jobId = UUID.randomUUID().toString()
+ execution.setVariable("jobId", jobId)
+
+ String sliceParams = jsonUtil.getJsonValue(subnetInstanceReq, "additionalProperties")
+ execution.setVariable("sliceParams", sliceParams)
+
+ } catch(BpmnError e) {
+ throw e
+ } catch(Exception ex) {
+ msg = "Exception in ModifySliceSubnet.preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "preProcessRequest Exit")
+ }
+
+
+ /**
+ * create operation status in request db
+ *
+ * Init the Operation Status
+ */
+ def prepareInitOperationStatus = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareInitOperationStatus Start")
+
+ String serviceId = execution.getVariable("serviceInstanceID")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+ logger.debug("Generated new job for Service Instance serviceId:" + serviceId + "jobId:" + jobId)
+
+ ResourceOperationStatus initStatus = new ResourceOperationStatus()
+ initStatus.setServiceId(serviceId)
+ initStatus.setOperationId(jobId)
+ initStatus.setResourceTemplateUUID(nsiId)
+ initStatus.setOperType("Modify")
+ requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
+
+ logger.debug(Prefix + "prepareInitOperationStatus Exit")
+ }
+
+
+
+ /**
+ * return sync response
+ */
+ def sendSyncResponse = { DelegateExecution execution ->
+ logger.debug(Prefix + "sendSyncResponse Start")
+ try {
+ String jobId = execution.getVariable("jobId")
+ String modifySyncResponse = """{"jobId": "${jobId}","status": "processing"}"""
+ .trim().replaceAll(" ", "")
+ logger.debug("sendSyncResponse to APIH:" + "\n" + modifySyncResponse)
+ sendWorkflowResponse(execution, 202, modifySyncResponse)
+
+ execution.setVariable("sentSyncResponse", true)
+ } catch (Exception ex) {
+ String msg = "Exception in sendSyncResponse:" + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "sendSyncResponse Exit")
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/QueryJobStatus.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/QueryJobStatus.groovy
new file mode 100644
index 0000000000..5cdf540173
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/QueryJobStatus.groovy
@@ -0,0 +1,141 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Wipro Limited.
+ * ================================================================================
+ * 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 groovy.json.JsonSlurper
+import org.json.JSONObject
+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.json.JsonUtils
+import org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import org.onap.so.bpmn.core.UrnPropertiesReader
+
+public class QueryJobStatus extends AbstractServiceTaskProcessor{
+ private static final Logger logger = LoggerFactory.getLogger(QueryJobStatus.class)
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+
+ public void preProcessRequest(DelegateExecution execution) {
+ logger.debug("Start preProcessRequest")
+
+ try{
+ String requestId = execution.getVariable("msoRequestId")
+ logger.debug("RequestId :" + requestId)
+ String responseId = execution.getVariable("responseId")
+ String jobId = execution.getVariable("jobId")
+ def jsonSlurper = new JsonSlurper()
+
+ HashMap<String,?> esrInfo=jsonSlurper.parseText(execution.getVariable("esrInfo"))
+ logger.debug("esrInfo" + esrInfo.toString())
+
+ HashMap<String,?> serviceInfo=jsonSlurper.parseText(execution.getVariable("serviceInfo"))
+ logger.debug("serviceInfo" + serviceInfo.toString())
+
+ execution.setVariable("esrInfo", esrInfo)
+ execution.setVariable("serviceInfo", serviceInfo)
+
+ String nssmfEndpoint = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint",execution)
+ String endPoint = String.format("/api/rest/provMns/v1/NSS/jobs/%s", jobId)
+ String url = nssmfEndpoint + endPoint
+ execution.setVariable("NSSMF_AdapterEndpoint", url)
+
+ String payload = """
+ {
+ "responseId": "${responseId}",
+ "esrInfo": ${execution.getVariable("esrInfo") as JSONObject},
+ "serviceInfo": ${execution.getVariable("serviceInfo") as JSONObject}
+ }
+ """
+
+ execution.setVariable("NSSMF_AdapterRequest", payload.replaceAll("\\s+", ""))
+ execution.setVariable("startTime", System.currentTimeMillis())
+ logger.debug("Outgoing NSSMF_AdapterRequest: \n" + payload)
+ }catch(Exception e){
+ String msg = "Exception in QueryJobStatus.preProcessRequest " + ex.getMessage()
+ logger.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug("exit preProcessRequest")
+ }
+
+ public void checkJobStatus(DelegateExecution execution) {
+ logger.debug(" *** checkJobStatus *** ")
+ def NSSMF_ResponseCode = execution.getVariable("NSSMF_ResponseCode") as Integer
+ logger.debug("NSSMF_ResponseCode:" + NSSMF_ResponseCode)
+ def NSSMF_Response = execution.getVariable("NSSMF_Response") as String
+ def status = jsonUtil.getJsonValue(NSSMF_Response, "responseDescriptor.status")
+ logger.debug("NSSMF_Response" + NSSMF_Response)
+
+ Long startTime = execution.getVariable("startTime") as Long
+ Long timeout = execution.getVariable("timeout") as Long
+ timeout = timeout == null ? 600000 : timeout * 60000
+
+ if(NSSMF_Response != null) {
+ if (status.equalsIgnoreCase("processing") && (System.currentTimeMillis() - startTime) > timeout) {
+ handleTimeOut(execution)
+ }
+ else if(status.equalsIgnoreCase("finished") || status.equalsIgnoreCase("failed")) {
+ execution.setVariable("JobStatusCompleted", "TRUE")
+ } else {
+ execution.setVariable("JobStatusCompleted", "FALSE")
+ }
+ } else {
+ Map<String, ?> responseDescriptorMap = new HashMap<>()
+ responseDescriptorMap.put("status","failed")
+ responseDescriptorMap.put("statusDescription","Exception while querying job status")
+ String responseDescriptor = """
+ {
+ "responseDescriptor": "${responseDescriptorMap}",
+ }
+ """
+ execution.setVariable("JobStatusCompleted", "TRUE")
+ execution.setVariable("NSSMF_Response",responseDescriptor.replaceAll("\\s+", ""))
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
+ }
+ logger.debug("exit checkJobStatus")
+ }
+
+ private handleTimeOut(DelegateExecution execution) {
+ Map<String, ?> responseDescriptorMap = new HashMap<>()
+ responseDescriptorMap.put("status","failed")
+ responseDescriptorMap.put("statusDescription","timeout")
+ String responseDescriptor = """
+ {
+ "responseDescriptor": "${responseDescriptorMap}",
+ }
+ """
+ execution.setVariable("JobStatusCompleted", "TRUE")
+ execution.setVariable("NSSMF_Response",responseDescriptor.replaceAll("\\s+", ""))
+ }
+
+ public void updateJobStatusDetails(DelegateExecution execution)
+ {
+ logger.debug("**updateJobStatusDetails**")
+ def NSSMF_Response = execution.getVariable("NSSMF_Response") as String
+ def responseDescriptor = jsonUtil.getJsonValue(NSSMF_Response, "responseDescriptor")
+ execution.setVariable("responseDescriptor",responseDescriptor)
+ logger.debug("**exit updateJobStatusDetails")
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/TnAllocateNssi.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/TnAllocateNssi.groovy
new file mode 100644
index 0000000000..3367920064
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/TnAllocateNssi.groovy
@@ -0,0 +1,339 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 com.google.gson.JsonArray
+import com.google.gson.JsonObject
+import groovy.json.JsonSlurper
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.AAIResourcesClient
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+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.db.request.beans.ResourceOperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import org.springframework.web.util.UriUtils
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class TnAllocateNssi extends AbstractServiceTaskProcessor {
+ String Prefix = "TNALLOC_"
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+ JsonSlurper jsonSlurper = new JsonSlurper()
+ ObjectMapper objectMapper = new ObjectMapper()
+ TnNssmfUtils tnNssmfUtils = new TnNssmfUtils()
+ private static final Logger logger = LoggerFactory.getLogger(TnAllocateNssi.class)
+
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug("Start preProcessRequest")
+ execution.setVariable("prefix", Prefix)
+ String msg = ""
+
+ try {
+ execution.setVariable("startTime", System.currentTimeMillis())
+
+ msg = tnNssmfUtils.getExecutionInputParams(execution)
+ logger.debug("Allocate TN NSSI input parameters: " + msg)
+
+ tnNssmfUtils.setSdncCallbackUrl(execution, true)
+ logger.debug("SDNC Callback URL: " + execution.getVariable("sdncCallbackUrl"))
+
+ String additionalPropJsonStr = execution.getVariable("sliceParams")
+
+ String tnNssiId = execution.getVariable("serviceInstanceID")
+ if (isBlank(tnNssiId)) {
+ tnNssiId = UUID.randomUUID().toString()
+ }
+
+ String operationId = UUID.randomUUID().toString()
+ execution.setVariable("operationId", operationId)
+
+ logger.debug("Generate new TN NSSI ID:" + tnNssiId)
+ tnNssiId = UriUtils.encode(tnNssiId, "UTF-8")
+ execution.setVariable("sliceServiceInstanceId", tnNssiId)
+
+ String sliceServiceInstanceName = execution.getVariable("servicename")
+ execution.setVariable("sliceServiceInstanceName", sliceServiceInstanceName)
+
+ //additional properties
+ String sliceProfile = jsonUtil.getJsonValue(additionalPropJsonStr, "sliceProfile")
+ if (isBlank(sliceProfile)) {
+ msg = "Input sliceProfile is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("sliceProfile", sliceProfile)
+ }
+
+ String transportSliceNetworks = jsonUtil.getJsonValue(additionalPropJsonStr, "transportSliceNetworks")
+ if (isBlank(transportSliceNetworks)) {
+ msg = "Input transportSliceNetworks is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("transportSliceNetworks", transportSliceNetworks)
+ }
+ logger.debug("transportSliceNetworks: " + transportSliceNetworks)
+
+ String nsiInfoStr = jsonUtil.getJsonValue(additionalPropJsonStr, "nsiInfo")
+ if (isBlank(nsiInfoStr)) {
+ msg = "Input nsiInfo is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable("nsiInfo", nsiInfoStr)
+ }
+
+ //nsiId is passed in from caller bpmn
+ //String nsiIdStr = jsonUtil.getJsonValue(nsiInfo, "nsiId")
+ //execution.setVariable("nsiId", nsiIdStr)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug("Finish preProcessRequest")
+ }
+
+
+ void prepareDecomposeService(DelegateExecution execution) {
+ logger.debug("Start prepareDecomposeService")
+ String msg = ""
+ String modelUuid = execution.getVariable("modelUuid")
+ if (isBlank(modelUuid)) {
+ msg = "Input modelUuid is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ if (isBlank(modelInvariantUuid)) {
+ msg = "Input modelInvariantUuid is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelUuid}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("ssServiceModelInfo", serviceModelInfo)
+
+ logger.debug("Finish prepareDecomposeService")
+ }
+
+ void processDecomposition(DelegateExecution execution) {
+ logger.debug("Start processDecomposition")
+
+ ServiceDecomposition tnNsstServiceDecomposition = execution.getVariable("tnNsstServiceDecomposition")
+ logger.debug("tnNsstServiceDecomposition : " + tnNsstServiceDecomposition.toString())
+ //TN NSST decomposition
+ String tnModelVersion = tnNsstServiceDecomposition.getModelInfo().getModelVersion()
+ String tnModelName = tnNsstServiceDecomposition.getModelInfo().getModelName()
+ List<ServiceProxy> serviceProxyList = tnNsstServiceDecomposition.getServiceProxy()
+ List<String> nsstInfoList = new ArrayList<>()
+ for (ServiceProxy serviceProxy : serviceProxyList) {
+ String nsstModelUuid = serviceProxy.getModelInfo().getModelUuid()
+ String nsstModelInvariantUuid = serviceProxy.getModelInfo().getModelInvariantUuid()
+ String name = serviceProxy.getModelInfo().getModelName()
+ String nsstServiceModelInfo = """{
+ "UUID":"${nsstModelUuid}",
+ "invariantUUID":"${nsstModelInvariantUuid}",
+ "name":"${name}"
+ }"""
+ nsstInfoList.add(nsstServiceModelInfo)
+ }
+ int currentIndex = 0
+ int maxIndex = nsstInfoList.size()
+ if (maxIndex < 1) {
+ String msg = "Exception in TN NSST processDecomposition. There is no NSST associated with TN NSST "
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ execution.setVariable("tnNsstInfoList", nsstInfoList)
+ execution.setVariable("tnModelVersion", tnModelVersion)
+ execution.setVariable("tnModelName", tnModelName)
+ execution.setVariable("currentIndex", currentIndex)
+ execution.setVariable("maxIndex", maxIndex)
+
+ logger.debug("End processDecomposition")
+ }
+
+ void prepareOofSelection(DelegateExecution execution) {
+ logger.debug("Start prepareOofSelection")
+
+ String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
+ logger.debug("get NSSI option OOF Url: " + urlString)
+ //build oof request body
+ String requestId = execution.getVariable("msoRequestId")
+ String messageType = "NSISelectionResponse"
+ Map<String, Object> profileInfo = objectMapper.readValue(execution.getVariable("sliceProfile"), Map.class)
+ String modelUuid = execution.getVariable("modelUuid")
+ String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
+ String modelName = execution.getVariable("tnModelName")
+ String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
+ List<String> nsstInfoList = objectMapper.readValue(execution.getVariable("nsstInfoList"), List.class)
+ JsonArray capabilitiesList = new JsonArray()
+
+ execution.setVariable("nssiSelection_Url", "/api/oof/selection/nsi/v1")
+ execution.setVariable("nssiSelection_messageType", messageType)
+ execution.setVariable("nssiSelection_correlator", requestId)
+ execution.setVariable("nssiSelection_timeout", timeout)
+ String oofRequest = buildSelectTnNssiRequest(requestId, messageType, modelUuid, modelInvariantUuid,
+ modelName, profileInfo, nsstInfoList, capabilitiesList, false)
+ execution.setVariable("nssiSelection_oofRequest", oofRequest)
+
+ logger.debug("Finish prepareOofSelection")
+ }
+
+ String buildSelectTnNssiRequest(String requestId, String messageType, String UUID, String invariantUUID,
+ String name, Map<String, Object> profileInfo,
+ List<String> nsstInfoList, JsonArray capabilitiesList, Boolean preferReuse) {
+
+ def transactionId = requestId
+ logger.debug("transactionId is: " + transactionId)
+ String correlator = requestId
+ String callbackUrl = UrnPropertiesReader.getVariable("mso.adapters.oof.callback.endpoint") + "/" + messageType + "/" + correlator
+ ObjectMapper objectMapper = new ObjectMapper()
+ String profileJson = objectMapper.writeValueAsString(profileInfo)
+ String nsstInfoListString = objectMapper.writeValueAsString(nsstInfoList)
+ //Prepare requestInfo object
+ JsonObject requestInfo = new JsonObject()
+ requestInfo.addProperty("transactionId", transactionId)
+ requestInfo.addProperty("requestId", requestId)
+ requestInfo.addProperty("callbackUrl", callbackUrl)
+ requestInfo.addProperty("sourceId", "SO")
+ requestInfo.addProperty("timeout", 600)
+ requestInfo.addProperty("numSolutions", 1)
+
+ //Prepare serviceInfo object
+ JsonObject ranNsstInfo = new JsonObject()
+ ranNsstInfo.addProperty("UUID", UUID)
+ ranNsstInfo.addProperty("invariantUUID", invariantUUID)
+ ranNsstInfo.addProperty("name", name)
+
+ JsonObject json = new JsonObject()
+ json.add("requestInfo", requestInfo)
+ json.add("NSTInfo", ranNsstInfo)
+ json.addProperty("serviceProfile", profileJson)
+ json.addProperty("NSSTInfo", nsstInfoListString)
+ json.add("subnetCapabilities", capabilitiesList)
+ json.addProperty("preferReuse", preferReuse)
+
+ return json.toString()
+ }
+
+ void processOofSelection(DelegateExecution execution) {
+ logger.debug(Prefix + "processOofSelection method start")
+ String oofResponse = execution.getVariable("nssiSelection_asyncCallbackResponse")
+ String requestStatus = jsonUtil.getJsonValue(oofResponse, "requestStatus")
+ if (requestStatus.equals("completed")) {
+ List<String> solution = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(oofResponse, "solutions"))
+ boolean existingNSI = jsonUtil.getJsonValue(solution.get(0), "existingNSI")
+ if (existingNSI) {
+ def sharedNSISolution = jsonUtil.getJsonValue(solution.get(0), "sharedNSISolution")
+ execution.setVariable("sharedTnNssiSolution", sharedNSISolution)
+ logger.debug("sharedTnNssiSolution from OOF " + sharedNSISolution)
+ String tnServiceInstanceId = jsonUtil.getJsonValue(solution.get(0), "sharedNSISolution.NSIId")
+ execution.setVariable("tnServiceInstanceId", tnServiceInstanceId)
+ org.onap.so.bpmn.core.domain.ServiceInstance serviceInstance = new org.onap.so.bpmn.core.domain.ServiceInstance();
+ serviceInstance.setInstanceId(tnServiceInstanceId);
+ ServiceDecomposition serviceDecomposition = execution.getVariable("tnNsstServiceDecomposition")
+ serviceDecomposition.setServiceInstance(serviceInstance);
+ execution.setVariable("tnNsstServiceDecomposition", serviceDecomposition)
+ execution.setVariable("isOofTnNssiSelected", true)
+ } else {
+ def sliceProfiles = jsonUtil.getJsonValue(solution.get(0), "newNSISolution.sliceProfiles")
+ execution.setVariable("tnConstituentSliceProfiles", sliceProfiles)
+ execution.setVariable("isOofTnNssiSelected", false)
+ logger.debug("tnConstituentSliceProfiles list from OOF " + sliceProfiles)
+ }
+ } else {
+ String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
+ logger.error("received failed status from oof " + statusMessage)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a failed Async Response from OOF : " + statusMessage)
+ }
+
+ logger.debug(Prefix + "processOofSelection method finished")
+ }
+
+ void updateAAIOrchStatus(DelegateExecution execution) {
+ logger.debug("Start updateAAIOrchStatus")
+ String sliceServiceInstanceId = execution.getVariable("sliceServiceInstanceId")
+ String orchStatus = execution.getVariable("orchestrationStatus")
+
+ try {
+ ServiceInstance si = new ServiceInstance()
+ si.setOrchestrationStatus(orchStatus)
+ AAIResourcesClient client = new AAIResourcesClient()
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, sliceServiceInstanceId)
+ client.update(uri, si)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in CreateSliceService.updateAAIOrchStatus " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ logger.debug("Finish updateAAIOrchStatus")
+ }
+
+
+ void prepareUpdateJobStatus(DelegateExecution execution,
+ String status,
+ String progress,
+ String statusDescription) {
+ String serviceId = execution.getVariable("sliceServiceInstanceId")
+ String jobId = execution.getVariable("jobId")
+ String nsiId = execution.getVariable("nsiId")
+
+ ResourceOperationStatus roStatus = new ResourceOperationStatus()
+ roStatus.setServiceId(serviceId)
+ roStatus.setOperationId(jobId)
+ roStatus.setResourceTemplateUUID(nsiId)
+ roStatus.setOperType("Allocate")
+ roStatus.setProgress(progress)
+ roStatus.setStatus(status)
+ roStatus.setStatusDescription(statusDescription)
+ requestDBUtil.prepareUpdateResourceOperationStatus(execution, status)
+ }
+
+}
+
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/TnNssmfUtils.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/TnNssmfUtils.groovy
new file mode 100644
index 0000000000..a1b883c34e
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/TnNssmfUtils.groovy
@@ -0,0 +1,244 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 org.camunda.bpm.engine.delegate.DelegateExecution
+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.json.JsonUtils
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class TnNssmfUtils {
+ private static final Logger logger = LoggerFactory.getLogger(TnNssmfUtils.class);
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ MsoUtils msoUtils = new MsoUtils()
+ SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
+
+ TnNssmfUtils() {
+ }
+
+
+ void setSdncCallbackUrl(DelegateExecution execution, boolean exceptionOnErr) {
+ setSdncCallbackUrl(execution, "sdncCallbackUrl", exceptionOnErr)
+ }
+
+ void setSdncCallbackUrl(DelegateExecution execution, String variableName, boolean exceptionOnErr) {
+ String sdncCallbackUrl = UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback', execution)
+
+ if (isBlank(sdncCallbackUrl) && exceptionOnErr) {
+ String msg = "mso.workflow.sdncadapter.callback is null"
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ execution.setVariable(variableName, sdncCallbackUrl)
+ }
+ }
+
+ String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action) {
+
+ String uuid = execution.getVariable('testReqId') // for junits
+ if (uuid == null) {
+ uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis()
+ }
+
+ def callbackURL = execution.getVariable("sdncCallbackUrl")
+ def requestId = execution.getVariable("msoRequestId")
+ def serviceId = execution.getVariable("sliceServiceInstanceId")
+ def vnfType = execution.getVariable("serviceType")
+ def vnfName = execution.getVariable("sliceServiceInstanceName")
+ def tenantId = execution.getVariable("sliceServiceInstanceId")
+ def source = execution.getVariable("sliceServiceInstanceId")
+ def vnfId = execution.getVariable("sliceServiceInstanceId")
+ def cloudSiteId = execution.getVariable("sliceServiceInstanceId")
+ def serviceModelInfo = execution.getVariable("serviceModelInfo")
+ def vnfModelInfo = execution.getVariable("serviceModelInfo")
+ def globalSubscriberId = execution.getVariable("globalSubscriberId")
+
+ String vnfNameString = """<vnf-name>${MsoUtils.xmlEscape(vnfName)}</vnf-name>"""
+ String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo)
+ String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo)
+
+ String sdncVNFParamsXml = ""
+
+ if (execution.getVariable("vnfParamsExistFlag") == true) {
+ sdncVNFParamsXml = buildSDNCParamsXml(execution)
+ } else {
+ sdncVNFParamsXml = ""
+ }
+
+ String sdncRequest =
+ """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
+ xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
+ xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
+ <sdncadapter:RequestHeader>
+ <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
+ <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
+ <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
+ <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
+ <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
+ <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
+ </sdncadapter:RequestHeader>
+ <sdncadapterworkflow:SDNCRequestData>
+ <request-information>
+ <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
+ <request-action>AllocateTnNssi</request-action>
+ <source>${MsoUtils.xmlEscape(source)}</source>
+ <notification-url/>
+ <order-number/>
+ <order-version/>
+ </request-information>
+ <service-information>
+ <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
+ <subscription-service-type>${MsoUtils.xmlEscape(serviceId)}</subscription-service-type>
+ ${serviceEcompModelInformation}
+ <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
+ <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
+ </service-information>
+ <vnf-information>
+ <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
+ <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
+ ${vnfEcompModelInformation}
+ </vnf-information>
+ <vnf-request-input>
+ ${vnfNameString}
+ <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
+ <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
+ ${sdncVNFParamsXml}
+ </vnf-request-input>
+ </sdncadapterworkflow:SDNCRequestData>
+ </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
+
+ logger.debug("sdncRequest: " + sdncRequest)
+ return sdncRequest
+ }
+
+ String buildSDNCParamsXml(DelegateExecution execution) {
+ String params = ""
+ StringBuilder sb = new StringBuilder()
+ Map<String, String> paramsMap = execution.getVariable("TNNSSMF_vnfParamsMap")
+
+ for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
+ String paramsXml
+ String key = entry.getKey();
+ String value = entry.getValue()
+ paramsXml = """<${key}>$value</$key>"""
+ params = sb.append(paramsXml)
+ }
+ return params
+ }
+
+ void validateSDNCResponse(DelegateExecution execution, String response, String method) {
+ validateSDNCResponse(execution, response, method, true)
+ }
+
+ void validateSDNCResponse(DelegateExecution execution, String response, String method, boolean exceptionOnErr) {
+ logger.debug("STARTED ValidateSDNCResponse Process")
+
+ String msg
+
+ String prefix = execution.setVariable("prefix")
+ if (isBlank(prefix)) {
+ if (exceptionOnErr) {
+ msg = "validateSDNCResponse: prefix is null"
+ logger.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+ return
+ }
+
+ WorkflowException workflowException = execution.getVariable("WorkflowException")
+ boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
+
+ logger.debug("workflowException: " + workflowException)
+
+ sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
+
+ String sdncResponse = response
+ if (execution.getVariable(prefix + 'sdncResponseSuccess') == true) {
+ logger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse)
+ RollbackData rollbackData = execution.getVariable("rollbackData")
+
+ if (method.equals("allocate")) {
+ rollbackData.put("VNFMODULE", "rollbackSDNCRequestAllocate", "true")
+ } else if (method.equals("deallocate")) {
+ rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeallocate", "true")
+ } else if (method.equals("activate")) {
+ rollbackData.put("VNFMODULE", "rollbackSDNCRequestActivate", "true")
+ } else if (method.equals("deactivate")) {
+ rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeactivate", "true")
+ } else if (method.equals("modify")) {
+ rollbackData.put("VNFMODULE", "rollbackSDNCRequestModify", "true")
+ }
+ execution.setVariable("rollbackData", rollbackData)
+ } else {
+ if (exceptionOnErr) {
+ msg = "validateSDNCResponse: bad Response from SDNC Adapter for " + method + " SDNC Call."
+ logger.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+ }
+
+ logger.debug("COMPLETED ValidateSDNCResponse Process")
+ }
+
+ String getExecutionInputParams(DelegateExecution execution) {
+ String res = "msoRequestId=" + execution.getVariable("msoRequestId") +
+ ", modelInvariantUuid=" + execution.getVariable("modelInvariantUuid") +
+ ", modelUuid=" + execution.getVariable("modelUuid") +
+ ", serviceInstanceID=" + execution.getVariable("serviceInstanceID") +
+ ", operationType=" + execution.getVariable("operationType") +
+ ", globalSubscriberId=" + execution.getVariable("globalSubscriberId") +
+ ", dummyServiceId=" + execution.getVariable("dummyServiceId") +
+ ", nsiId=" + execution.getVariable("nsiId") +
+ ", networkType=" + execution.getVariable("networkType") +
+ ", subscriptionServiceType=" + execution.getVariable("subscriptionServiceType") +
+ ", jobId=" + execution.getVariable("jobId") +
+ ", sliceParams=" + execution.getVariable("sliceParams") +
+ ", servicename=" + execution.getVariable("servicename")
+
+ return res
+ }
+
+ String getFirstSnssaiFromSliceProfile(String sliceProfileStr) {
+ String snssaiListStr = jsonUtil.getJsonValue(sliceProfileStr, "snssaiList")
+ String snssai = jsonUtil.StringArrayToList(snssaiListStr).get(0)
+
+ return snssai
+ }
+
+ String getFirstPlmnIdFromSliceProfile(String sliceProfileStr) {
+ String plmnListStr = jsonUtil.getJsonValue(sliceProfileStr, "plmnIdList")
+ String res = jsonUtil.StringArrayToList(plmnListStr).get(0)
+
+ return res
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSliceSubnetTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSliceSubnetTest.groovy
new file mode 100644
index 0000000000..adb83e7714
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSliceSubnetTest.groovy
@@ -0,0 +1,68 @@
+package org.onap.so.bpmn.infrastructure.scripts
+
+import static org.junit.Assert.*
+
+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
+
+class ActivateSliceSubnetTest {
+ @Before
+ void init() throws IOException {
+ super.init("ActivateSliceSubnet")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ public void testPreProcessRequest() {
+ when(mockExecution.getVariable("bpmnRequest")).thenReturn("""
+ {
+ "serviceInstanceID": "NSSI-C-001-HDBNJ-NSSMF-01-A-ZX ",
+ "networkType": "an/cn/tn",
+ "globalSubscriberId": "5GCustomer",
+ "subscriptionServiceType": "5G",
+ "additionalProperties": {
+ "nsiInfo": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "nsiName": "eMBB-001"
+ },
+ }
+}
+""".replaceAll("\\s+", ""))
+ when(mockExecution.getVariable("mso-request-id")).thenReturn("edb08d97-e0f9-4c71-840a-72080d7be42e")
+ when(mockExecution.getVariable("requestAction")).thenReturn("activateInstance")
+ ActivateSliceSubnet sliceSubnet = new ActivateSliceSubnet()
+ sliceSubnet.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(captor.capture() as String, captor.capture())
+ List<ExecutionEntity> values = captor.getAllValues()
+ assertNotNull(values)
+ }
+
+ @Test
+ void testPrepareInitOperationStatus() {
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("54321")
+ when(mockExecution.getVariable("jobId")).thenReturn("54321")
+ when(mockExecution.getVariable("nsiId")).thenReturn("11111")
+ ActivateSliceSubnet sliceSubnet = new ActivateSliceSubnet()
+ sliceSubnet.prepareInitOperationStatus(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("initResourceOperationStatus"), captor.capture())
+ String res = captor.getValue()
+ assertNotNull(res)
+ }
+
+
+ @Test
+ void testSendSyncResponse() {
+ when(mockExecution.getVariable("jobId")).thenReturn("123456")
+ ActivateSliceSubnet sliceSubnet = new ActivateSliceSubnet()
+ sliceSubnet.sendSyncResponse(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sentSyncResponse"), captor.capture())
+ def updateVolumeGroupRequest = captor.getValue()
+ assertEquals(updateVolumeGroupRequest, true)
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/AllocateSliceSubnetTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/AllocateSliceSubnetTest.groovy
new file mode 100644
index 0000000000..a9b4e095e7
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/AllocateSliceSubnetTest.groovy
@@ -0,0 +1,135 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2020, Wipro Limited.
+ #
+ # 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 static org.junit.Assert.*
+import static org.mockito.Mockito.times
+import static org.mockito.Mockito.when
+
+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
+
+
+class AllocateSliceSubnetTest extends MsoGroovyTest {
+
+ @Before
+ void init() throws IOException {
+ super.init("AllocateSliceSubnet")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ public void testPreProcessRequest() {
+ when(mockExecution.getVariable("serviceInstanceID")).thenReturn("12345")
+ when(mockExecution.getVariable("bpmnRequest")).thenReturn("""
+ {
+ "name": "eMBB-001",
+ "modelInvariantUuid": "NSST-C-001-HDBNJ-NSSMF-01-A-ZX",
+ "modelUuid": "NSST-C-001-HDBNJ-NSSMF-01-A-ZX-UUID",
+ "globalSubscriberId": "5GCustomer",
+ "subscriptionServiceType": "5G",
+ "networkType": "an/cn/tn",
+ "additionalProperties": {
+ "sliceProfile": {
+ "snssaiList": [
+ "001-100001"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098",
+ "plmnIdList": [
+ "460-00",
+ "460-01"
+ ],
+ "perfReq": {
+ "perfReqEmbbList ": [
+ {
+ "activityFactor": 50
+ }
+ ]
+ },
+ "maxNumberofUEs": 200,
+ "coverageAreaTAList": [
+ "1",
+ "2",
+ "3",
+ "4"
+ ],
+ "latency": 2,
+ "resourceSharingLevel": "non-shared"
+ },
+ "endPoints": [
+ {
+ "nodeId": "",
+ "additionalInfo": {
+ "xxx": "xxx"
+ }
+ }
+ ],
+ "nsiInfo": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "nsiName": "eMBB-001"
+ },
+ "scriptName": "AN1"
+ }
+}
+""".replaceAll("\\s+", ""))
+ when(mockExecution.getVariable("mso-request-id")).thenReturn("edb08d97-e0f9-4c71-840a-72080d7be42e")
+ AllocateSliceSubnet sliceSubnet = new AllocateSliceSubnet()
+ sliceSubnet.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(captor.capture() as String, captor.capture())
+ List<ExecutionEntity> values = captor.getAllValues()
+ assertNotNull(values)
+ }
+
+ @Test
+ void testPrepareInitOperationStatus() {
+
+ when(mockExecution.getVariable("dummyServiceId")).thenReturn("12345")
+ when(mockExecution.getVariable("jobId")).thenReturn("54321")
+
+ when(mockExecution.getVariable("nsiId")).thenReturn("11111")
+
+ AllocateSliceSubnet sliceSubnet = new AllocateSliceSubnet()
+
+ sliceSubnet.prepareInitOperationStatus(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("initResourceOperationStatus"), captor.capture())
+ String res = captor.getValue()
+ assertNotNull(res)
+ }
+
+
+ @Test
+ void testSendSyncResponse() {
+ when(mockExecution.getVariable("jobId")).thenReturn("123456")
+ AllocateSliceSubnet sliceSubnet = new AllocateSliceSubnet()
+ sliceSubnet.sendSyncResponse(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sentSyncResponse"), captor.capture())
+ def updateVolumeGroupRequest = captor.getValue()
+ assertEquals(updateVolumeGroupRequest, true)
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceServiceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceServiceTest.groovy
index 46f061d89c..01f4d6b97b 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceServiceTest.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSliceServiceTest.groovy
@@ -160,45 +160,6 @@ class CreateSliceServiceTest extends MsoGroovyTest {
}
@Test
- void testPrepareDecomposeService() {
- when(mockExecution.getVariable("uuiRequest")).thenReturn(uuiRequest)
- when(mockExecution.getVariable("serviceProfile")).thenReturn(serviceProfile)
- CreateSliceService sliceService = new CreateSliceService()
- sliceService.prepareDecomposeService(mockExecution)
-
- String serviceModelInfoExcept = """{
- "modelInvariantUuid":"123456",
- "modelUuid":"123456",
- "modelVersion":""
- }"""
- Mockito.verify(mockExecution, times(1)).setVariable(eq("ssServiceModelInfo"), captor.capture())
- String serviceModelInfo = captor.getValue()
- assertEquals(serviceModelInfoExcept.replaceAll("\\s+", ""),
- serviceModelInfo.replaceAll("\\s+", ""))
- }
-
- @Test
- void testProcessDecomposition() {
- when(mockExecution.getVariable("uuiRequest")).thenReturn(uuiRequest)
- when(mockExecution.getVariable("serviceProfile")).thenReturn(serviceProfile)
- when(mockExecution.getVariable("nstSolution")).thenReturn(nstSolution)
-
- CreateSliceService sliceService = new CreateSliceService()
- sliceService.processDecomposition(mockExecution)
-
- Mockito.verify(mockExecution, times(1)).setVariable(eq("subscriptionServiceType"), captor.capture())
- assertEquals(captor.getValue(), "5G")
- Mockito.verify(mockExecution, times(1)).setVariable(eq("serviceType"), captor.capture())
- assertEquals(captor.getValue(), "embb")
- Mockito.verify(mockExecution, times(1)).setVariable(eq("resourceSharingLevel"), captor.capture())
- assertEquals(captor.getValue(), "shared")
- Mockito.verify(mockExecution, times(1)).setVariable(eq("nstModelUuid"), captor.capture())
- assertEquals(captor.getValue(), "aaaaaa")
- Mockito.verify(mockExecution, times(1)).setVariable(eq("nstModelInvariantUuid"), captor.capture())
- assertEquals(captor.getValue(), "bbbbbb")
- }
-
- @Test
void testPrepareCreateOrchestrationTask() {
when(mockExecution.getVariable("serviceInstanceId")).thenReturn("123456")
when(mockExecution.getVariable("serviceInstanceName")).thenReturn("test")
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeAllocateSliceSubnetTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeAllocateSliceSubnetTest.groovy
new file mode 100644
index 0000000000..a254a90576
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeAllocateSliceSubnetTest.groovy
@@ -0,0 +1,72 @@
+package org.onap.so.bpmn.infrastructure.scripts
+
+import static org.junit.Assert.*
+
+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
+
+class DeAllocateSliceSubnetTest {
+
+ @Before
+ void init() throws IOException {
+ super.init("DeAllocateSliceSubnet")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ public void testPreProcessRequest() {
+ when(mockExecution.getVariable("bpmnRequest")).thenReturn("""
+ {
+ "serviceInstanceID": "NSSI-C-001-HDBNJ-NSSMF-01-A-ZX ",
+ "networkType": "an/cn/tn",
+ "globalSubscriberId": "5GCustomer",
+ "subscriptionServiceType": "5G",
+ "additionalProperties": {
+ "snssaiList": [
+ "001-100001"
+ ],
+ "scriptName": "AN1",
+ "nsiInfo": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "nsiName": "eMBB-001"
+ },
+ }
+}
+""".replaceAll("\\s+", ""))
+ when(mockExecution.getVariable("mso-request-id")).thenReturn("edb08d97-e0f9-4c71-840a-72080d7be42e")
+ DeAllocateSliceSubnet sliceSubnet = new DeAllocateSliceSubnet()
+ sliceSubnet.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(captor.capture() as String, captor.capture())
+ List<ExecutionEntity> values = captor.getAllValues()
+ assertNotNull(values)
+ }
+
+ @Test
+ void testPrepareInitOperationStatus() {
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("54321")
+ when(mockExecution.getVariable("jobId")).thenReturn("54321")
+ when(mockExecution.getVariable("nsiId")).thenReturn("11111")
+ DeAllocateSliceSubnet sliceSubnet = new DeAllocateSliceSubnet()
+ sliceSubnet.prepareInitOperationStatus(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("initResourceOperationStatus"), captor.capture())
+ String res = captor.getValue()
+ assertNotNull(res)
+ }
+
+
+ @Test
+ void testSendSyncResponse() {
+ when(mockExecution.getVariable("jobId")).thenReturn("123456")
+ DeAllocateSliceSubnet sliceSubnet = new DeAllocateSliceSubnet()
+ sliceSubnet.sendSyncResponse(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sentSyncResponse"), captor.capture())
+ def updateVolumeGroupRequest = captor.getValue()
+ assertEquals(updateVolumeGroupRequest, true)
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateCoreNSSITest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateCoreNSSITest.groovy
new file mode 100644
index 0000000000..a39ca04d71
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateCoreNSSITest.groovy
@@ -0,0 +1,631 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Tech Mahindra
+ * ================================================================================
+ * 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 static org.junit.Assert.*
+
+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.onap.so.bpmn.common.scripts.MsoGroovyTest
+import org.slf4j.Logger
+import org.mockito.Mockito
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+
+import static org.mockito.Mockito.spy
+import static org.mockito.Mockito.times
+import static org.mockito.Mockito.verify
+import static org.mockito.Mockito.when
+import static org.mockito.ArgumentMatchers.eq
+
+import javax.ws.rs.NotFoundException
+
+class DoActivateCoreNSSITest extends MsoGroovyTest {
+
+ DoActivateCoreNSSI doActivate = new DoActivateCoreNSSI()
+ @Before
+ void init() throws IOException {
+ super.init("DoActivateCoreNSSI")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest(){
+
+ setUpMockdataFromCommonActivateSliceSubnet()
+ doActivate.preProcessRequest(mockExecution)
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("oStatus"), captor.capture())
+ def statusValue = captor.getValue()
+ assertEquals("deactivated", statusValue)
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sNssai"), captor.capture())
+ def sNssai = captor.getValue()
+ assertEquals("01-5B179BD4", sNssai)
+
+ Mockito.verify(mockExecution,times(3)).setVariable(captor.capture() as String, captor.capture())
+ List<ExecutionEntity> values = captor.getAllValues()
+ assertNotNull(values)
+ }
+
+ @Test
+ void testGetNetworkInstanceWithSPInstanceAssociatedWithNssiId(){
+
+ setUpMockdataFromCommonActivateSliceSubnet()
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ DoActivateCoreNSSI obj = spy(DoActivateCoreNSSI.class)
+ when(obj.getAAIClient()).thenReturn(client)
+ AAIResourceUri resourceUri1 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "NSSI-C-7Q4-HDBNJ-NSSMF-01-A-ZX")
+ when(client.exists(resourceUri1)).thenReturn(true)
+ AAIResultWrapper wrapper1 = new AAIResultWrapper(mockQuerySliceServiceReturn())
+ when(client.get(resourceUri1, NotFoundException.class)).thenReturn(wrapper1)
+
+ //networkServiceInstanceId
+ when(mockExecution.getVariable("networkServiceInstanceId")).thenReturn("206535e7-77c9-4036-9387-3f1cf57b4379")
+
+ AAIResourceUri resourceUri2 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "206535e7-77c9-4036-9387-3f1cf57b4379")
+ when(client.exists(resourceUri2)).thenReturn(true)
+ AAIResultWrapper wrapper2 = new AAIResultWrapper(mockQueryNS())
+ when(client.get(resourceUri2, NotFoundException.class)).thenReturn(wrapper2)
+
+ //Check Vnf
+ when(mockExecution.getVariable("vnfId")).thenReturn("eeb66c6f-36bd-47ad-8294-48f46b1aa912")
+ AAIResourceUri resourceUri3 = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "eeb66c6f-36bd-47ad-8294-48f46b1aa912")
+ when(client.exists(resourceUri3)).thenReturn(true)
+ AAIResultWrapper wrapper3 = new AAIResultWrapper(mockQueryVnf())
+ when(client.get(resourceUri3, NotFoundException.class)).thenReturn(wrapper3)
+
+
+ //Allotted Resources-1
+ //when(mockExecution.getVariable("vnfId")).thenReturn("eeb66c6f-36bd-47ad-8294-48f46b1aa912")
+ AAIResourceUri resourceUri4 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "0d3d3cce-46a8-486d-816a-954e71697c4e")
+ when(client.exists(resourceUri4)).thenReturn(true)
+ AAIResultWrapper wrapper4 = new AAIResultWrapper(mockServiceProfile1())
+ when(client.get(resourceUri4, NotFoundException.class)).thenReturn(wrapper4)
+
+ //Allotted Resources-2
+ //when(mockExecution.getVariable("vnfId")).thenReturn("eeb66c6f-36bd-47ad-8294-48f46b1aa912")
+ AAIResourceUri resourceUri5 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "1c7046f2-a5a3-4d7f-9da8-388ee641a795")
+ when(client.exists(resourceUri5)).thenReturn(true)
+ AAIResultWrapper wrapper5 = new AAIResultWrapper(mockServiceProfile2())
+ when(client.get(resourceUri5, NotFoundException.class)).thenReturn(wrapper5)
+
+ obj.getNetworkInstanceWithSPInstanceAssociatedWithNssiId(mockExecution)
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("networkServiceInstanceId"), captor.capture())
+ assertEquals("206535e7-77c9-4036-9387-3f1cf57b4379", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("networkServiceInstanceName"), captor.capture())
+ assertEquals("nsi_DemoEmbb", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("networkServiceModelInvariantUuid"), captor.capture())
+ assertEquals("848c5656-5594-4d41-84bb-7afc7c64765c", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("owningEntityId"), captor.capture())
+ assertEquals("OE-generic", captor.getValue())
+
+ //VnfId
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("vnfId"), captor.capture())
+ assertEquals("eeb66c6f-36bd-47ad-8294-48f46b1aa912", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("snssaiAndOrchStatusList"), captor.capture())
+ List<Map<String, Object>> snssaiList = new ArrayList<>()
+ Map<String, Object> snssaiMap = new LinkedHashMap<>()
+ snssaiMap.put("snssai", "01-5C83F071")
+ snssaiMap.put("status", "activated")
+ snssaiList.add(snssaiMap)
+ Map<String, Object> snssaiMap1 = new LinkedHashMap<>()
+ snssaiMap1.put("snssai", "01-5B179BD4")
+ snssaiMap1.put("status", "activated")
+ snssaiList.add(snssaiMap1)
+ assertEquals(snssaiList, captor.getValue())
+
+ //Verify Project
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("projectName"), captor.capture())
+ assertEquals("Project-generic", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("tenantId"), captor.capture())
+ assertEquals("3d5819f1542e4ef9a4ccb0bcb278ca10", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("cloudOwner"), captor.capture())
+ assertEquals("k8scloudowner", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("lcpCloudRegionId"), captor.capture())
+ assertEquals("k8sregion", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("platformName"), captor.capture())
+ assertEquals("test", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("lineOfBusinessName"), captor.capture())
+ assertEquals("LOB-Demonstration", captor.getValue())
+
+ }
+
+ @Test
+ void testPrepareVnfInstanceParamsJson() {
+ List<Map<String, Object>> snssaiList = new ArrayList<>()
+ Map<String, Object> snssaiMap = new LinkedHashMap<>()
+ snssaiMap.put("snssai", "01-5C83F071")
+ snssaiMap.put("status", "activated")
+ snssaiList.add(snssaiMap)
+ Map<String, Object> snssaiMap1 = new LinkedHashMap<>()
+ snssaiMap1.put("snssai", "01-5B179BD4")
+ snssaiMap1.put("status", "activated")
+ snssaiList.add(snssaiMap1)
+
+ when(mockExecution.getVariable("snssaiAndOrchStatusList")).thenReturn(snssaiList)
+
+ String returnedJsonAsString= doActivate.prepareVnfInstanceParamsJson(mockExecution)
+
+ String expectedJsonAsString = """{supportedNssai={"sNssai":[{"snssai":"01-5C83F071","status":"activated"},{"snssai":"01-5B179BD4","status":"activated"}]}}"""
+ assertEquals(expectedJsonAsString, returnedJsonAsString)
+ }
+
+
+ String mockQueryNS() {
+ return """
+ {
+ "service-instance-id": "206535e7-77c9-4036-9387-3f1cf57b4379",
+ "service-instance-name": "nsi_DemoEmbb",
+ "environment-context": "General_Revenue-Bearing",
+ "workload-context": "Production",
+ "model-invariant-id": "848c5656-5594-4d41-84bb-7afc7c64765c",
+ "model-version-id": "2de92587-3395-44e8-bb2c-b9529747e580",
+ "resource-version": "1599228110527",
+ "selflink": "restconf/config/GENERIC-RESOURCE-API:services/service/206535e7-77c9-4036-9387-3f1cf57b4379/service-data/service-topology/",
+ "orchestration-status": "Assigned",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "owning-entity",
+ "relationship-label": "org.onap.relationships.inventory.BelongsTo",
+ "related-link": "/aai/v19/business/owning-entities/owning-entity/OE-generic",
+ "relationship-data": [{
+ "relationship-key": "owning-entity.owning-entity-id",
+ "relationship-value": "OE-generic"
+ }]
+ }, {
+ "related-to": "generic-vnf",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/network/generic-vnfs/generic-vnf/eeb66c6f-36bd-47ad-8294-48f46b1aa912",
+ "relationship-data": [{
+ "relationship-key": "generic-vnf.vnf-id",
+ "relationship-value": "eeb66c6f-36bd-47ad-8294-48f46b1aa912"
+ }],
+ "related-to-property": [{
+ "property-key": "generic-vnf.vnf-name",
+ "property-value": "vfwuctest 0"
+ }]
+ }, {
+ "related-to": "project",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/projects/project/Project-generic",
+ "relationship-data": [{
+ "relationship-key": "project.project-name",
+ "relationship-value": "Project-generic"
+ }]
+ }]
+ }
+}
+ """
+ }
+
+ String mockQueryVnf() {
+
+ return """
+ {
+ "vnf-id": "eeb66c6f-36bd-47ad-8294-48f46b1aa912",
+ "vnf-name": "vfwuctest 0",
+ "vnf-type": "vfwuctest/null",
+ "service-id": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb",
+ "prov-status": "PREPROV",
+ "orchestration-status": "ConfigAssigned",
+ "in-maint": false,
+ "is-closed-loop-disabled": false,
+ "resource-version": "1599228155361",
+ "model-invariant-id": "1086e068-c932-4b61-ae3b-2d2eb0cbe3ec",
+ "model-version-id": "7fbb28cf-7dfc-447a-892c-4a3130b371d2",
+ "model-customization-id": "471b3188-e8f2-470b-9f4d-89e74d45445f",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "tenant",
+ "relationship-label": "org.onap.relationships.inventory.BelongsTo",
+ "related-link": "/aai/v19/cloud-infrastructure/cloud-regions/cloud-region/k8scloudowner/k8sregion/tenants/tenant/3d5819f1542e4ef9a4ccb0bcb278ca10",
+ "relationship-data": [{
+ "relationship-key": "cloud-region.cloud-owner",
+ "relationship-value": "k8scloudowner"
+ }, {
+ "relationship-key": "cloud-region.cloud-region-id",
+ "relationship-value": "k8sregion"
+ }, {
+ "relationship-key": "tenant.tenant-id",
+ "relationship-value": "3d5819f1542e4ef9a4ccb0bcb278ca10"
+ }],
+ "related-to-property": [{
+ "property-key": "tenant.tenant-name",
+ "property-value": "onap-tm5g-dev"
+ }]
+ }, {
+ "related-to": "cloud-region",
+ "relationship-label": "org.onap.relationships.inventory.LocatedIn",
+ "related-link": "/aai/v19/cloud-infrastructure/cloud-regions/cloud-region/k8scloudowner/k8sregion",
+ "relationship-data": [{
+ "relationship-key": "cloud-region.cloud-owner",
+ "relationship-value": "k8scloudowner"
+ }, {
+ "relationship-key": "cloud-region.cloud-region-id",
+ "relationship-value": "k8sregion"
+ }],
+ "related-to-property": [{
+ "property-key": "cloud-region.owner-defined-type",
+ "property-value": "OwnerType"
+ }]
+ }, {
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/business/customers/customer/Demonstration/service-subscriptions/service-subscription/vfw-k8s/service-instances/service-instance/206535e7-77c9-4036-9387-3f1cf57b4379",
+ "relationship-data": [{
+ "relationship-key": "customer.global-customer-id",
+ "relationship-value": "Demonstration"
+ }, {
+ "relationship-key": "service-subscription.service-type",
+ "relationship-value": "vfw-k8s"
+ }, {
+ "relationship-key": "service-instance.service-instance-id",
+ "relationship-value": "206535e7-77c9-4036-9387-3f1cf57b4379"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "vfw-0201"
+ }]
+ }, {
+ "related-to": "platform",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/platforms/platform/test",
+ "relationship-data": [{
+ "relationship-key": "platform.platform-name",
+ "relationship-value": "test"
+ }]
+ }, {
+ "related-to": "line-of-business",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/lines-of-business/line-of-business/LOB-Demonstration",
+ "relationship-data": [{
+ "relationship-key": "line-of-business.line-of-business-name",
+ "relationship-value": "LOB-Demonstration"
+ }]
+ }]
+ }
+}
+ """
+ }
+
+ String mockServiceProfile1() {
+ return """
+ {
+ "service-instance-id": "0d3d3cce-46a8-486d-816a-954e71697c4e",
+ "service-instance-name": "DemoEmbb2",
+ "service-role": "e2esliceprofile-service",
+ "environment-context": "01-5C83F071",
+ "model-invariant-id": "040b1b40-3120-446b-b8e3-4f21d153d11e",
+ "model-version-id": "8b7dabb3-3f27-4555-a9fe-803e862b0292",
+ "service-instance-location-id": "39-00",
+ "resource-version": "1593511782269",
+ "orchestration-status": "activated",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/4b2bdbc0-cf7e-4c50-882a-f660e3ab8520",
+ "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": "4b2bdbc0-cf7e-4c50-882a-f660e3ab8520"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "DemoEmbb"
+ }]
+ }]
+ },
+ "allotted-resources": {
+ "allotted-resource": [{
+ "id": "362e46c2-cd84-45e4-a6c1-77f4ef88328d",
+ "model-invariant-id": "e5941a50-ddb4-4f74-be03-25449ae02ddc",
+ "model-version-id": "ab171d60-c2cc-4903-ac1d-c451b647e461",
+ "resource-version": "1593511173712",
+ "type": "Allotted Resource",
+ "allotted-resource-name": "Allotted_DemoEmbb",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/ea107578-9854-4718-8145-7c7febf0de6c",
+ "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": "ea107578-9854-4718-8145-7c7febf0de6c"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "nsi_DemoEmbb"
+ }]
+ }]
+ }
+ }]
+ },
+ "slice-profiles": {
+ "slice-profile": [{
+ "profile-id": "31a83df8-5bd0-4df7-a50f-7900476b81a2",
+ "latency": 3,
+ "max-number-of-UEs": 0,
+ "coverage-area-TA-list": "Beijing;Beijing;HaidianDistrict;WanshouluStreet",
+ "ue-mobility-level": "stationary",
+ "resource-sharing-level": "0",
+ "exp-data-rate-UL": 500,
+ "exp-data-rate-DL": 2000,
+ "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": "01-5C83F071",
+ "resource-version": "1593525640617"
+ }]
+ }
+}
+
+ """
+ }
+
+ String mockServiceProfile2() {
+ return """
+ {
+ "service-instance-id": "1c7046f2-a5a3-4d7f-9da8-388ee641a795",
+ "service-instance-name": "DemoEmbb",
+ "service-role": "e2esliceprofile-service",
+ "environment-context": "01-5B179BD4",
+ "model-invariant-id": "040b1b40-3120-446b-b8e3-4f21d153d12e",
+ "model-version-id": "8b7dabb3-3f27-4555-a9fe-803e862b0282",
+ "service-instance-location-id": "39-00",
+ "resource-version": "1593511782169",
+ "orchestration-status": "activated",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/4b2bdbc0-cf7e-4c50-882a-f660e3ab8520",
+ "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": "4b2bdbc0-cf7e-4c50-882a-f660e3ab8520"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "DemoEmbb"
+ }]
+ }]
+ },
+ "allotted-resources": {
+ "allotted-resource": [{
+ "id": "362e46c2-cd84-45e4-a6c1-77f4ef88328d",
+ "model-invariant-id": "e5941a50-ddb4-4f74-be03-25449ae02ddc",
+ "model-version-id": "ab171d60-c2cc-4903-ac1d-c451b647e461",
+ "resource-version": "1593511173712",
+ "type": "Allotted Resource",
+ "allotted-resource-name": "Allotted_DemoEmbb",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/ea107578-9854-4718-8145-7c7febf0de6c",
+ "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": "ea107578-9854-4718-8145-7c7febf0de6c"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "nsi_DemoEmbb"
+ }]
+ }]
+ }
+ }]
+ },
+ "slice-profiles": {
+ "slice-profile": [{
+ "profile-id": "b86df550-9d70-452b-a5a9-eb8823417255",
+ "latency": 6,
+ "max-number-of-UEs": 0,
+ "coverage-area-TA-list": "Beijing;Beijing;HaidianDistrict;WanshouluStreet",
+ "ue-mobility-level": "stationary",
+ "resource-sharing-level": "0",
+ "exp-data-rate-UL": 500,
+ "exp-data-rate-DL": 1000,
+ "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": "01-5B179BD4",
+ "resource-version": "1593511356725"
+ }]
+ }
+}
+ """
+ }
+
+ String mockQuerySliceServiceReturn(){
+ String expect =
+ """{
+ "service-instance-id": "NSSI-C-7Q4-HDBNJ-NSSMF-01-A-ZX",
+ "service-instance-name": "nssi_DemoEmbb",
+ "service-role": "nssi",
+ "environment-context": "cn",
+ "model-invariant-id": "da575e8e-0863-4172-88b3-b3a9ead67895",
+ "model-version-id": "e398c92f-27da-44b9-a717-1dbfc1bdd82e",
+ "service-instance-location-id": "39-00",
+ "resource-version": "1593525640482",
+ "orchestration-status": "activated",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/206535e7-77c9-4036-9387-3f1cf57b4379",
+ "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": "206535e7-77c9-4036-9387-3f1cf57b4379"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "nsi_DemoEmbb"
+ }]
+ },
+ {
+ "related-to": "allotted-resource",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/0d3d3cce-46a8-486d-816a-954e71697c4e/allotted-resources/allotted-resource/d63c241a-4c0b-4294-b4c3-5a57421a1769",
+ "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": "0d3d3cce-46a8-486d-816a-954e71697c4e"
+ }, {
+ "relationship-key": "allotted-resource.id",
+ "relationship-value": "d63c241a-4c0b-4294-b4c3-5a57421a1769"
+ }],
+ "related-to-property": [{
+ "property-key": "allotted-resource.description"
+ }, {
+ "property-key": "allotted-resource.allotted-resource-name",
+ "property-value": "Allotted_DemoEmbb_shared"
+ }]
+ }, {
+ "related-to": "allotted-resource",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/1c7046f2-a5a3-4d7f-9da8-388ee641a795/allotted-resources/allotted-resource/362e46c2-cd84-45e4-a6c1-77f4ef88328d",
+ "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": "1c7046f2-a5a3-4d7f-9da8-388ee641a795"
+ }, {
+ "relationship-key": "allotted-resource.id",
+ "relationship-value": "362e46c2-cd84-45e4-a6c1-77f4ef88328d"
+ }],
+ "related-to-property": [{
+ "property-key": "allotted-resource.description"
+ }, {
+ "property-key": "allotted-resource.allotted-resource-name",
+ "property-value": "Allotted_DemoEmbb"
+ }]
+ }
+ ]
+ }
+}
+ """
+ return expect
+ }
+
+ void setUpMockdataFromCommonActivateSliceSubnet() {
+
+ String bpmnRequest = """
+ {
+ "serviceInstanceID": "NSSI-C-7Q4-HDBNJ-NSSMF-01-A-ZX",
+ "networkType": "an/cn/tn",
+ "globalSubscriberId": "5GCustomer",
+ "subscriptionServiceType": "5G",
+ "additionalProperties": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "snssaiList": [
+ "01-5B179BD4"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098"
+ }
+ }
+ """
+
+ String sliceParams ="""{
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "snssaiList": [
+ "01-5B179BD4"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098"
+ }"""
+
+ when(mockExecution.getVariable("msoRequestId")).thenReturn("5ad89cf9-0569-4a93-4509-d8324321e2be")
+ when(mockExecution.getVariable("serviceInstanceID")).thenReturn("NSSI-C-7Q4-HDBNJ-NSSMF-01-A-ZX")
+ when(mockExecution.getVariable("nsiId")).thenReturn("NSI-M-001-HDBNJ-NSMF-01-A-ZX")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G")
+ when(mockExecution.getVariable("operationType")).thenReturn("deactivateInstance")
+ when(mockExecution.getVariable("jobId")).thenReturn("5ad89cf9-0569-4a93-9999-d8324321e2be")
+ when(mockExecution.getVariable("bpmnRequest")).thenReturn(bpmnRequest)
+ when(mockExecution.getVariable("sliceParams")).thenReturn(sliceParams)
+ }
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateTnNssiTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateTnNssiTest.groovy
new file mode 100644
index 0000000000..93557a48cf
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoActivateTnNssiTest.groovy
@@ -0,0 +1,178 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 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.assertNotNull
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.*
+
+class DoActivateTnNssiTest extends MsoGroovyTest {
+ @Before
+ void init() throws IOException {
+ super.init("DoActivateTnNssiTest")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest() {
+ when(mockExecution.getVariable("msoRequestId")).thenReturn("4c614769-f58a-4556-8ad9-dcd903077c82")
+ when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback")
+ when(mockExecution.getVariable("modelInvariantUuid")).thenReturn("f85cbcc0-ad74-45d7-a5a1-17c8744fdb71")
+ when(mockExecution.getVariable("modelUuid")).thenReturn("36a3a8ea-49a6-4ac8-b06c-89a54544b9b6")
+ when(mockExecution.getVariable("serviceInstanceID")).thenReturn("eb0863e9-a69b-4b17-8a56-f05ad110bef7")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("operationType")).thenReturn("opTypeTest")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("servicename")).thenReturn("5G-test")
+ when(mockExecution.getVariable("networkType")).thenReturn("5G-network")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G-service")
+ when(mockExecution.getVariable("nsiId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56")
+ when(mockExecution.getVariable("jobId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4")
+ when(mockExecution.getVariable("operationType")).thenReturn("activateInstance")
+ when(mockExecution.getVariable("sliceParams")).thenReturn(mockSliceParams())
+
+ DoActivateTnNssi obj = new DoActivateTnNssi()
+ obj.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sliceServiceInstanceId"), captor.capture())
+ String sliceServiceInstanceId = captor.getValue()
+ assertNotNull(sliceServiceInstanceId)
+ }
+
+ @Test
+ void testPreprocessSdncRequest() {
+ when(mockExecution.getVariable("msoRequestId")).thenReturn("4c614769-f58a-4556-8ad9-dcd903077c82")
+ when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback")
+ when(mockExecution.getVariable("sliceServiceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("sliceServiceInstanceName")).thenReturn("5G-service")
+ when(mockExecution.getVariable("actionType")).thenReturn("activate")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G")
+ when(mockExecution.getVariable("modelInvariantUuid")).thenReturn("f85cbcc0-ad74-45d7-a5a1-17c8744fdb71")
+ when(mockExecution.getVariable("modelUuid")).thenReturn("36a3a8ea-49a6-4ac8-b06c-89a54544b9b6")
+ when(mockExecution.getVariable("sliceParams")).thenReturn(mockSliceParams())
+ when(mockExecution.getVariable("serviceModelInfo")).thenReturn(mockServiceModelInfo())
+// JsonUtils jsonUtil = new JsonUtils()
+// String sliceProfile = jsonUtil.getJsonValue(mockSliceParams(), "sliceProfile")
+// when(mockExecution.getVariable("sliceProfile")).thenReturn(sliceProfile)
+
+ DoActivateTnNssi obj = spy(DoActivateTnNssi.class)
+
+ obj.preprocessSdncActOrDeactTnNssiRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("TNNSSMF_SDNCRequest"), captor.capture())
+ String request = captor.getValue()
+ assertNotNull(request)
+ }
+
+
+ private String mockSliceParams() {
+ String expect = """{
+ "sliceProfile": {
+ "snssaiList": [
+ "001-100001"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098",
+ "plmnIdList": [
+ "460-00",
+ "460-01"
+ ],
+ "perfReq": {
+ },
+ "coverageAreaTAList": [
+ ],
+ "latency": 2,
+ "maxBandwidth": 100,
+ "resourceSharingLevel": "non-shared"
+ },
+ "transportSliceNetworks": [
+ {
+ "connectionLinks": [
+ {
+ "transportEndpointA": "tranportEp_ID_XXX",
+ "transportEndpointB": "tranportEp_ID_YYY"
+ },
+ {
+ "transportEndpointA": "tranportEp_ID_AAA",
+ "transportEndpointB": "tranportEp_ID_BBB"
+ }
+ ]
+ },
+ {
+ "connectionLinks": [
+ {
+ "transportEndpointA": "tranportEp_ID_CCC",
+ "transportEndpointB": "tranportEp_ID_DDD"
+ },
+ {
+ "transportEndpointA": "tranportEp_ID_EEE",
+ "transportEndpointB": "tranportEp_ID_FFF"
+ }
+ ]
+ }
+ ],
+ "nsiInfo": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "nsiName": "eMBB-001"
+ },
+ "scriptName": "AN1"
+ }"""
+ return expect.replaceAll("\\\\s+", "")
+ }
+
+ private String mockSliceProfile() {
+ String expect = """{
+ "snssaiList": [
+ "001-100001"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098",
+ "plmnIdList": [
+ "460-00",
+ "460-01"
+ ],
+ "perfReq": {
+ },
+ "coverageAreaTAList": [
+ ],
+ "latency": 2,
+ "maxBandwidth": 100,
+ "resourceSharingLevel": "non-shared"
+ }"""
+ return expect.replaceAll("\\\\s+", "")
+ }
+
+ private String mockServiceModelInfo() {
+ String expect = """{
+ "modelInvariantUuid":"f85cbcc0-ad74-45d7-a5a1-17c8744fdb71",
+ "modelUuid":"36a3a8ea-49a6-4ac8-b06c-89a54544b9b6",
+ "modelVersion":""
+ }"""
+ return expect.replaceAll("\\\\s+", "")
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNSSITest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNSSITest.groovy
new file mode 100644
index 0000000000..dc7a429c2c
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNSSITest.groovy
@@ -0,0 +1,103 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Tech Mahindra
+ * ================================================================================
+ * 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 static org.junit.Assert.*
+
+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.mockito.Mockito.when
+import static org.mockito.Mockito.times
+import static org.mockito.ArgumentMatchers.eq
+
+class DoAllocateCoreNSSITest extends MsoGroovyTest {
+
+ @Before
+ void init() throws IOException {
+ super.init("DoAllocateCoreNSSI")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ public void testPreProcessRequest() {
+
+ String sliceParams="""{
+ "sliceProfile": {
+ "snssaiList": [
+ "001-100001"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098",
+ "plmnIdList": [
+ "460-00",
+ "460-01"
+ ],
+ "perfReq": {
+ "perfReqEmbbList ": [{
+ "activityFactor": 50
+ }]
+ },
+ "maxNumberofUEs": 200,
+ "coverageAreaTAList": [
+ "1",
+ "2",
+ "3",
+ "4"
+ ],
+ "latency": 2,
+ "resourceSharingLevel": "non-shared"
+ },
+ "endPoints": [{
+ "nodeId": "",
+ "additionalInfo": {
+ "xxx": "xxx"
+ }
+ },
+ {
+ "nodeId": "",
+ "additionalInfo": {
+ "xxx": "xxx"
+ }
+ }
+ ],
+ "nsiInfo": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "nsiName": "eMBB-001"
+ },
+ "scriptName": "AN1"
+}"""
+ String expected = """{"plmnIdList":["460-00","460-01"],"sliceProfileId":"ab9af40f13f721b5f13539d87484098","maxNumberofUEs":200,"latency":2,"snssaiList":["001-100001"],"perfReq":{"perfReqEmbbList ":[{"activityFactor":50}]},"coverageAreaTAList":["1","2","3","4"],"resourceSharingLevel":"non-shared"}"""
+ when(mockExecution.getVariable("sliceParams")).thenReturn(sliceParams)
+ DoAllocateCoreNSSI allocateNssi = new DoAllocateCoreNSSI()
+ allocateNssi.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sliceProfile"), captor.capture())
+ def sliceProfile = captor.getValue()
+ assertEquals(expected, sliceProfile)
+ Mockito.verify(mockExecution, times(3)).setVariable(captor.capture() as String, captor.capture())
+ }
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNonSharedSliceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNonSharedSliceTest.groovy
new file mode 100644
index 0000000000..1eddf66b86
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreNonSharedSliceTest.groovy
@@ -0,0 +1,118 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Tech Mahindra
+ * ================================================================================
+ * 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 static org.junit.Assert.*
+
+import org.junit.Before
+import org.junit.Test
+import org.mockito.ArgumentCaptor
+import org.mockito.Captor
+import org.mockito.Mockito
+import com.fasterxml.jackson.databind.ObjectMapper
+
+import static org.mockito.Mockito.when
+import static org.mockito.Mockito.times
+import static org.mockito.Mockito.eq
+
+import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+
+class DoAllocateCoreNonSharedSliceTest extends MsoGroovyTest {
+
+ @Before
+ void init() throws IOException {
+ super.init("DoAllocateCoreNonSharedSlice")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ public void testPreProcessRequest() {
+
+ String networkServiceModelInfo=""" {
+ "modelName" : "5GC-eMBB Service Proxy",
+ "modelUuid" : "b666119e-4400-47c6-a0c1-bbe050a33b47",
+ "modelInvariantUuid" : "a26327e1-4a9b-4883-b7a5-5f37dcb7405a",
+ "modelVersion" : "1.0",
+ "modelCustomizationUuid" : "cbc12c2a-67e6-4336-9236-eaf51eacdc75",
+ "modelInstanceName" : "5gcembb_proxy 0"
+ }"""
+
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("123456")
+ when(mockExecution.getVariable("networkServiceModelInfo")).thenReturn(networkServiceModelInfo)
+
+ DoAllocateCoreNonSharedSlice allocateNssi = new DoAllocateCoreNonSharedSlice()
+ allocateNssi.preProcessRequest(mockExecution)
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("networkServiceModelUuid"), captor.capture())
+ captor.getValue()
+ assertEquals("b666119e-4400-47c6-a0c1-bbe050a33b47", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("networkServiceName"), captor.capture())
+ assertEquals("5GC-eMBB", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("orchestrationStatus"), captor.capture())
+ assertEquals("created", captor.getValue())
+ Mockito.verify(mockExecution, times(4)).setVariable(captor.capture() as String, captor.capture())
+ }
+
+ @Test
+ void testPrepareServiceOrderRequest() {
+
+ String sliceProfile = "{\r\n \"snssaiList\": [ \r\n \"001-100001\"\r\n ],\r\n \"sliceProfileId\": \"ab9af40f13f721b5f13539d87484098\",\r\n \"plmnIdList\": [\r\n \"460-00\",\r\n \"460-01\"\r\n ],\r\n \"perfReq\": {\r\n \"perfReqEmbbList \": [\r\n {\r\n \"activityFactor\": 50\r\n }\r\n ]\r\n },\r\n \"maxNumberofUEs\": 200, \r\n \"coverageAreaTAList\": [ \r\n \"1\",\r\n \"2\",\r\n \"3\",\r\n \"4\"\r\n ],\r\n \"latency\": 2,\r\n \"resourceSharingLevel\": \"non-shared\" \r\n }"
+ when(mockExecution.getVariable("sliceProfile")).thenReturn(sliceProfile)
+ when(mockExecution.getVariable("serviceType")).thenReturn("5g")
+ when(mockExecution.getVariable("networkServiceName")).thenReturn("5g_embb")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("networkServiceModelUuid")).thenReturn("12345")
+
+ DoAllocateCoreNonSharedSlice allocateNssi = new DoAllocateCoreNonSharedSlice()
+ allocateNssi.prepareServiceOrderRequest(mockExecution)
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("serviceOrderRequest"), captor.capture())
+ String value = captor.getValue()
+ assertNotNull(value)
+ }
+
+ @Test
+ void testRetrieveServiceCharacteristicsAsKeyValue() {
+
+ String sliceProfile = "{\r\n \"snssaiList\": [ \r\n \"001-100001\"\r\n ],\r\n \"sliceProfileId\": \"ab9af40f13f721b5f13539d87484098\",\r\n \"plmnIdList\": [\r\n \"460-00\",\r\n \"460-01\"\r\n ],\r\n \"perfReq\": {\r\n \"perfReqEmbbList \": [\r\n {\r\n \"activityFactor\": 50\r\n }\r\n ]\r\n },\r\n \"maxNumberofUEs\": 200, \r\n \"coverageAreaTAList\": [ \r\n \"1\",\r\n \"2\",\r\n \"3\",\r\n \"4\"\r\n ],\r\n \"latency\": 2,\r\n \"resourceSharingLevel\": \"non-shared\" \r\n }"
+ Map<String, Object> ServiceCharacteristicValue = new LinkedHashMap<>()
+ Map<String, Object> ServiceCharacteristicValueObject = new LinkedHashMap<>()
+ ServiceCharacteristicValueObject.put("serviceCharacteristicValue","001-100001")
+ ServiceCharacteristicValue.put("name", "snssai")
+ ServiceCharacteristicValue.put("value", ServiceCharacteristicValueObject)
+
+ List expectedList= new ArrayList()
+ expectedList.add(ServiceCharacteristicValue)
+
+ ObjectMapper objectMapper = new ObjectMapper()
+ Map<String, Object> serviceCharacteristic = objectMapper.readValue(sliceProfile, Map.class);
+
+ DoAllocateCoreNonSharedSlice allocateNssi = new DoAllocateCoreNonSharedSlice()
+ List characteristicList=allocateNssi.retrieveServiceCharacteristicsAsKeyValue(serviceCharacteristic)
+
+ assertEquals(expectedList, characteristicList)
+ }
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreSharedSliceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreSharedSliceTest.groovy
new file mode 100644
index 0000000000..e5799eca66
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateCoreSharedSliceTest.groovy
@@ -0,0 +1,646 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 Tech Mahindra
+ * ================================================================================
+ * 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 static org.junit.Assert.*
+
+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.onap.so.bpmn.common.scripts.MsoGroovyTest
+import org.mockito.Mockito
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+
+import static org.mockito.Mockito.spy
+import static org.mockito.Mockito.times
+import static org.mockito.Mockito.verify
+import static org.mockito.Mockito.when
+import static org.mockito.ArgumentMatchers.eq
+
+import javax.ws.rs.NotFoundException
+
+class DoAllocateCoreSharedSliceTest extends MsoGroovyTest {
+
+ DoAllocateCoreSharedSlice allocate = new DoAllocateCoreSharedSlice()
+
+ @Before
+ void init() throws IOException {
+ super.init("DoAllocateCoreSharedSlice")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest(){
+
+ String solutions = """ [
+ {
+ "invariantUUID": "y7685f64-5717-4562-b3fc-2c963f66afa6",
+ "UUID": "8u785f64-5717-4562-b3fc-2c963f66afa6",
+ "NSSIName": "embb-core-ser",
+ "NSSIId": "f4485f64-5717-4562-b3fc-2c963f66afa6",
+ "matchLevel": {
+ "blob":"content"
+ }
+ }
+ ]"""
+ String sliceProfile = "{\r\n \"snssaiList\": [ \r\n \"001-100001\"\r\n ],\r\n \"sliceProfileId\": \"ab9af40f13f721b5f13539d87484098\",\r\n \"plmnIdList\": [\r\n \"460-00\",\r\n \"460-01\"\r\n ],\r\n \"perfReq\": {\r\n \"perfReqEmbbList \": [\r\n {\r\n \"activityFactor\": 50\r\n }\r\n ]\r\n },\r\n \"maxNumberofUEs\": 200, \r\n \"coverageAreaTAList\": [ \r\n \"1\",\r\n \"2\",\r\n \"3\",\r\n \"4\"\r\n ],\r\n \"latency\": 2,\r\n \"resourceSharingLevel\": \"non-shared\" \r\n }"
+
+ setUpBaseMockData()
+
+ when(mockExecution.getVariable("solutions")).thenReturn(solutions)
+ when(mockExecution.getVariable("sliceProfile")).thenReturn(sliceProfile)
+
+ allocate.preProcessRequest(mockExecution)
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("nssiId"), captor.capture())
+ def nssiId = captor.getValue()
+ assertEquals("f4485f64-5717-4562-b3fc-2c963f66afa6", nssiId)
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sNssai"), captor.capture())
+ def sNssai = captor.getValue()
+ assertEquals("001-100001", sNssai)
+
+ Mockito.verify(mockExecution,times(3)).setVariable(captor.capture() as String, captor.capture())
+ List<ExecutionEntity> values = captor.getAllValues()
+ assertNotNull(values)
+ }
+
+ @Test
+ public void tesPrepareSOMacroRequestPayload() {
+
+ String json ="{ \"serviceResources\" : {\r\n\t\"modelInfo\" : {\r\n\t\t\"modelName\" : \"MSOTADevInfra_vSAMP10a_Service\",\r\n\t\t\"modelUuid\" : \"5df8b6de-2083-11e7-93ae-92361f002671\",\r\n\t\t\"modelInvariantUuid\" : \"9647dfc4-2083-11e7-93ae-92361f002671\",\r\n\t\t\"modelVersion\" : \"1.0\"\r\n\t},\r\n\t\"serviceType\" : \"PortMirroring\",\r\n\t\"serviceRole\" : \"InfraRole\",\r\n\t\"environmentContext\" : \"Luna\",\r\n\t\"workloadContext\" : \"Oxygen\",\r\n\t\"serviceVnfs\": [\r\n\t\r\n\t\t{ \"modelInfo\" : {\r\n\t\t\t\"modelName\" : \"vSAMP10a\",\r\n\t\t\t\"modelUuid\" : \"ff2ae348-214a-11e7-93ae-92361f002671\",\r\n\t\t\t\"modelInvariantUuid\" : \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\t\t\t\"modelVersion\" : \"1.0\",\r\n\t\t\t\"modelCustomizationUuid\" : \"68dc9a92-214c-11e7-93ae-92361f002671\",\r\n\t\t\t\"modelInstanceName\" : \"vSAMP10a 1\"\r\n\t\t\t},\r\n\t\t\"toscaNodeType\" : \"VF\",\r\n\t\t\"nfFunction\" \t: null,\r\n\t\t\"nfType\" \t\t: null,\r\n\t\t\"nfRole\" \t\t: null,\r\n\t\t\"nfNamingCode\" \t: null,\r\n\t\t\"multiStageDesign\"\t\t: null,\r\n\t\t\t\"vfModules\": [\r\n\t\t\t\t{\r\n\t\t\t\t\t\"modelInfo\" : { \r\n\t\t\t\t\t\t\"modelName\" : \"NetworkFqdnTest4\",\r\n\t\t\t\t\t\t\"modelUuid\" : \"025606c1-4223-11e7-9252-005056850d2e\",\r\n\t\t\t\t\t\t\"modelInvariantUuid\" : \"06bd0a18-65c0-4418-83c7-5b0d13cba01a\",\r\n\t\t\t\t\t\t\"modelVersion\" : \"2.0\",\r\n\t\t\t\t\t\t\"modelCustomizationUuid\" : \"06bd0a18-65c0-4418-83c7-5b0d13cba01a\"\r\n\t\t\t\t\t},\t\t\"isBase\" : true,\r\n\t\t\t\t\t\"vfModuleLabel\" : \"label\",\r\n\t\t\t\t\t\"initialCount\" : 0,\r\n\t\t\t\t\t\"hasVolumeGroup\" : true\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"modelInfo\" : { \r\n\t\t\t\t\t\t\"modelName\" : \"NetworkFqdnTest3\",\r\n\t\t\t\t\t\t\"modelUuid\" : \"02560575-4223-11e7-9252-005056850d2e\",\r\n\t\t\t\t\t\t\"modelInvariantUuid\" : \"06bd0a18-65c0-4418-83c7-5b0d13cba0bb\",\r\n\t\t\t\t\t\t\"modelVersion\" : \"1.0\",\r\n\t\t\t\t\t\t\"modelCustomizationUuid\" : \"06bd0a18-65c0-4418-83c7-5b0d13cba0bb\"\r\n\t\t\t\t\t},\t\t\"isBase\" : true,\r\n\t\t\t\t\t\"vfModuleLabel\" : \"label\",\r\n\t\t\t\t\t\"initialCount\" : 0,\r\n\t\t\t\t\t\"hasVolumeGroup\" : false\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"modelInfo\" : { \r\n\t\t\t\t\t\t\"modelName\" : \"NetworkFqdnTest5\",\r\n\t\t\t\t\t\t\"modelUuid\" : \"025607e4-4223-11e7-9252-005056850d2e\",\r\n\t\t\t\t\t\t\"modelInvariantUuid\" : \"06bd0a18-65c0-4418-83c7-5b0d14cba01a\",\r\n\t\t\t\t\t\t\"modelVersion\" : \"1.0\",\r\n\t\t\t\t\t\t\"modelCustomizationUuid\" : \"06bd0a18-65c0-4418-83c7-5b0d14cba01a\"\r\n\t\t\t\t\t},\t\t\"isBase\" : false,\r\n\t\t\t\t\t\"vfModuleLabel\" : \"label\",\r\n\t\t\t\t\t\"initialCount\" : 0,\r\n\t\t\t\t\t\"hasVolumeGroup\" : false\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"modelInfo\" : { \r\n\t\t\t\t\t\t\"modelName\" : \"vSAMP10aDEV::PCM::module-2\",\r\n\t\t\t\t\t\t\"modelUuid\" : \"7774b4e4-7d37-11e7-bb31-be2e44b06b34\",\r\n\t\t\t\t\t\t\"modelInvariantUuid\" : \"93e9c1d2-7d37-11e7-bb31-be2e44b06b34\",\r\n\t\t\t\t\t\t\"modelVersion\" : \"2\",\r\n\t\t\t\t\t\t\"modelCustomizationUuid\" : \"6728bee8-7d3a-11e7-bb31-be2e44b06b34\"\r\n\t\t\t\t\t},\t\t\"isBase\" : false,\r\n\t\t\t\t\t\"vfModuleLabel\" : \"PCM\",\r\n\t\t\t\t\t\"initialCount\" : 0,\r\n\t\t\t\t\t\"hasVolumeGroup\" : true\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"modelInfo\" : { \r\n\t\t\t\t\t\t\"modelName\" : \"vSAMP10aDEV::PCM::module-1\",\r\n\t\t\t\t\t\t\"modelUuid\" : \"066de97e-253e-11e7-93ae-92361f002671\",\r\n\t\t\t\t\t\t\"modelInvariantUuid\" : \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\t\t\t\t\t\t\"modelVersion\" : \"2\",\r\n\t\t\t\t\t\t\"modelCustomizationUuid\" : \"b4ea86b4-253f-11e7-93ae-92361f002671\"\r\n\t\t\t\t\t},\t\t\"isBase\" : false,\r\n\t\t\t\t\t\"vfModuleLabel\" : \"PCM\",\r\n\t\t\t\t\t\"initialCount\" : 0,\r\n\t\t\t\t\t\"hasVolumeGroup\" : true\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"modelInfo\" : { \r\n\t\t\t\t\t\t\"modelName\" : \"vSAMP10aDEV::base::module-0\",\r\n\t\t\t\t\t\t\"modelUuid\" : \"20c4431c-246d-11e7-93ae-92361f002671\",\r\n\t\t\t\t\t\t\"modelInvariantUuid\" : \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\t\t\t\t\t\t\"modelVersion\" : \"2\",\r\n\t\t\t\t\t\t\"modelCustomizationUuid\" : \"cb82ffd8-252a-11e7-93ae-92361f002671\"\r\n\t\t\t\t\t},\t\t\"isBase\" : true,\r\n\t\t\t\t\t\"vfModuleLabel\" : \"base\",\r\n\t\t\t\t\t\"initialCount\" : 1,\r\n\t\t\t\t\t\"hasVolumeGroup\" : true\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"modelInfo\" : { \r\n\t\t\t\t\t\t\"modelName\" : \"vSAMP10a::base::module-0\",\r\n\t\t\t\t\t\t\"modelUuid\" : \"02560de2-4223-11e7-9252-005056850d2e\",\r\n\t\t\t\t\t\t\"modelInvariantUuid\" : null,\r\n\t\t\t\t\t\t\"modelVersion\" : \"2\",\r\n\t\t\t\t\t\t\"modelCustomizationUuid\" : \"MIGRATED_36e76920-ef30-4793-9979-cbd7d4b2bfc4\"\r\n\t\t\t\t\t},\t\t\"isBase\" : true,\r\n\t\t\t\t\t\"vfModuleLabel\" : \"base\",\r\n\t\t\t\t\t\"initialCount\" : 1,\r\n\t\t\t\t\t\"hasVolumeGroup\" : true\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"modelInfo\" : { \r\n\t\t\t\t\t\t\"modelName\" : \"base::module-0\",\r\n\t\t\t\t\t\t\"modelUuid\" : \"02561381-4223-11e7-9252-005056850d2e\",\r\n\t\t\t\t\t\t\"modelInvariantUuid\" : null,\r\n\t\t\t\t\t\t\"modelVersion\" : \"1\",\r\n\t\t\t\t\t\t\"modelCustomizationUuid\" : \"MIGRATED_51baae4c-b7c7-4f57-b77e-6e01acca89e5\"\r\n\t\t\t\t\t},\t\t\"isBase\" : true,\r\n\t\t\t\t\t\"vfModuleLabel\" : \"module-0\",\r\n\t\t\t\t\t\"initialCount\" : 1,\r\n\t\t\t\t\t\"hasVolumeGroup\" : false\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"modelInfo\" : { \r\n\t\t\t\t\t\t\"modelName\" : \"vSAMP10a::PCM::module-1\",\r\n\t\t\t\t\t\t\"modelUuid\" : \"02560f1b-4223-11e7-9252-005056850d2e\",\r\n\t\t\t\t\t\t\"modelInvariantUuid\" : null,\r\n\t\t\t\t\t\t\"modelVersion\" : \"1\",\r\n\t\t\t\t\t\t\"modelCustomizationUuid\" : \"MIGRATED_e9be2ed7-45b6-479c-b06e-9093899f8ce8\"\r\n\t\t\t\t\t},\t\t\"isBase\" : true,\r\n\t\t\t\t\t\"vfModuleLabel\" : \"PCM\",\r\n\t\t\t\t\t\"initialCount\" : 1,\r\n\t\t\t\t\t\"hasVolumeGroup\" : true\r\n\t\t\t\t}\r\n\t\t\t]\r\n\t\t}\r\n\t],\r\n\t\"serviceNetworks\": [],\r\n\t\"serviceAllottedResources\": [\r\n\t\t{\r\n\t\t\t\"modelInfo\" : {\r\n\t\t\t\t\"modelName\" : \"Tunnel_Xconn\",\r\n\t\t\t\t\"modelUuid\" : \"f6b7d4c6-e8a4-46e2-81bc-31cad5072842\",\r\n\t\t\t\t\"modelInvariantUuid\" : \"b7a1b78e-6b6b-4b36-9698-8c9530da14af\",\r\n\t\t\t\t\"modelVersion\" : \"1.0\",\r\n\t\t\t\t\"modelCustomizationUuid\" : \"5b9bee43-f537-4fb3-9e8b-4de9f714d28a\",\r\n\t\t\t\t\"modelInstanceName\" : \"Pri_Tunnel_Xconn 9\"\r\n\t\t\t},\r\n\t\t\t\"toscaNodeType\" : null,\r\n\t\t\t\"allottedResourceType\" : null,\r\n\t\t\t\"allottedResourceRole\" : null,\r\n\t\t\t\"providingServiceModelInvariantUuid\" : null,\r\n\t\t\t\"nfFunction\" : null,\r\n\t\t\t\"nfType\" : null,\r\n\t\t\t\"nfRole\" : null,\r\n\t\t\t\"nfNamingCode\" : null\r\n\t\t}\r\n\t],\r\n\t\"serviceConfigs\": [\r\n\t\t{\r\n\t\t\t\"modelInfo\" : {\r\n\t\t\t\t\"modelName\" : \"Mulder\",\r\n\t\t\t\t\"modelUuid\" : \"025606c1-4fff-11e7-9252-005056850d2e\",\r\n\t\t\t\t\"modelInvariantUuid\" : \"025606c1-4eee-11e7-9252-005056850d2e\",\r\n\t\t\t\t\"modelVersion\" : \"1.0\",\r\n\t\t\t\t\"modelCustomizationUuid\" : \"025606c1-4ddd-11e7-9252-005056850d2e\",\r\n\t\t\t\t\"modelInstanceName\" : \"X_FILES_001\"\r\n\t\t\t},\r\n\t\t\t\"toscaNodeType\" : \"Scully\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"modelInfo\" : {\r\n\t\t\t\t\"modelName\" : \"Krychuk\",\r\n\t\t\t\t\"modelUuid\" : \"025606c1-5fff-11e7-9252-005056850d2e\",\r\n\t\t\t\t\"modelInvariantUuid\" : \"025606c1-5eee-11e7-9252-005056850d2e\",\r\n\t\t\t\t\"modelVersion\" : \"1.0\",\r\n\t\t\t\t\"modelCustomizationUuid\" : \"025606c1-5ddd-11e7-9252-005056850d2e\",\r\n\t\t\t\t\"modelInstanceName\" : \"X_FILES_002\"\r\n\t\t\t},\r\n\t\t\t\"toscaNodeType\" : \"Skinner\"\r\n\t\t}\r\n\t]\r\n\t}}\r\n\r\n"
+ String sliceProfile = "{\r\n \"snssaiList\": [ \r\n \"001-100001\"\r\n ],\r\n \"sliceProfileId\": \"ab9af40f13f721b5f13539d87484098\",\r\n \"plmnIdList\": [\r\n \"460-00\",\r\n \"460-01\"\r\n ],\r\n \"perfReq\": {\r\n \"perfReqEmbbList \": [\r\n {\r\n \"activityFactor\": 50\r\n }\r\n ]\r\n },\r\n \"maxNumberofUEs\": 200, \r\n \"coverageAreaTAList\": [ \r\n \"1\",\r\n \"2\",\r\n \"3\",\r\n \"4\"\r\n ],\r\n \"latency\": 2,\r\n \"resourceSharingLevel\": \"non-shared\" \r\n }"
+ String vnfs="[{\"toscaNodeType\":\"VF\",\"vfModules\":[{\"initialCount\":0,\"vfModuleLabel\":\"label\",\"modelInfo\":{\"modelInvariantUuid\":\"06bd0a18-65c0-4418-83c7-5b0d13cba01a\",\"modelName\":\"NetworkFqdnTest4\",\"modelVersion\":\"2.0\",\"modelCustomizationUuid\":\"06bd0a18-65c0-4418-83c7-5b0d13cba01a\",\"modelUuid\":\"025606c1-4223-11e7-9252-005056850d2e\"},\"hasVolumeGroup\":true,\"isBase\":true},{\"initialCount\":0,\"vfModuleLabel\":\"label\",\"modelInfo\":{\"modelInvariantUuid\":\"06bd0a18-65c0-4418-83c7-5b0d13cba0bb\",\"modelName\":\"NetworkFqdnTest3\",\"modelVersion\":\"1.0\",\"modelCustomizationUuid\":\"06bd0a18-65c0-4418-83c7-5b0d13cba0bb\",\"modelUuid\":\"02560575-4223-11e7-9252-005056850d2e\"},\"hasVolumeGroup\":false,\"isBase\":true},{\"initialCount\":0,\"vfModuleLabel\":\"label\",\"modelInfo\":{\"modelInvariantUuid\":\"06bd0a18-65c0-4418-83c7-5b0d14cba01a\",\"modelName\":\"NetworkFqdnTest5\",\"modelVersion\":\"1.0\",\"modelCustomizationUuid\":\"06bd0a18-65c0-4418-83c7-5b0d14cba01a\",\"modelUuid\":\"025607e4-4223-11e7-9252-005056850d2e\"},\"hasVolumeGroup\":false,\"isBase\":false},{\"initialCount\":0,\"vfModuleLabel\":\"PCM\",\"modelInfo\":{\"modelInvariantUuid\":\"93e9c1d2-7d37-11e7-bb31-be2e44b06b34\",\"modelName\":\"vSAMP10aDEV::PCM::module-2\",\"modelVersion\":\"2\",\"modelCustomizationUuid\":\"6728bee8-7d3a-11e7-bb31-be2e44b06b34\",\"modelUuid\":\"7774b4e4-7d37-11e7-bb31-be2e44b06b34\"},\"hasVolumeGroup\":true,\"isBase\":false},{\"initialCount\":0,\"vfModuleLabel\":\"PCM\",\"modelInfo\":{\"modelInvariantUuid\":\"64efd51a-2544-11e7-93ae-92361f002671\",\"modelName\":\"vSAMP10aDEV::PCM::module-1\",\"modelVersion\":\"2\",\"modelCustomizationUuid\":\"b4ea86b4-253f-11e7-93ae-92361f002671\",\"modelUuid\":\"066de97e-253e-11e7-93ae-92361f002671\"},\"hasVolumeGroup\":true,\"isBase\":false},{\"initialCount\":1,\"vfModuleLabel\":\"base\",\"modelInfo\":{\"modelInvariantUuid\":\"78ca26d0-246d-11e7-93ae-92361f002671\",\"modelName\":\"vSAMP10aDEV::base::module-0\",\"modelVersion\":\"2\",\"modelCustomizationUuid\":\"cb82ffd8-252a-11e7-93ae-92361f002671\",\"modelUuid\":\"20c4431c-246d-11e7-93ae-92361f002671\"},\"hasVolumeGroup\":true,\"isBase\":true},{\"initialCount\":1,\"vfModuleLabel\":\"base\",\"modelInfo\":{\"modelInvariantUuid\":null,\"modelName\":\"vSAMP10a::base::module-0\",\"modelVersion\":\"2\",\"modelCustomizationUuid\":\"MIGRATED_36e76920-ef30-4793-9979-cbd7d4b2bfc4\",\"modelUuid\":\"02560de2-4223-11e7-9252-005056850d2e\"},\"hasVolumeGroup\":true,\"isBase\":true},{\"initialCount\":1,\"vfModuleLabel\":\"module-0\",\"modelInfo\":{\"modelInvariantUuid\":null,\"modelName\":\"base::module-0\",\"modelVersion\":\"1\",\"modelCustomizationUuid\":\"MIGRATED_51baae4c-b7c7-4f57-b77e-6e01acca89e5\",\"modelUuid\":\"02561381-4223-11e7-9252-005056850d2e\"},\"hasVolumeGroup\":false,\"isBase\":true},{\"initialCount\":1,\"vfModuleLabel\":\"PCM\",\"modelInfo\":{\"modelInvariantUuid\":null,\"modelName\":\"vSAMP10a::PCM::module-1\",\"modelVersion\":\"1\",\"modelCustomizationUuid\":\"MIGRATED_e9be2ed7-45b6-479c-b06e-9093899f8ce8\",\"modelUuid\":\"02560f1b-4223-11e7-9252-005056850d2e\"},\"hasVolumeGroup\":true,\"isBase\":true}],\"modelInfo\":{\"modelInvariantUuid\":\"2fff5b20-214b-11e7-93ae-92361f002671\",\"modelName\":\"vSAMP10a\",\"modelVersion\":\"1.0\",\"modelCustomizationUuid\":\"68dc9a92-214c-11e7-93ae-92361f002671\",\"modelInstanceName\":\"vSAMP10a 1\",\"modelUuid\":\"ff2ae348-214a-11e7-93ae-92361f002671\"},\"nfRole\":null,\"nfType\":null,\"multiStageDesign\":null,\"nfFunction\":null,\"nfNamingCode\":null}]\r\n"
+ String service = "{\r\n \"modelName\" : \"eMBB-NSST\",\r\n \"modelUuid\" : \"ecfa2329-8765-4665-84e0-a32a2ac2be90\",\r\n \"modelInvariantUuid\" : \"2eeeb5ff-4655-47d8-8aa3-044682246b60\",\r\n \"modelVersion\" : \"1.0\"\r\n }"
+
+ when(mockExecution.getVariable("serviceVnfs")).thenReturn(vnfs)
+
+ when(mockExecution.getVariable("serviceType")).thenReturn("5g")
+ when(mockExecution.getVariable("vnfs")).thenReturn(vnfs)
+ when(mockExecution.getVariable("serviceModelInfo")).thenReturn(service)
+ when(mockExecution.getVariable("sliceProfile")).thenReturn(sliceProfile)
+ allocate.prepareSOMacroRequestPayload(mockExecution)
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("requestPayload"), captor.capture())
+ assertNotNull(captor.getValue())
+ }
+
+ @Test
+ void testPrepareVnfInstanceParamsJson() {
+ List<Map<String, Object>> snssaiList = new ArrayList<>()
+ Map<String, Object> snssaiMap = new LinkedHashMap<>()
+ snssaiMap.put("snssai", "01-5C83F071")
+ snssaiMap.put("status", "activated")
+ snssaiList.add(snssaiMap)
+ Map<String, Object> snssaiMap1 = new LinkedHashMap<>()
+ snssaiMap1.put("snssai", "01-5B179BD4")
+ snssaiMap1.put("status", "activated")
+ snssaiList.add(snssaiMap1)
+
+ when(mockExecution.getVariable("snssaiAndOrchStatusList")).thenReturn(snssaiList)
+
+ String returnedJsonAsString= allocate.prepareVnfInstanceParamsJson(mockExecution)
+ String expectedJsonAsString = """{supportedNssai={"sNssai":[{"snssai":"01-5C83F071","status":"activated"},{"snssai":"01-5B179BD4","status":"activated"}]}}"""
+ assertEquals(expectedJsonAsString, returnedJsonAsString)
+ }
+
+ @Test
+ void testGetNetworkInstanceWithSPInstanceAssociatedWithNssiId(){
+
+ setUpBaseMockData()
+ when(mockExecution.getVariable("serviceType")).thenReturn("5G")
+
+ DoAllocateCoreSharedSlice obj = spy(DoAllocateCoreSharedSlice.class)
+ when(obj.getAAIClient()).thenReturn(client)
+ AAIResourceUri resourceUri1 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "NSSI-C-7Q4-HDBNJ-NSSMF-01-A-ZX")
+ when(client.exists(resourceUri1)).thenReturn(true)
+ AAIResultWrapper wrapper1 = new AAIResultWrapper(mockQuerySliceServiceReturn())
+ when(client.get(resourceUri1, NotFoundException.class)).thenReturn(wrapper1)
+
+ //networkServiceInstanceId
+ when(mockExecution.getVariable("networkServiceInstanceId")).thenReturn("206535e7-77c9-4036-9387-3f1cf57b4379")
+
+ AAIResourceUri resourceUri2 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "206535e7-77c9-4036-9387-3f1cf57b4379")
+ when(client.exists(resourceUri2)).thenReturn(true)
+ AAIResultWrapper wrapper2 = new AAIResultWrapper(mockQueryNS())
+ when(client.get(resourceUri2, NotFoundException.class)).thenReturn(wrapper2)
+
+ //Check Vnf
+ when(mockExecution.getVariable("vnfId")).thenReturn("eeb66c6f-36bd-47ad-8294-48f46b1aa912")
+ AAIResourceUri resourceUri3 = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "eeb66c6f-36bd-47ad-8294-48f46b1aa912")
+ when(client.exists(resourceUri3)).thenReturn(true)
+ AAIResultWrapper wrapper3 = new AAIResultWrapper(mockQueryVnf())
+ when(client.get(resourceUri3, NotFoundException.class)).thenReturn(wrapper3)
+
+
+ //Allotted Resources-1
+ AAIResourceUri resourceUri4 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "0d3d3cce-46a8-486d-816a-954e71697c4e")
+ when(client.exists(resourceUri4)).thenReturn(true)
+ AAIResultWrapper wrapper4 = new AAIResultWrapper(mockServiceProfile1())
+ when(client.get(resourceUri4, NotFoundException.class)).thenReturn(wrapper4)
+
+ //Allotted Resources-2
+ AAIResourceUri resourceUri5 = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "1c7046f2-a5a3-4d7f-9da8-388ee641a795")
+ when(client.exists(resourceUri5)).thenReturn(true)
+ AAIResultWrapper wrapper5 = new AAIResultWrapper(mockServiceProfile2())
+ when(client.get(resourceUri5, NotFoundException.class)).thenReturn(wrapper5)
+
+ obj.getNetworkInstanceAssociatedWithNssiId(mockExecution)
+
+ //networkServiceInstanceId
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("networkServiceInstanceId"), captor.capture())
+ assertEquals("206535e7-77c9-4036-9387-3f1cf57b4379", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("networkServiceInstanceName"), captor.capture())
+ assertEquals("nsi_DemoEmbb", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("networkServiceModelInvariantUuid"), captor.capture())
+ assertEquals("848c5656-5594-4d41-84bb-7afc7c64765c", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("owningEntityId"), captor.capture())
+ assertEquals("OE-generic", captor.getValue())
+
+ //assertEquals("206535e7-77c9-4036-9387-3f1cf57b4379", captor.getValue())
+
+ //VnfId
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("vnfId"), captor.capture())
+ assertEquals("eeb66c6f-36bd-47ad-8294-48f46b1aa912", captor.getValue())
+
+ //
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("snssaiAndOrchStatusList"), captor.capture())
+ List<Map<String, Object>> snssaiList = new ArrayList<>()
+ Map<String, Object> snssaiMap = new LinkedHashMap<>()
+ snssaiMap.put("snssai", "01-5C83F071")
+ snssaiMap.put("orchestrationStatus", "activated")
+ snssaiList.add(snssaiMap)
+ Map<String, Object> snssaiMap1 = new LinkedHashMap<>()
+ snssaiMap1.put("snssai", "01-5B179BD4")
+ snssaiMap1.put("orchestrationStatus", "activated")
+ snssaiList.add(snssaiMap1)
+ assertEquals(snssaiList, captor.getValue())
+
+ //Verify Project
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("projectName"), captor.capture())
+ assertEquals("Project-generic", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("tenantId"), captor.capture())
+ assertEquals("3d5819f1542e4ef9a4ccb0bcb278ca10", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("cloudOwner"), captor.capture())
+ assertEquals("k8scloudowner", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("lcpCloudRegionId"), captor.capture())
+ assertEquals("k8sregion", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("platformName"), captor.capture())
+ assertEquals("test", captor.getValue())
+
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("lineOfBusinessName"), captor.capture())
+ assertEquals("LOB-Demonstration", captor.getValue())
+
+ }
+
+ void setUpBaseMockData() {
+
+ String sliceParams ="""{
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "snssaiList": [
+ "01-5B179BD4"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098"
+ }"""
+
+ when(mockExecution.getVariable("msoRequestId")).thenReturn("5ad89cf9-0569-4a93-4509-d8324321e2be")
+ when(mockExecution.getVariable("serviceInstanceID")).thenReturn("NSSI-C-7Q4-HDBNJ-NSSMF-01-A-ZX")
+ when(mockExecution.getVariable("nsiId")).thenReturn("NSI-M-001-HDBNJ-NSMF-01-A-ZX")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G")
+ when(mockExecution.getVariable("operationType")).thenReturn("deactivateInstance")
+ when(mockExecution.getVariable("jobId")).thenReturn("5ad89cf9-0569-4a93-9999-d8324321e2be")
+ when(mockExecution.getVariable("sliceParams")).thenReturn(sliceParams)
+ }
+
+ String mockQueryNS() {
+ return """
+ {
+ "service-instance-id": "206535e7-77c9-4036-9387-3f1cf57b4379",
+ "service-instance-name": "nsi_DemoEmbb",
+ "environment-context": "General_Revenue-Bearing",
+ "workload-context": "Production",
+ "model-invariant-id": "848c5656-5594-4d41-84bb-7afc7c64765c",
+ "model-version-id": "2de92587-3395-44e8-bb2c-b9529747e580",
+ "resource-version": "1599228110527",
+ "selflink": "restconf/config/GENERIC-RESOURCE-API:services/service/206535e7-77c9-4036-9387-3f1cf57b4379/service-data/service-topology/",
+ "orchestration-status": "Assigned",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "owning-entity",
+ "relationship-label": "org.onap.relationships.inventory.BelongsTo",
+ "related-link": "/aai/v19/business/owning-entities/owning-entity/OE-generic",
+ "relationship-data": [{
+ "relationship-key": "owning-entity.owning-entity-id",
+ "relationship-value": "OE-generic"
+ }]
+ }, {
+ "related-to": "generic-vnf",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/network/generic-vnfs/generic-vnf/eeb66c6f-36bd-47ad-8294-48f46b1aa912",
+ "relationship-data": [{
+ "relationship-key": "generic-vnf.vnf-id",
+ "relationship-value": "eeb66c6f-36bd-47ad-8294-48f46b1aa912"
+ }],
+ "related-to-property": [{
+ "property-key": "generic-vnf.vnf-name",
+ "property-value": "vfwuctest 0"
+ }]
+ }, {
+ "related-to": "project",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/projects/project/Project-generic",
+ "relationship-data": [{
+ "relationship-key": "project.project-name",
+ "relationship-value": "Project-generic"
+ }]
+ }]
+ }
+}
+ """
+ }
+
+ String mockQueryVnf() {
+
+ return """
+ {
+ "vnf-id": "eeb66c6f-36bd-47ad-8294-48f46b1aa912",
+ "vnf-name": "vfwuctest 0",
+ "vnf-type": "vfwuctest/null",
+ "service-id": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb",
+ "prov-status": "PREPROV",
+ "orchestration-status": "ConfigAssigned",
+ "in-maint": false,
+ "is-closed-loop-disabled": false,
+ "resource-version": "1599228155361",
+ "model-invariant-id": "1086e068-c932-4b61-ae3b-2d2eb0cbe3ec",
+ "model-version-id": "7fbb28cf-7dfc-447a-892c-4a3130b371d2",
+ "model-customization-id": "471b3188-e8f2-470b-9f4d-89e74d45445f",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "tenant",
+ "relationship-label": "org.onap.relationships.inventory.BelongsTo",
+ "related-link": "/aai/v19/cloud-infrastructure/cloud-regions/cloud-region/k8scloudowner/k8sregion/tenants/tenant/3d5819f1542e4ef9a4ccb0bcb278ca10",
+ "relationship-data": [{
+ "relationship-key": "cloud-region.cloud-owner",
+ "relationship-value": "k8scloudowner"
+ }, {
+ "relationship-key": "cloud-region.cloud-region-id",
+ "relationship-value": "k8sregion"
+ }, {
+ "relationship-key": "tenant.tenant-id",
+ "relationship-value": "3d5819f1542e4ef9a4ccb0bcb278ca10"
+ }],
+ "related-to-property": [{
+ "property-key": "tenant.tenant-name",
+ "property-value": "onap-tm5g-dev"
+ }]
+ }, {
+ "related-to": "cloud-region",
+ "relationship-label": "org.onap.relationships.inventory.LocatedIn",
+ "related-link": "/aai/v19/cloud-infrastructure/cloud-regions/cloud-region/k8scloudowner/k8sregion",
+ "relationship-data": [{
+ "relationship-key": "cloud-region.cloud-owner",
+ "relationship-value": "k8scloudowner"
+ }, {
+ "relationship-key": "cloud-region.cloud-region-id",
+ "relationship-value": "k8sregion"
+ }],
+ "related-to-property": [{
+ "property-key": "cloud-region.owner-defined-type",
+ "property-value": "OwnerType"
+ }]
+ }, {
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/business/customers/customer/Demonstration/service-subscriptions/service-subscription/vfw-k8s/service-instances/service-instance/206535e7-77c9-4036-9387-3f1cf57b4379",
+ "relationship-data": [{
+ "relationship-key": "customer.global-customer-id",
+ "relationship-value": "Demonstration"
+ }, {
+ "relationship-key": "service-subscription.service-type",
+ "relationship-value": "vfw-k8s"
+ }, {
+ "relationship-key": "service-instance.service-instance-id",
+ "relationship-value": "206535e7-77c9-4036-9387-3f1cf57b4379"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "vfw-0201"
+ }]
+ }, {
+ "related-to": "platform",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/platforms/platform/test",
+ "relationship-data": [{
+ "relationship-key": "platform.platform-name",
+ "relationship-value": "test"
+ }]
+ }, {
+ "related-to": "line-of-business",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/lines-of-business/line-of-business/LOB-Demonstration",
+ "relationship-data": [{
+ "relationship-key": "line-of-business.line-of-business-name",
+ "relationship-value": "LOB-Demonstration"
+ }]
+ }]
+ }
+}
+ """
+ }
+
+ String mockQuerySliceServiceReturn(){
+ String expect =
+ """{
+ "service-instance-id": "NSSI-C-7Q4-HDBNJ-NSSMF-01-A-ZX",
+ "service-instance-name": "nssi_DemoEmbb",
+ "service-role": "nssi",
+ "environment-context": "cn",
+ "model-invariant-id": "da575e8e-0863-4172-88b3-b3a9ead67895",
+ "model-version-id": "e398c92f-27da-44b9-a717-1dbfc1bdd82e",
+ "service-instance-location-id": "39-00",
+ "resource-version": "1593525640482",
+ "orchestration-status": "activated",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/206535e7-77c9-4036-9387-3f1cf57b4379",
+ "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": "206535e7-77c9-4036-9387-3f1cf57b4379"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "nsi_DemoEmbb"
+ }]
+ },
+ {
+ "related-to": "allotted-resource",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/0d3d3cce-46a8-486d-816a-954e71697c4e/allotted-resources/allotted-resource/d63c241a-4c0b-4294-b4c3-5a57421a1769",
+ "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": "0d3d3cce-46a8-486d-816a-954e71697c4e"
+ }, {
+ "relationship-key": "allotted-resource.id",
+ "relationship-value": "d63c241a-4c0b-4294-b4c3-5a57421a1769"
+ }],
+ "related-to-property": [{
+ "property-key": "allotted-resource.description"
+ }, {
+ "property-key": "allotted-resource.allotted-resource-name",
+ "property-value": "Allotted_DemoEmbb_shared"
+ }]
+ }, {
+ "related-to": "allotted-resource",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/1c7046f2-a5a3-4d7f-9da8-388ee641a795/allotted-resources/allotted-resource/362e46c2-cd84-45e4-a6c1-77f4ef88328d",
+ "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": "1c7046f2-a5a3-4d7f-9da8-388ee641a795"
+ }, {
+ "relationship-key": "allotted-resource.id",
+ "relationship-value": "362e46c2-cd84-45e4-a6c1-77f4ef88328d"
+ }],
+ "related-to-property": [{
+ "property-key": "allotted-resource.description"
+ }, {
+ "property-key": "allotted-resource.allotted-resource-name",
+ "property-value": "Allotted_DemoEmbb"
+ }]
+ }
+ ]
+ }
+}
+ """
+ return expect
+ }
+
+ String mockServiceProfile1() {
+ return """{
+ "service-instance-id": "0d3d3cce-46a8-486d-816a-954e71697c4e",
+ "service-instance-name": "DemoEmbb2",
+ "service-role": "e2esliceprofile-service",
+ "environment-context": "01-5C83F071",
+ "model-invariant-id": "040b1b40-3120-446b-b8e3-4f21d153d11e",
+ "model-version-id": "8b7dabb3-3f27-4555-a9fe-803e862b0292",
+ "service-instance-location-id": "39-00",
+ "resource-version": "1593511782269",
+ "orchestration-status": "activated",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/4b2bdbc0-cf7e-4c50-882a-f660e3ab8520",
+ "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": "4b2bdbc0-cf7e-4c50-882a-f660e3ab8520"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "DemoEmbb"
+ }]
+ }]
+ },
+ "allotted-resources": {
+ "allotted-resource": [{
+ "id": "362e46c2-cd84-45e4-a6c1-77f4ef88328d",
+ "model-invariant-id": "e5941a50-ddb4-4f74-be03-25449ae02ddc",
+ "model-version-id": "ab171d60-c2cc-4903-ac1d-c451b647e461",
+ "resource-version": "1593511173712",
+ "type": "Allotted Resource",
+ "allotted-resource-name": "Allotted_DemoEmbb",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/ea107578-9854-4718-8145-7c7febf0de6c",
+ "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": "ea107578-9854-4718-8145-7c7febf0de6c"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "nsi_DemoEmbb"
+ }]
+ }]
+ }
+ }]
+ },
+ "slice-profiles": {
+ "slice-profile": [{
+ "profile-id": "31a83df8-5bd0-4df7-a50f-7900476b81a2",
+ "latency": 3,
+ "max-number-of-UEs": 0,
+ "coverage-area-TA-list": "Beijing;Beijing;HaidianDistrict;WanshouluStreet",
+ "ue-mobility-level": "stationary",
+ "resource-sharing-level": "0",
+ "exp-data-rate-UL": 500,
+ "exp-data-rate-DL": 2000,
+ "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": "01-5C83F071",
+ "resource-version": "1593525640617"
+ }]
+ }
+}"""
+ }
+
+ String mockServiceProfile2() {
+ return """{
+ "service-instance-id": "1c7046f2-a5a3-4d7f-9da8-388ee641a795",
+ "service-instance-name": "DemoEmbb",
+ "service-role": "e2esliceprofile-service",
+ "environment-context": "01-5B179BD4",
+ "model-invariant-id": "040b1b40-3120-446b-b8e3-4f21d153d12e",
+ "model-version-id": "8b7dabb3-3f27-4555-a9fe-803e862b0282",
+ "service-instance-location-id": "39-00",
+ "resource-version": "1593511782169",
+ "orchestration-status": "activated",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/4b2bdbc0-cf7e-4c50-882a-f660e3ab8520",
+ "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": "4b2bdbc0-cf7e-4c50-882a-f660e3ab8520"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "DemoEmbb"
+ }]
+ }]
+ },
+ "allotted-resources": {
+ "allotted-resource": [{
+ "id": "362e46c2-cd84-45e4-a6c1-77f4ef88328d",
+ "model-invariant-id": "e5941a50-ddb4-4f74-be03-25449ae02ddc",
+ "model-version-id": "ab171d60-c2cc-4903-ac1d-c451b647e461",
+ "resource-version": "1593511173712",
+ "type": "Allotted Resource",
+ "allotted-resource-name": "Allotted_DemoEmbb",
+ "relationship-list": {
+ "relationship": [{
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v19/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/ea107578-9854-4718-8145-7c7febf0de6c",
+ "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": "ea107578-9854-4718-8145-7c7febf0de6c"
+ }],
+ "related-to-property": [{
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "nsi_DemoEmbb"
+ }]
+ }]
+ }
+ }]
+ },
+ "slice-profiles": {
+ "slice-profile": [{
+ "profile-id": "b86df550-9d70-452b-a5a9-eb8823417255",
+ "latency": 6,
+ "max-number-of-UEs": 0,
+ "coverage-area-TA-list": "Beijing;Beijing;HaidianDistrict;WanshouluStreet",
+ "ue-mobility-level": "stationary",
+ "resource-sharing-level": "0",
+ "exp-data-rate-UL": 500,
+ "exp-data-rate-DL": 1000,
+ "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": "01-5B179BD4",
+ "resource-version": "1593511356725"
+ }]
+ }
+}"""
+ }
+} \ No newline at end of file
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateTnNssiTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateTnNssiTest.groovy
new file mode 100644
index 0000000000..33110b6e5b
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoAllocateTnNssiTest.groovy
@@ -0,0 +1,167 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 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.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+
+import static org.junit.Assert.assertNotNull
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.*
+
+class DoAllocateTnNssiTest extends MsoGroovyTest {
+ @Before
+ void init() throws IOException {
+ super.init("DoAllocateTnNssiTest")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest() {
+ when(mockExecution.getVariable("msoRequestId")).thenReturn("4c614769-f58a-4556-8ad9-dcd903077c82")
+ when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback")
+ when(mockExecution.getVariable("modelInvariantUuid")).thenReturn("f85cbcc0-ad74-45d7-a5a1-17c8744fdb71")
+ when(mockExecution.getVariable("modelUuid")).thenReturn("36a3a8ea-49a6-4ac8-b06c-89a54544b9b6")
+ //when(mockExecution.getVariable("serviceInstanceID")).thenReturn("eb0863e9-a69b-4b17-8a56-f05ad110bef7")
+ //when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("operationType")).thenReturn("opTypeTest")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("servicename")).thenReturn("5G-test")
+ when(mockExecution.getVariable("networkType")).thenReturn("5G-network")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G-service")
+ when(mockExecution.getVariable("nsiId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56")
+ when(mockExecution.getVariable("jobId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4")
+ when(mockExecution.getVariable("sliceParams")).thenReturn(mockSliceParams())
+
+ TnAllocateNssi obj = new TnAllocateNssi()
+ obj.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sliceServiceInstanceId"), captor.capture())
+ String sliceServiceInstanceId = captor.getValue()
+ assertNotNull(sliceServiceInstanceId)
+ }
+
+ @Test
+ void testCreateServiceInstance() {
+ when(mockExecution.getVariable("sliceServiceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("sliceServiceInstanceName")).thenReturn("5G-service")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G")
+ when(mockExecution.getVariable("modelInvariantUuid")).thenReturn("f85cbcc0-ad74-45d7-a5a1-17c8744fdb71")
+ when(mockExecution.getVariable("modelUuid")).thenReturn("36a3a8ea-49a6-4ac8-b06c-89a54544b9b6")
+ when(mockExecution.getVariable("sliceProfile")).thenReturn(mockSliceProfile())
+
+// JsonUtils jsonUtil = new JsonUtils()
+// String sliceProfile = jsonUtil.getJsonValue(mockSliceParams(), "sliceProfile")
+// when(mockExecution.getVariable("sliceProfile")).thenReturn(sliceProfile)
+
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ DoCreateTnNssiInstance obj = spy(DoCreateTnNssiInstance.class)
+ when(obj.getAAIClient()).thenReturn(client)
+
+ obj.createServiceInstance(mockExecution)
+ }
+
+
+ private String mockSliceParams() {
+ String expect = """{
+ "sliceProfile": {
+ "snssaiList": [
+ "001-100001"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098",
+ "plmnIdList": [
+ "460-00",
+ "460-01"
+ ],
+ "perfReq": {
+ },
+ "coverageAreaTAList": [
+ ],
+ "latency": 2,
+ "maxBandwidth": 100,
+ "resourceSharingLevel": "non-shared"
+ },
+ "transportSliceNetworks": [
+ {
+ "connectionLinks": [
+ {
+ "transportEndpointA": "tranportEp_ID_XXX",
+ "transportEndpointB": "tranportEp_ID_YYY"
+ },
+ {
+ "transportEndpointA": "tranportEp_ID_AAA",
+ "transportEndpointB": "tranportEp_ID_BBB"
+ }
+ ]
+ },
+ {
+ "connectionLinks": [
+ {
+ "transportEndpointA": "tranportEp_ID_CCC",
+ "transportEndpointB": "tranportEp_ID_DDD"
+ },
+ {
+ "transportEndpointA": "tranportEp_ID_EEE",
+ "transportEndpointB": "tranportEp_ID_FFF"
+ }
+ ]
+ }
+ ],
+ "nsiInfo": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "nsiName": "eMBB-001"
+ },
+ "scriptName": "AN1"
+ }"""
+ return expect.replaceAll("\\\\s+", "")
+ }
+
+ private String mockSliceProfile() {
+ String expect = """{
+ "snssaiList": [
+ "001-100001"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098",
+ "plmnIdList": [
+ "460-00",
+ "460-01"
+ ],
+ "perfReq": {
+ },
+ "coverageAreaTAList": [
+ ],
+ "latency": 2,
+ "maxBandwidth": 100,
+ "resourceSharingLevel": "non-shared"
+ }"""
+ return expect.replaceAll("\\\\s+", "")
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateCoreNSSITest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateCoreNSSITest.groovy
new file mode 100644
index 0000000000..48b96fb60e
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateCoreNSSITest.groovy
@@ -0,0 +1,829 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 TIM
+ * ================================================================================
+ * 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.camunda.bpm.engine.ProcessEngineServices
+import org.camunda.bpm.engine.RepositoryService
+import org.camunda.bpm.engine.impl.cmmn.execution.CaseExecutionImpl
+import org.camunda.bpm.engine.impl.core.variable.scope.AbstractVariableScope
+import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity
+import org.camunda.bpm.engine.repository.ProcessDefinition
+import org.junit.Rule
+import org.junit.rules.ExpectedException
+import org.mockito.invocation.InvocationOnMock
+import org.mockito.stubbing.Answer
+import org.onap.aai.domain.yang.CloudRegion
+import org.onap.aai.domain.yang.Customer
+import org.onap.aai.domain.yang.GenericVnf
+import org.onap.aai.domain.yang.ModelVer
+import org.onap.aai.domain.yang.OwningEntity
+import org.onap.aai.domain.yang.Project
+import org.onap.aai.domain.yang.Relationship
+import org.onap.aai.domain.yang.RelationshipList
+import org.onap.aai.domain.yang.ServiceSubscription
+import org.onap.aai.domain.yang.SliceProfile
+import org.onap.aai.domain.yang.SliceProfiles
+import org.onap.aai.domain.yang.Tenant
+import org.onap.aai.domain.yang.Tenants
+import org.onap.aai.domain.yang.VfModule
+import org.onap.aai.domain.yang.VfModules
+import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
+import org.onap.aaiclient.client.aai.entities.Relationships
+import org.onap.aaiclient.client.aai.entities.uri.AAISimpleUri
+import org.onap.aaiclient.client.aai.entities.uri.ServiceInstanceUri
+import org.onap.logging.filter.base.ONAPComponents
+import org.onap.so.beans.nsmf.NssiResponse
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.MsoUtils
+import org.onap.so.bpmn.mock.FileUtil
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.serviceinstancebeans.RequestDetails
+import org.onap.so.utils.CryptoUtils
+
+import javax.ws.rs.core.Response
+
+import static org.junit.Assert.*;
+import org.junit.Before
+import org.junit.Test
+import org.mockito.Mockito
+import org.onap.aai.domain.yang.ServiceInstance
+import org.onap.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+
+import static org.mockito.ArgumentMatchers.anyDouble
+import static org.mockito.ArgumentMatchers.anyInt
+import static org.mockito.ArgumentMatchers.anyString
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.doNothing
+import static org.mockito.Mockito.doReturn
+import static org.mockito.Mockito.doThrow
+import static org.mockito.Mockito.mock
+import static org.mockito.Mockito.mock
+import static org.mockito.Mockito.mock
+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 DoDeallocateCoreNSSITest extends MsoGroovyTest {
+
+ @Before
+ void init() throws IOException {
+ super.init("DoDeallocateNSSITest")
+ }
+
+
+ @Test
+ void testPreProcessRequest() {
+ def currentNSSI = [:]
+ currentNSSI.put("nssiId","5G-999")
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ DoDeallocateCoreNSSI dcnssi = new DoDeallocateCoreNSSI()
+ dcnssi.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution,times(1)).getVariable("currentNSSI")
+ }
+
+
+ @Test
+ void testExecuteTerminateNSSIQuery() {
+ HttpClientFactory httpClientFactoryMock
+ HttpClient httpClientMock
+
+ def currentNSSI = [:]
+ currentNSSI.put("nssiId","5G-999")
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ when(mockExecution.getVariable("mso.oof.endpoint")).thenReturn("http://oof.onap:8088")
+ when(mockExecution.getVariable("mso.oof.auth")).thenReturn("mso.oof.auth")
+ when(mockExecution.getVariable("mso.msoKey")).thenReturn("mso.msoKey")
+ when(mockExecution.getVariable("mso-request-id")).thenReturn("mso-request-id")
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+ when(spy.getAAIClient()).thenReturn(client)
+
+ when(spy.encryptBasicAuth("mso.oof.auth", "mso.msoKey")).thenReturn("auth-value")
+
+ String authHeaderResponse = "auth-header"
+
+ /* String authHeaderResponse = "{\n" +
+ " \"errorCode\": \"401\",\n" +
+ " \"errorMessage\": \"Bad request\"\n" +
+ "}" */
+
+ when(spy.getAuthHeader(mockExecution, "auth-value", "mso.msoKey")).thenReturn(authHeaderResponse)
+
+ String urlString = "http://oof.onap:8088"
+
+ String httpRequest = "{\n" +
+ " \"type\": \"NSSI\",\n" +
+ " \"NxIId\": \"5G-999\",\n" +
+ " \"requestInfo\": {\n" +
+ " \"transactionId\": \"mso-request-id\",\n" +
+ " \"requestId\": \"mso-request-id\",\n" +
+ " \"sourceId\": \"so\",\n" +
+ " }\n" +
+ "}"
+
+ boolean terminateResponse = true
+
+ String oofResponse = "{\n" +
+ " \"requestId\": \"mso-request-id\",\n" +
+ " \"transactionId\": \"mso-request-id\",\n" +
+ " \"statusMessage\": \"\",\n" +
+ " \"requestStatus\": \"accepted\",\n" +
+ " \"terminateResponse\": \"${terminateResponse}\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n"
+
+ String oofCallResponse = oofResponse
+
+ /* String oofCallResponse = "{\n" +
+ " \"errorCode\": \"401\",\n" +
+ " \"errorMessage\": \"Exception during the call\"\n" +
+ "}" */
+
+ when(spy.callOOF(urlString, "auth-header", httpRequest)).thenReturn(oofCallResponse)
+
+ spy.executeTerminateNSSIQuery(mockExecution)
+
+ verify(mockExecution).setVariable("isTerminateNSSI", terminateResponse)
+
+ }
+
+
+ @Test
+ void testGetNetworkServiceInstance() {
+ def currentNSSI = [:]
+ currentNSSI.put("nssiId","5G-999")
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5G-999")
+ AAIResourceUri networkServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "NS-777")
+
+ ServiceInstance nssi = new ServiceInstance()
+ nssi.setServiceInstanceId("5G-999")
+
+ ServiceInstance networkServiceInstance = new ServiceInstance()
+ networkServiceInstance.setServiceInstanceId("NS-777")
+ networkServiceInstance.setServiceRole("Network Service")
+
+ Optional<ServiceInstance> nssiOpt = Optional.of(nssi)
+ Optional<ServiceInstance> networkServiceInstaneOpt = Optional.of(networkServiceInstance)
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+ when(spy.getAAIClient()).thenReturn(client)
+
+ when(client.get(ServiceInstance.class, nssiUri)).thenReturn(nssiOpt)
+
+ //String json = FileUtil.readResourceFile("__files/AAI/ServiceInstanceWithAR.json")
+ AAIResultWrapper wrapperMock = mock(AAIResultWrapper.class) //new AAIResultWrapper(json)
+ Relationships rsMock = mock(Relationships.class)
+ Optional<Relationships> orsMock = Optional.of(rsMock)
+ List<AAIResourceUri> arus = new ArrayList<>()
+ AAIResourceUri aru = new ServiceInstanceUri(networkServiceInstanceUri)
+ arus.add(aru)
+
+ when(client.get(nssiUri)).thenReturn(wrapperMock)
+ when(wrapperMock.getRelationships()).thenReturn(orsMock)
+
+ when(rsMock.getRelatedAAIUris(AAIObjectType.SERVICE_INSTANCE)).thenReturn(arus)
+ when(client.get(ServiceInstance.class, aru)).thenReturn(networkServiceInstaneOpt)
+
+ spy.getNetworkServiceInstance(mockExecution)
+
+ assertTrue("Either NSSI doesn't exist or unexpected NSSI Service Instance ID",
+ currentNSSI.get("nssi") != null && ((ServiceInstance)currentNSSI.get("nssi")).getServiceInstanceId().equals(nssi.getServiceInstanceId()))
+
+ assertTrue("Either Network Service Instance doesn't exist or unexpected Network Service Instance ID",
+ currentNSSI.get("networkServiceInstance") != null && ((ServiceInstance)currentNSSI.get("networkServiceInstance")).getServiceInstanceId().equals(networkServiceInstance.getServiceInstanceId()))
+
+ assertNotNull("networkServiceInstanceUri doesn't exist", currentNSSI.get("networkServiceInstanceUri"))
+ }
+
+
+ @Test
+ void testDeleteServiceOrder() {
+ def currentNSSI = [:]
+ currentNSSI.put("nssiId","5G-999")
+
+ ServiceInstance networkServiceInstance = new ServiceInstance()
+ networkServiceInstance.setServiceInstanceId("NS-777")
+ networkServiceInstance.setServiceRole("Network Service")
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ currentNSSI.put("networkServiceInstance", networkServiceInstance)
+
+ when(mockExecution.getVariable("nbi.endpoint.url")).thenReturn("http://nbi.onap:8088")
+ when(mockExecution.getVariable("mso.msoKey")).thenReturn("mso.msoKey")
+ when(mockExecution.getVariable("mso.infra.endpoint.auth")).thenReturn("mso.infra.endpoint.auth")
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+ when(spy.getAAIClient()).thenReturn(client)
+
+ when(spy.encryptBasicAuth("mso.infra.endpoint.auth", "mso.msoKey")).thenReturn("auth-value")
+
+ String authHeaderResponse = "auth-header"
+
+ /* String authHeaderResponse = "{\n" +
+ " \"errorCode\": \"401\",\n" +
+ " \"errorMessage\": \"Bad request\"\n" +
+ "}" */
+
+ when(spy.getAuthHeader(mockExecution, "auth-value", "mso.msoKey")).thenReturn(authHeaderResponse)
+
+ String urlString = String.format("http://nbi.onap:8088/api/v4/serviceOrder/%s", networkServiceInstance.getServiceInstanceId())
+
+ String callDeleteServiceOrderResponse = "deleted"
+
+ when(spy.callDeleteServiceOrder(mockExecution, urlString, "auth-header")).thenReturn(callDeleteServiceOrderResponse)
+
+ spy.deleteServiceOrder(mockExecution)
+ }
+
+
+
+ @Test
+ void getConstituteVNFFromNetworkServiceInst() {
+ def currentNSSI = [:]
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+ when(spy.getAAIClient()).thenReturn(client)
+
+ ServiceInstance networkServiceInstance = new ServiceInstance()
+ networkServiceInstance.setServiceInstanceId("NS-777")
+ networkServiceInstance.setServiceRole("Network Service")
+
+ GenericVnf genericVNF = new GenericVnf()
+ genericVNF.setVnfId("VNF-1")
+
+ AAIResourceUri networkServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, networkServiceInstance.getServiceInstanceId())
+
+ Optional<GenericVnf> genericVnfOpt = Optional.of(genericVNF)
+ AAIResourceUri genericVNFUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericVNF.getVnfId())
+
+ currentNSSI.put("networkServiceInstanceUri", networkServiceInstanceUri)
+ currentNSSI.put("networkServiceInstance", networkServiceInstance)
+
+ AAIResultWrapper wrapperMock = mock(AAIResultWrapper.class) //new AAIResultWrapper(json)
+ Relationships rsMock = mock(Relationships.class)
+ Optional<Relationships> orsMock = Optional.of(rsMock)
+ List<AAIResourceUri> arus = new ArrayList<>()
+ AAIResourceUri aru = new AAISimpleUri(genericVNFUri)
+ arus.add(aru)
+
+ when(client.get(networkServiceInstanceUri)).thenReturn(wrapperMock)
+ when(wrapperMock.getRelationships()).thenReturn(orsMock)
+
+ when(rsMock.getRelatedAAIUris(AAIObjectType.GENERIC_VNF)).thenReturn(arus)
+ when(client.get(GenericVnf.class, genericVNFUri)).thenReturn(genericVnfOpt)
+
+ spy.getConstituteVNFFromNetworkServiceInst(mockExecution)
+
+ assertNotNull("constituteVnfUri doesn't exist", currentNSSI.get("constituteVnfUri"))
+
+ assertTrue("Either Constitute VNF doesn't exist or unexpected VNF ID",
+ currentNSSI.get("constituteVnf") != null && ((GenericVnf)currentNSSI.get("constituteVnf")).getVnfId().equals(genericVNF.getVnfId()))
+ }
+
+
+ @Test
+ void testGetNSSIAssociatedProfiles() {
+ def currentNSSI = [:]
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ ServiceInstance nssi = new ServiceInstance()
+ nssi.setServiceInstanceId("5G-999")
+
+ SliceProfiles sliceProfiles = new SliceProfiles()
+
+ List<SliceProfile> slProfiles = sliceProfiles.getSliceProfile()
+ slProfiles.add(new SliceProfile())
+ slProfiles.add(new SliceProfile())
+
+ nssi.setSliceProfiles(sliceProfiles)
+ currentNSSI.put("nssi", nssi)
+
+ DoDeallocateCoreNSSI obj = new DoDeallocateCoreNSSI()
+ obj.getNSSIAssociatedProfiles(mockExecution)
+
+ List<SliceProfile> associatedProfiles = (List<SliceProfile>)currentNSSI.get("associatedProfiles")
+ assertTrue("Either associatedProfiles doesn't exist or size is incorrect", (associatedProfiles != null && associatedProfiles.size() == 2))
+ }
+
+
+ @Test
+ void testCalculateSNSSAI() {
+ def currentNSSI = [:]
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ String theSNSSAI = "theS-NSSAI"
+
+ currentNSSI.put("S-NSSAI", theSNSSAI)
+
+ List<SliceProfile> associatedProfiles = new ArrayList<>()
+ SliceProfile sliceProfile1 = new SliceProfile()
+ sliceProfile1.setSNssai("snssai1")
+
+ SliceProfile sliceProfile2 = new SliceProfile()
+ sliceProfile2.setSNssai(theSNSSAI)
+
+ SliceProfile sliceProfile3 = new SliceProfile()
+ sliceProfile3.setSNssai("snssai3")
+
+ associatedProfiles.add(sliceProfile1)
+ associatedProfiles.add(sliceProfile2)
+ associatedProfiles.add(sliceProfile3)
+
+ int sizeBefore = associatedProfiles.size()
+
+ currentNSSI.put("associatedProfiles", associatedProfiles)
+
+ DoDeallocateCoreNSSI obj = new DoDeallocateCoreNSSI()
+ obj.calculateSNSSAI(mockExecution)
+
+ List<SliceProfile> snssais = (List<SliceProfile>)currentNSSI.get("S-NSSAIs")
+ SliceProfile sliceProfileContainsSNSSAI = (SliceProfile)currentNSSI.get("sliceProfileS-NSSAI")
+
+ assertTrue("Either snssais doesn't exist or size is incorrect", (snssais != null && snssais.size() == (sizeBefore - 1)))
+ assertNotNull("Slice Profile which contains given S-NSSAI not found", sliceProfileContainsSNSSAI)
+ assertTrue("Wrong Slice Profile", sliceProfileContainsSNSSAI.getSNssai().equals(theSNSSAI))
+ }
+
+
+ @Test
+ void testInvokePUTServiceInstance() {
+ def currentNSSI = [:]
+
+ ServiceInstance networkServiceInstance = new ServiceInstance()
+ networkServiceInstance.setServiceInstanceId("NS-777")
+ networkServiceInstance.setServiceRole("Network Service")
+
+ GenericVnf constituteVnf = new GenericVnf()
+ constituteVnf.setVnfId("VNF-1")
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ currentNSSI.put("networkServiceInstance", networkServiceInstance)
+ currentNSSI.put("constituteVnf", constituteVnf)
+
+ when(mockExecution.getVariable("mso.infra.endpoint.url")).thenReturn("http://mso.onap:8088")
+ when(mockExecution.getVariable("mso.msoKey")).thenReturn("mso.msoKey")
+ when(mockExecution.getVariable("mso.infra.endpoint.auth")).thenReturn("mso.infra.endpoint.auth")
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+ when(spy.getAAIClient()).thenReturn(client)
+
+ when(spy.encryptBasicAuth("mso.infra.endpoint.auth", "mso.msoKey")).thenReturn("auth-value")
+
+ String authHeaderResponse = "auth-header"
+
+ when(spy.getAuthHeader(mockExecution, "auth-value", "mso.msoKey")).thenReturn(authHeaderResponse)
+
+ String urlString = String.format("http://mso.onap:8088/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s", networkServiceInstance.getServiceInstanceId(), constituteVnf.getVnfId())
+
+ String callPUTServiceInstanceResponse = "put"
+
+ RequestDetails requestDetails = new RequestDetails()
+ ObjectMapper mapper = new ObjectMapper()
+ String requestDetailsStr = mapper.writeValueAsString(requestDetails)
+
+ when(spy.prepareRequestDetails(mockExecution)).thenReturn(requestDetailsStr)
+
+ when(spy.callPUTServiceInstance(urlString, "auth-header", requestDetailsStr)).thenReturn(callPUTServiceInstanceResponse)
+
+ spy.invokePUTServiceInstance(mockExecution)
+ }
+
+
+ @Test
+ void testRemoveNSSIAssociationWithNSI() {
+ def currentNSSI = [:]
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+
+ when(spy.getAAIClient()).thenReturn(client)
+
+ String nssiId = "5G-999"
+ String nsiId = "5G-99"
+ currentNSSI.put("nssiId", nssiId)
+ currentNSSI.put("nsiId", nsiId)
+
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+ AAIResourceUri nsiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nsiId)
+
+ doNothing().when(client).disconnect(nssiUri, nsiUri)
+
+ spy.removeNSSIAssociationWithNSI(mockExecution)
+
+ }
+
+
+ @Test
+ void testRemoveSPAssociationWithNSSI() {
+ def currentNSSI = [:]
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ String nssiId = "5G-999"
+ currentNSSI.put("nssiId", nssiId)
+ ServiceInstance nssi = new ServiceInstance()
+ nssi.setServiceInstanceId(nssiId)
+ nssi.setSliceProfiles(new SliceProfiles())
+
+ currentNSSI.put("nssi", nssi)
+
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+
+ when(spy.getAAIClient()).thenReturn(client)
+
+ String theSNSSAI = "theS-NSSAI"
+ currentNSSI.put("S-NSSAI", theSNSSAI)
+
+ List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
+
+ SliceProfile sliceProfile1 = new SliceProfile()
+ sliceProfile1.setSNssai("snssai1")
+
+ SliceProfile sliceProfile2 = new SliceProfile()
+ sliceProfile2.setSNssai(theSNSSAI)
+
+ SliceProfile sliceProfile3 = new SliceProfile()
+ sliceProfile3.setSNssai("snssai3")
+
+ associatedProfiles.add(sliceProfile1)
+ associatedProfiles.add(sliceProfile2)
+ associatedProfiles.add(sliceProfile3)
+
+ int sizeBefore = associatedProfiles.size()
+
+ doNothing().when(client).update(nssiUri, nssi)
+
+ spy.removeSPAssociationWithNSSI(mockExecution)
+
+ assertTrue("Association between slice profile and NSSI wasn't removed", ((ServiceInstance)currentNSSI.get("nssi")).getSliceProfiles().getSliceProfile().size() == (sizeBefore - 1))
+ }
+
+
+ @Test
+ void testDeleteSliceProfileInstance() {
+ def currentNSSI = [:]
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ String globalSubscriberId = "global-id"
+ String serviceType = "service"
+ String nssiId = "5G-999"
+
+ currentNSSI.put("globalSubscriberId", nssiId)
+ currentNSSI.put("serviceType", nssiId)
+ currentNSSI.put("nssiId", nssiId)
+
+ String theSNSSAI = "theS-NSSAI"
+
+ SliceProfile sliceProfile = new SliceProfile()
+ sliceProfile.setSNssai(theSNSSAI)
+ sliceProfile.setProfileId("prof-id")
+
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+
+ currentNSSI.put("sliceProfileS-NSSAI", sliceProfile)
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+
+ when(spy.getAAIClient()).thenReturn(client)
+
+ doNothing().when(client).delete(nssiUri)
+
+ spy.deleteSliceProfileInstance(mockExecution)
+
+ }
+
+
+ @Test
+ void testDeleteNSSIServiceInstance() {
+ def currentNSSI = [:]
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ String nssiId = "5G-999"
+
+ currentNSSI.put("nssiId", nssiId)
+
+ AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+
+ when(spy.getAAIClient()).thenReturn(client)
+
+ doNothing().when(client).delete(nssiUri)
+
+ spy.deleteNSSIServiceInstance(mockExecution)
+ }
+
+
+ @Test
+ void testUpdateServiceOperationStatus() {
+ def currentNSSI = [:]
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ String nssiId = "5G-999"
+
+ currentNSSI.put("nssiId", nssiId)
+ currentNSSI.put("e2eServiceInstanceId", "e2eServiceInstanceId")
+ currentNSSI.put("operationId", "operationId")
+ currentNSSI.put("operationType", "operationType")
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+
+ spy.updateServiceOperationStatus(mockExecution)
+
+ }
+
+
+ @Test
+ void testPrepareRequestDetails() {
+ def currentNSSI = [:]
+
+ when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
+
+ ServiceInstance networkServiceInstance = new ServiceInstance()
+ networkServiceInstance.setServiceInstanceId("NS-777")
+ networkServiceInstance.setServiceRole("Network Service")
+ networkServiceInstance.setModelInvariantId("model-invariant-id")
+ networkServiceInstance.setServiceInstanceName("service-instance-name")
+
+ ServiceInstance nssi = new ServiceInstance()
+ nssi.setServiceInstanceId("5G-999")
+ nssi.setOrchestrationStatus("orchestration-status")
+
+ AAIResourceUri networkServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "networkServiceInstance.getServiceInstanceId()")
+
+ AAIResourceUri cloudRegionAAIUri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, "cloud-owner", "cloud-region-id")
+
+ currentNSSI.put("networkServiceInstanceUri", networkServiceInstanceUri)
+
+ currentNSSI.put("networkServiceInstance", networkServiceInstance)
+
+ currentNSSI.put("globalSubscriberId", "globalSubscriberId")
+
+ currentNSSI.put("subscriberName", "subscriber-name")
+
+ currentNSSI.put("serviceId", "service-id")
+
+ currentNSSI.put("nssi", nssi)
+
+ List<SliceProfile> associatedProfiles = new ArrayList<>()
+ SliceProfile sliceProfile1 = new SliceProfile()
+ sliceProfile1.setSNssai("snssai1")
+
+ SliceProfile sliceProfile2 = new SliceProfile()
+ sliceProfile2.setSNssai("snssai2")
+
+ associatedProfiles.add(sliceProfile1)
+ associatedProfiles.add(sliceProfile2)
+
+ List<String> snssais = new ArrayList<>()
+ snssais.add(sliceProfile1.getSNssai())
+ snssais.add(sliceProfile2.getSNssai())
+
+ currentNSSI.put("S-NSSAIs", snssais)
+
+
+ ServiceSubscription serviceSubscription = new ServiceSubscription()
+ serviceSubscription.setServiceType("service-type")
+
+ currentNSSI.put("serviceSubscription", serviceSubscription)
+
+ GenericVnf genericVnf = new GenericVnf()
+ genericVnf.setServiceId("service-id")
+ genericVnf.setVnfName("vnf-name")
+ genericVnf.setModelInvariantId("model-invariant-id")
+ genericVnf.setModelCustomizationId("model-customization-id")
+ genericVnf.setVnfName("vnf-name")
+ genericVnf.setVnfId("vnf-id")
+
+ VfModule vfModule = new VfModule()
+ vfModule.setModelInvariantId("model-invariant-id")
+ vfModule.setModelCustomizationId("model-customization-id")
+ vfModule.setModelVersionId("model-version-id")
+ vfModule.setVfModuleName("vf-module-name")
+
+ VfModules vfModules = new VfModules()
+ vfModules.getVfModule().add(vfModule)
+ genericVnf.setVfModules(vfModules)
+
+ currentNSSI.put("constituteVnf", genericVnf)
+
+ AAIResourceUri constituteVNFURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericVnf.getVnfId())
+
+ currentNSSI.put("constituteVnfUri", constituteVNFURI)
+
+ DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
+
+ when(spy.getAAIClient()).thenReturn(client)
+
+ prepareModelVer(networkServiceInstance)
+
+ //prepareSubscriberInfo(networkServiceInstanceUri)
+
+ prepareCloudConfiguration(constituteVNFURI, cloudRegionAAIUri)
+
+ prepareModelVer(genericVnf)
+
+ prepareModelVer(vfModule)
+
+ prepareOwningEntity(networkServiceInstanceUri)
+
+ prepareProject(cloudRegionAAIUri)
+
+ String requestDetails = spy.prepareRequestDetails(mockExecution)
+
+ }
+
+
+ void prepareProject(AAIResourceUri cloudRegionAAIUri) {
+ Project project = new Project()
+ project.setProjectName("project-name")
+
+ AAIResultWrapper wrapperMock = mock(AAIResultWrapper.class)
+ Relationships rsMock = mock(Relationships.class)
+ Optional<Relationships> orsMock = Optional.of(rsMock)
+
+ when(client.get(cloudRegionAAIUri)).thenReturn(wrapperMock)
+ when(wrapperMock.getRelationships()).thenReturn(orsMock)
+
+ List<AAIResourceUri> arus = new ArrayList<>()
+ AAIResourceUri aru = new AAISimpleUri(cloudRegionAAIUri)
+ arus.add(aru)
+
+ when(rsMock.getRelatedAAIUris(AAIObjectType.PROJECT)).thenReturn(arus)
+
+ Optional<Project> projectOpt = Optional.of(project)
+
+ when(client.get(Project.class, aru)).thenReturn(projectOpt)
+ }
+
+
+ void prepareOwningEntity(AAIResourceUri networkServiceInstanceUri) {
+ OwningEntity owningEntity = new OwningEntity()
+
+ owningEntity.setOwningEntityId("owning-entity-id")
+ owningEntity.setOwningEntityName("owning-entity-name")
+
+ AAIResultWrapper wrapperMock = mock(AAIResultWrapper.class)
+
+ Relationships rsMock = mock(Relationships.class)
+ Optional<Relationships> orsMock = Optional.of(rsMock)
+
+ when(client.get(networkServiceInstanceUri)).thenReturn(wrapperMock)
+ when(wrapperMock.getRelationships()).thenReturn(orsMock)
+
+ List<AAIResourceUri> arus = new ArrayList<>()
+ AAIResourceUri aru = new AAISimpleUri(networkServiceInstanceUri)
+ arus.add(aru)
+
+ when(rsMock.getRelatedAAIUris(AAIObjectType.OWNING_ENTITY)).thenReturn(arus)
+
+ Optional<OwningEntity> owningEntityOpt = Optional.of(owningEntity)
+
+ when(client.get(OwningEntity.class, aru)).thenReturn(owningEntityOpt)
+ }
+
+
+
+ void prepareCloudConfiguration(AAIResourceUri constituteVNFURI, cloudRegionAAIUri) {
+ AAIResultWrapper wrapperMock = mock(AAIResultWrapper.class)
+
+ Relationships rsMock = mock(Relationships.class)
+ Optional<Relationships> orsMock = Optional.of(rsMock)
+
+ when(client.get(constituteVNFURI)).thenReturn(wrapperMock)
+ when(wrapperMock.getRelationships()).thenReturn(orsMock)
+
+ List<AAIResourceUri> arus = new ArrayList<>()
+ AAIResourceUri aru = new AAISimpleUri(cloudRegionAAIUri)
+ arus.add(aru)
+
+ when(rsMock.getRelatedAAIUris(AAIObjectType.CLOUD_REGION)).thenReturn(arus)
+
+ CloudRegion cloudRegion = new CloudRegion()
+ cloudRegion.setCloudRegionId("cloud-region-id")
+ cloudRegion.setCloudOwner("cloud-owner")
+ Tenant tenant = new Tenant()
+ tenant.setTenantId("tenant-id")
+
+ Tenants tenants = new Tenants()
+ tenants.getTenant().add(tenant)
+ cloudRegion.setTenants(tenants)
+ Optional<CloudRegion> cloudRegionOpt = Optional.of(cloudRegion)
+
+ when(client.get(CloudRegion.class, aru)).thenReturn(cloudRegionOpt)
+ }
+
+
+ void prepareSubscriberInfo( AAIResourceUri networkServiceInstanceUri) {
+ AAIResultWrapper wrapperMock = mock(AAIResultWrapper.class)
+
+ Relationships rsMock = mock(Relationships.class)
+ Optional<Relationships> orsMock = Optional.of(rsMock)
+
+ when(client.get(networkServiceInstanceUri)).thenReturn(wrapperMock)
+ when(wrapperMock.getRelationships()).thenReturn(orsMock)
+
+ AAIResourceUri serviceSubscriptionUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION, "global-customer-id", "service-type")
+
+ AAIResourceUri customerUri = AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, "global-customer-id")
+ List<AAIResourceUri> arus = new ArrayList<>()
+
+ arus.add(serviceSubscriptionUri)
+
+ when(rsMock.getRelatedAAIUris(AAIObjectType.SERVICE_SUBSCRIPTION)).thenReturn(arus)
+
+ ServiceSubscription serviceSubscription = new ServiceSubscription()
+ serviceSubscription.setServiceType("service-type")
+ Optional<ServiceSubscription> serviceSubscriptionOpt = Optional.of(serviceSubscription)
+
+ when(client.get(ServiceSubscription.class, serviceSubscriptionUri)).thenReturn(serviceSubscriptionOpt)
+
+ when(client.get(networkServiceInstanceUri)).thenReturn(wrapperMock)
+
+ when(rsMock.getRelatedAAIUris(AAIObjectType.CUSTOMER)).thenReturn(arus)
+
+ Customer customer = new Customer()
+ customer.setSubscriberName("subscriber-name")
+ Optional<Customer> customerOpt = Optional.of(customer)
+
+ when(client.get(Customer.class, customerUri)).thenReturn(customerOpt)
+ }
+
+
+ void prepareModelVer(ServiceInstance networkServiceInstance) {
+ ModelVer modelVer = new ModelVer()
+ modelVer.setModelVersionId("model-version-id")
+ modelVer.setModelName("model-name")
+ modelVer.setModelVersion("model-version")
+
+ Optional<ModelVer> modelVerOpt = Optional.of(modelVer)
+
+ AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, networkServiceInstance.getModelInvariantId(), networkServiceInstance.getModelVersionId())
+ when(client.get(ModelVer.class, modelVerUrl)).thenReturn(modelVerOpt)
+ }
+
+ void prepareModelVer(GenericVnf genericVnf) {
+ ModelVer modelVer = new ModelVer()
+ modelVer.setModelVersionId("model-version-id")
+ modelVer.setModelName("model-name")
+ modelVer.setModelVersion("model-version")
+
+ Optional<ModelVer> modelVerOpt = Optional.of(modelVer)
+
+ AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, genericVnf.getModelInvariantId(), genericVnf.getModelVersionId())
+ when(client.get(ModelVer.class, modelVerUrl)).thenReturn(modelVerOpt)
+ }
+
+ void prepareModelVer(VfModule vfModule) {
+ ModelVer modelVer = new ModelVer()
+ modelVer.setModelVersionId("model-version-id")
+ modelVer.setModelName("model-name")
+ modelVer.setModelVersion("model-version")
+
+ Optional<ModelVer> modelVerOpt = Optional.of(modelVer)
+
+ AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, vfModule.getModelInvariantId(), vfModule.getModelVersionId())
+ when(client.get(ModelVer.class, modelVerUrl)).thenReturn(modelVerOpt)
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateTnNssiTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateTnNssiTest.groovy
new file mode 100644
index 0000000000..eac79a9473
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateTnNssiTest.groovy
@@ -0,0 +1,135 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 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.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+
+import static org.junit.Assert.assertNotNull
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.*
+
+class DoDeallocateTnNssiTest extends MsoGroovyTest {
+ @Before
+ void init() throws IOException {
+ super.init("DeallocateTnNssiTest")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest() {
+ when(mockExecution.getVariable("msoRequestId")).thenReturn("4c614769-f58a-4556-8ad9-dcd903077c82")
+ when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback")
+ when(mockExecution.getVariable("modelInvariantUuid")).thenReturn("f85cbcc0-ad74-45d7-a5a1-17c8744fdb71")
+ when(mockExecution.getVariable("modelUuid")).thenReturn("36a3a8ea-49a6-4ac8-b06c-89a54544b9b6")
+ when(mockExecution.getVariable("serviceInstanceID")).thenReturn("eb0863e9-a69b-4b17-8a56-f05ad110bef7")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("operationType")).thenReturn("opTypeTest")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("servicename")).thenReturn("5G-test")
+ when(mockExecution.getVariable("networkType")).thenReturn("5G-network")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G-service")
+ when(mockExecution.getVariable("nsiId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56")
+ when(mockExecution.getVariable("jobId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4")
+ when(mockExecution.getVariable("sliceParams")).thenReturn("""
+ {
+ "sliceProfile": {
+ "snssaiList": [
+ "001-100001"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098",
+ "plmnIdList": [
+ "460-00",
+ "460-01"
+ ],
+ "perfReq": {
+ },
+ "coverageAreaTAList": [
+ ],
+ "latency": 2,
+ "maxBandwidth": 100,
+ "resourceSharingLevel": "non-shared"
+ },
+ "transportSliceNetworks": [
+ {
+ "connectionLinks": [
+ {
+ "transportEndpointA": "tranportEp_ID_XXX",
+ "transportEndpointB": "tranportEp_ID_YYY"
+ },
+ {
+ "transportEndpointA": "tranportEp_ID_AAA",
+ "transportEndpointB": "tranportEp_ID_BBB"
+ }
+ ]
+ },
+ {
+ "connectionLinks": [
+ {
+ "transportEndpointA": "tranportEp_ID_CCC",
+ "transportEndpointB": "tranportEp_ID_DDD"
+ },
+ {
+ "transportEndpointA": "tranportEp_ID_EEE",
+ "transportEndpointB": "tranportEp_ID_FFF"
+ }
+ ]
+ }
+ ],
+ "nsiInfo": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "nsiName": "eMBB-001"
+ },
+ "scriptName": "AN1"
+ }""".replaceAll("\\\\s+", ""))
+
+ DoDeallocateTnNssi runScript = new DoDeallocateTnNssi()
+ runScript.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sliceServiceInstanceId"), captor.capture())
+ String sliceServiceInstanceId = captor.getValue()
+ assertNotNull(sliceServiceInstanceId)
+ }
+
+ @Test
+ void testDeleteServiceInstance() {
+ when(mockExecution.getVariable("serviceInstanceID")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G")
+
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ DoDeallocateTnNssi obj = spy(DoDeallocateTnNssi.class)
+ when(obj.getAAIClient()).thenReturn(client)
+ doNothing().when(client).delete(serviceInstanceUri)
+
+ obj.deleteServiceInstance(mockExecution)
+ Mockito.verify(client, times(1)).delete(serviceInstanceUri)
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyTnNssiTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyTnNssiTest.groovy
new file mode 100644
index 0000000000..bbbec3bb46
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoModifyTnNssiTest.groovy
@@ -0,0 +1,174 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2020 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 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.aaiclient.client.aai.AAIObjectType
+import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
+import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+
+import static org.junit.Assert.assertNotNull
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.*
+
+class DoModifyTnNssiTest extends MsoGroovyTest {
+ @Before
+ void init() throws IOException {
+ super.init("DoModifyTnNssiTest")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ void testPreProcessRequest() {
+ when(mockExecution.getVariable("msoRequestId")).thenReturn("4c614769-f58a-4556-8ad9-dcd903077c82")
+ when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback")
+ when(mockExecution.getVariable("modelInvariantUuid")).thenReturn("f85cbcc0-ad74-45d7-a5a1-17c8744fdb71")
+ when(mockExecution.getVariable("modelUuid")).thenReturn("36a3a8ea-49a6-4ac8-b06c-89a54544b9b6")
+ when(mockExecution.getVariable("serviceInstanceID")).thenReturn("eb0863e9-a69b-4b17-8a56-f05ad110bef7")
+ when(mockExecution.getVariable("operationId")).thenReturn("998c2081-5a71-4a39-9ae6-d6b7c5bb50c0")
+ when(mockExecution.getVariable("operationType")).thenReturn("opTypeTest")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("servicename")).thenReturn("5G-test")
+ when(mockExecution.getVariable("networkType")).thenReturn("5G-network")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G-service")
+ when(mockExecution.getVariable("nsiId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56")
+ when(mockExecution.getVariable("jobId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4")
+ when(mockExecution.getVariable("operationType")).thenReturn("activateInstance")
+ when(mockExecution.getVariable("sliceParams")).thenReturn(mockSliceParams())
+
+ DoModifyTnNssi obj = new DoModifyTnNssi()
+ obj.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sliceServiceInstanceId"), captor.capture())
+ String sliceServiceInstanceId = captor.getValue()
+ assertNotNull(sliceServiceInstanceId)
+ }
+
+ @Test
+ void testUpdateServiceInstance() {
+ when(mockExecution.getVariable("sliceServiceInstanceId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2be")
+ when(mockExecution.getVariable("sliceServiceInstanceName")).thenReturn("5G-service")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("5GCustomer")
+ when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("5G")
+ when(mockExecution.getVariable("sliceProfileId")).thenReturn("5ad89cf9-0569-4a93-9306-d8324321e2b1")
+ when(mockExecution.getVariable("modelInvariantUuid")).thenReturn("f85cbcc0-ad74-45d7-a5a1-17c8744fdb71")
+ when(mockExecution.getVariable("modelUuid")).thenReturn("36a3a8ea-49a6-4ac8-b06c-89a54544b9b6")
+ when(mockExecution.getVariable("sliceProfile")).thenReturn(mockSliceProfile())
+
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "5GCustomer", "5G", "5ad89cf9-0569-4a93-9306-d8324321e2be")
+ DoModifyTnNssi obj = spy(DoModifyTnNssi.class)
+ when(obj.getAAIClient()).thenReturn(client)
+
+ obj.updateServiceInstance(mockExecution)
+ }
+
+
+ private String mockSliceParams() {
+ String expect = """{
+ "sliceProfile": {
+ "snssaiList": [
+ "001-100001"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098",
+ "plmnIdList": [
+ "460-00",
+ "460-01"
+ ],
+ "perfReq": {
+ },
+ "coverageAreaTAList": [
+ ],
+ "latency": 2,
+ "maxBandwidth": 100,
+ "resourceSharingLevel": "non-shared"
+ },
+ "transportSliceNetworks": [
+ {
+ "connectionLinks": [
+ {
+ "transportEndpointA": "tranportEp_ID_XXX",
+ "transportEndpointB": "tranportEp_ID_YYY"
+ },
+ {
+ "transportEndpointA": "tranportEp_ID_AAA",
+ "transportEndpointB": "tranportEp_ID_BBB"
+ }
+ ]
+ },
+ {
+ "connectionLinks": [
+ {
+ "transportEndpointA": "tranportEp_ID_CCC",
+ "transportEndpointB": "tranportEp_ID_DDD"
+ },
+ {
+ "transportEndpointA": "tranportEp_ID_EEE",
+ "transportEndpointB": "tranportEp_ID_FFF"
+ }
+ ]
+ }
+ ],
+ "nsiInfo": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "nsiName": "eMBB-001"
+ },
+ "scriptName": "AN1"
+ }"""
+ return expect.replaceAll("\\\\s+", "")
+ }
+
+ private String mockSliceProfile() {
+ String expect = """{
+ "snssaiList": [
+ "001-100001"
+ ],
+ "sliceProfileId": "ab9af40f13f721b5f13539d87484098",
+ "plmnIdList": [
+ "460-00",
+ "460-01"
+ ],
+ "perfReq": {
+ },
+ "coverageAreaTAList": [
+ ],
+ "latency": 2,
+ "maxBandwidth": 100,
+ "resourceSharingLevel": "non-shared"
+ }"""
+ return expect.replaceAll("\\\\s+", "")
+ }
+
+ private String mockServiceModelInfo() {
+ String expect = """{
+ "modelInvariantUuid":"f85cbcc0-ad74-45d7-a5a1-17c8744fdb71",
+ "modelUuid":"36a3a8ea-49a6-4ac8-b06c-89a54544b9b6",
+ "modelVersion":""
+ }"""
+ return expect.replaceAll("\\\\s+", "")
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ModifySliceSubnetTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ModifySliceSubnetTest.groovy
new file mode 100644
index 0000000000..b7515a487c
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ModifySliceSubnetTest.groovy
@@ -0,0 +1,72 @@
+package org.onap.so.bpmn.infrastructure.scripts
+
+import static org.junit.Assert.*
+
+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
+
+class ModifySliceSubnetTest {
+ @Before
+ void init() throws IOException {
+ super.init("ModifySliceSubnet")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+ @Test
+ public void testPreProcessRequest() {
+ when(mockExecution.getVariable("bpmnRequest")).thenReturn("""
+ {
+ "serviceInstanceID": "NSSI-C-001-HDBNJ-NSSMF-01-A-ZX ",
+ "networkType": "an/cn/tn",
+ "globalSubscriberId": "5GCustomer",
+ "subscriptionServiceType": "5G",
+ "additionalProperties": {
+ "nsiInfo": {
+ "nsiId": "NSI-M-001-HDBNJ-NSMF-01-A-ZX",
+ "nsiName": "eMBB-001"
+ },
+ }
+}
+""".replaceAll("\\s+", ""))
+ when(mockExecution.getVariable("mso-request-id")).thenReturn("edb08d97-e0f9-4c71-840a-72080d7be42e")
+ ModifySliceSubnet sliceSubnet = new ModifySliceSubnet()
+ sliceSubnet.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(captor.capture() as String, captor.capture())
+ List<ExecutionEntity> values = captor.getAllValues()
+ assertNotNull(values)
+ }
+
+ @Test
+ void testPrepareInitOperationStatus() {
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("54321")
+ when(mockExecution.getVariable("jobId")).thenReturn("54321")
+ when(mockExecution.getVariable("nsiId")).thenReturn("11111")
+ ModifySliceSubnet sliceSubnet = new ModifySliceSubnet()
+ sliceSubnet.prepareInitOperationStatus(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("initResourceOperationStatus"), captor.capture())
+ String res = captor.getValue()
+ assertNotNull(res)
+ }
+
+
+ @Test
+ void testSendSyncResponse() {
+ when(mockExecution.getVariable("jobId")).thenReturn("123456")
+ ModifySliceSubnet sliceSubnet = new ModifySliceSubnet()
+ sliceSubnet.sendSyncResponse(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("sentSyncResponse"), captor.capture())
+ def updateVolumeGroupRequest = captor.getValue()
+ assertEquals(updateVolumeGroupRequest, true)
+ }
+
+ @Test
+ public void test() {
+ fail("Not yet implemented")
+ }
+
+}