aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/so-bpmn-infrastructure-common
diff options
context:
space:
mode:
Diffstat (limited to 'bpmn/so-bpmn-infrastructure-common')
-rw-r--r--bpmn/so-bpmn-infrastructure-common/pom.xml2
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationService.groovy435
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatus.groovy333
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy76
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationService.groovy429
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceService.groovy263
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy309
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceService.groovy322
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java14
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java79
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcher.java165
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/UpdatePnfEntryInAai.java65
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagement.java2
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java5
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatusTest.groovy344
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcherTest.java182
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java5
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementThrowingException.java5
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/UpdatePnfEntryInAaiTest.java91
19 files changed, 3061 insertions, 65 deletions
diff --git a/bpmn/so-bpmn-infrastructure-common/pom.xml b/bpmn/so-bpmn-infrastructure-common/pom.xml
index 74df3a2c2e..0df3fbe704 100644
--- a/bpmn/so-bpmn-infrastructure-common/pom.xml
+++ b/bpmn/so-bpmn-infrastructure-common/pom.xml
@@ -4,7 +4,7 @@
<parent>
<groupId>org.onap.so</groupId>
<artifactId>bpmn</artifactId>
- <version>1.4.0-SNAPSHOT</version>
+ <version>1.6.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>so-bpmn-infrastructure-common</artifactId>
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationService.groovy
new file mode 100644
index 0000000000..dc33bc930a
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationService.groovy
@@ -0,0 +1,435 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., Ltd.
+ #
+ # Licensed under the Apache License, Version 2.0 (the "License")
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+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.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.WorkflowException
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.AAIResourcesClient
+import org.onap.so.client.aai.entities.AAIResultWrapper
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.db.request.beans.OperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import javax.ws.rs.NotFoundException
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class ActivateCommunicationService extends AbstractServiceTaskProcessor {
+
+ String Prefix="ACS_"
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+
+ JsonUtils jsonUtil = new JsonUtils()
+
+ AAIResourcesClient client = getAAIClient()
+
+ private static final Logger logger = LoggerFactory.getLogger(ActivateCommunicationService.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix + "preProcessRequest Start")
+ execution.setVariable("prefix", Prefix)
+ String msg
+
+ try {
+ // check for incoming json message/input
+ String siRequest = execution.getVariable("bpmnRequest")
+ logger.debug(siRequest)
+
+ String requestId = execution.getVariable("mso-request-id")
+ execution.setVariable("msoRequestId", requestId)
+ logger.info("Input Request:" + siRequest + " reqId:" + requestId)
+
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ if (isBlank(serviceInstanceId)) {
+ msg = "Input serviceInstanceId' is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "globalSubscriberId")
+ if (isBlank(globalSubscriberId)) {
+ msg = "Input globalSubscriberId' is null"
+ logger.info(msg)
+ execution.setVariable("globalSubscriberId", "5GCustomer")
+ } else {
+ execution.setVariable("globalSubscriberId", globalSubscriberId)
+ }
+
+ String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "serviceType")
+ if (isBlank(subscriptionServiceType)) {
+ msg = "Input subscriptionServiceType is null"
+ logger.debug(msg)
+ execution.setVariable("subscriptionServiceType", "5G")
+ } else {
+ execution.setVariable("subscriptionServiceType", subscriptionServiceType)
+ }
+
+ String operationId = jsonUtil.getJsonValue(siRequest, "operationId")
+ execution.setVariable("operationId", operationId)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in preProcessRequest " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "preProcessRequest Exit")
+ }
+
+
+ def checkAAIOrchStatus = { DelegateExecution execution ->
+
+ logger.debug(Prefix + "checkAAIOrchStatus Start")
+
+ String msg
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ String operationType = execution.getVariable("operationType")
+
+ logger.debug("serviceInstanceId: " + serviceInstanceId)
+
+ //check the cms status
+ try {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, serviceInstanceId)
+
+ 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()) {
+
+ if (si.get().getOrchestrationStatus().toLowerCase() == "activated" &&
+ operationType == "deactivation") {
+ logger.info("Service is in active state")
+ execution.setVariable("serviceExpectStatus", "deactivated")
+ execution.setVariable("isContinue", "true")
+ execution.setVariable("requestParam", "deactivate")
+
+ } else if (si.get().getOrchestrationStatus().toLowerCase() == "deactivated" &&
+ operationType == "activation"){
+ logger.info("Service is in de-activated state")
+ execution.setVariable("serviceExpectStatus", "activated")
+ execution.setVariable("isContinue", "true")
+ execution.setVariable("requestParam", "activate")
+
+ } else {
+ execution.setVariable("isContinue", "false")
+ }
+
+ RelationshipList relationshipList = si.get().getRelationshipList()
+ List<Relationship> relationship
+ if (relationshipList != null && (relationship = relationshipList.getRelationship()) != null
+ && relationship.size() > 0) {
+ List<RelationshipData> relationshipDatas = relationship.get(0).getRelationshipData()
+
+ for (RelationshipData relationshipData : relationshipDatas) {
+ execution.setVariable("e2e_" + relationshipData.getRelationshipKey(),
+ relationshipData.getRelationshipValue())
+ }
+ } else {
+ msg = "the communication service has no e2e service"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+ }
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in " + Prefix + "checkAAIOrchStatus: " + ex.getMessage()
+ logger.info( msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ logger.debug(Prefix + "checkAAIOrchStatus Exit")
+ }
+
+
+ def prepareInitOperationStatus = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareInitOperationStatus Start")
+
+ String serviceId = execution.getVariable("serviceInstanceId")
+
+ // 生成 operationId
+ String operationId = execution.getVariable("operationId")
+
+ String operationType = execution.getVariable("operationType")
+
+ OperationStatus initStatus = new OperationStatus()
+ initStatus.setServiceId(serviceId)
+ initStatus.setOperationId(operationId)
+ initStatus.setOperation(operationType)
+ initStatus.setUserId(execution.getVariable("globalSubscriberId") as String)
+ initStatus.setResult("processing")
+ initStatus.setProgress("0")
+ initStatus.setReason("")
+ initStatus.setOperationContent("communication service active operation start")
+
+ requestDBUtil.prepareUpdateOperationStatus(execution, initStatus)
+
+ logger.debug(Prefix + "prepareInitOperationStatus Exit")
+ }
+
+
+ def sendSyncResponse = { DelegateExecution execution ->
+ logger.debug(Prefix + "sendSyncResponse Start")
+ try {
+ String operationId = execution.getVariable("operationId")
+
+ String restRequest = """{"operationId":"${operationId}"}""".trim()
+ logger.debug(" sendSyncResponse to APIH:" + "\n" + restRequest)
+
+ sendWorkflowResponse(execution, 202, restRequest)
+ execution.setVariable("sentSyncResponse", true)
+ } catch (Exception ex) {
+ String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "sendSyncResponse Exit")
+ }
+
+
+ def preRequestSend2NSMF = { DelegateExecution execution ->
+ logger.debug(Prefix + "preRequestSend2NSMF Start")
+ try {
+
+ String e2eServiceInstanceId = execution.getVariable("e2e_service-instance.service-instance-id")
+ execution.setVariable("e2eServiceInstanceId", e2eServiceInstanceId)
+
+ String requestParam = execution.getVariable("requestParam")
+ //String NSMF_endpoint = "/onap/so/infra/e2eServiceInstances/v3"
+ def NSMF_endpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
+ def url = NSMF_endpoint + "/e2eServiceInstances/v3/${e2eServiceInstanceId}/${requestParam}"
+ execution.setVariable("NSMF_endpoint", url)
+
+ //get from model catalog inputs
+ String payload = """
+ {
+ "globalSubscriberId": "${execution.getVariable("globalSubscriberId")}",
+ "serviceType": "${execution.getVariable("subscriptionServiceType")}"
+ }
+ """
+ execution.setVariable("CSMF_NSMFRequest", payload.replaceAll("\\s+", ""))
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in " + Prefix + "preRequestSend2NSMF. " + ex.getMessage()
+ logger.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ logger.debug(Prefix + "preRequestSend2NSMF Exit")
+ }
+
+
+ def processNSMFResponse = { DelegateExecution execution ->
+ logger.debug(Prefix + "processNSMFResponse Start")
+ //oof
+ try {
+ def CSMF_NSMFResponseCode = execution.getVariable("CSMF_NSMFResponseCode") as Integer
+ if (CSMF_NSMFResponseCode >= 200 && CSMF_NSMFResponseCode < 400) {
+ def CSMF_NSMFResponse = execution.getVariable("CSMF_NSMFResponse") as String
+ def e2eOperationId = jsonUtil.getJsonValue(CSMF_NSMFResponse, "operationId")
+
+ execution.setVariable("e2eOperationId", e2eOperationId)
+ execution.setVariable("ProcessNsmfSuccess", "OK")
+ } else {
+ execution.setVariable("ProcessNsmfSuccess", "ERROR")
+ execution.setVariable("operationStatus", "error")
+ execution.setVariable("operationContent",
+ "communication service " + execution.getVariable("operationType")
+ + " operation error: nsmf response fail")
+ execution.setVariable("orchestrationStatus", "error")
+ }
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ String msg = "Exception in " + Prefix + "processOOFResponse. " + ex.getMessage()
+ logger.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "processNSMFResponse Exit")
+ }
+
+
+ def prepareUpdateOperationStatus = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareUpdateOperationStatus Start")
+ // update status creating
+ OperationStatus status = new OperationStatus()
+ status.setServiceId(execution.getVariable("serviceInstanceId") as String)
+ status.setOperationId(execution.getVariable("operationId") as String)
+ status.setOperation(execution.getVariable("operationType") as String)
+ status.setResult("processing")
+ status.setProgress("20")
+ status.setOperationContent("communication service "+ execution.getVariable("operationType")
+ + " operation processing: waiting nsmf service create finished")
+ status.setUserId(execution.getVariable("globalSubscriberId") as String)
+
+ requestDBUtil.prepareUpdateOperationStatus(execution, status)
+ logger.debug(Prefix + "prepareUpdateOperationStatus Exit")
+ }
+
+
+ //todo
+ def prepareCallCheckProcessStatus = { DelegateExecution execution ->
+ logger.debug(Prefix + "prepareCallCheckProcessStatus Start")
+
+ 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", "communication service")
+
+ execution.setVariable("timeOut", 3 * 60 * 60 * 1000)
+
+ def successParamMap = new HashMap<String, Object>()
+ successParamMap.put("orchestrationStatus", execution.getVariable("serviceExpectStatus"))
+
+ execution.setVariable("successParamMap", successParamMap)
+
+ def errorParamMap = new HashMap<String, Object>()
+ errorParamMap.put("orchestrationStatus", "error")
+
+ execution.setVariable("errorParamMap", errorParamMap)
+
+ def timeOutParamMap = new HashMap<String, Object>()
+ timeOutParamMap.put("orchestrationStatus", "error")
+
+ execution.setVariable("timeOutParamMap", timeOutParamMap)
+
+ execution.setVariable("initProgress", 20)
+ execution.setVariable("endProgress", 90)
+
+ logger.debug(Prefix + "prepareCallCheckProcessStatus Exit")
+ }
+
+
+ /**
+ * prepare update operation status to complete after NSMF process success
+ * @param execution
+ */
+ def prepareCompleteStatus = { DelegateExecution execution ->
+
+ logger.debug(Prefix + "prepareCompleteStatus Start")
+ String operationType = execution.getVariable("operationType")
+ OperationStatus status = new OperationStatus()
+ status.setServiceId(execution.getVariable("serviceInstanceId") as String)
+ status.setOperationId(execution.getVariable("operationId") as String)
+ status.setOperation(operationType)
+ status.setResult(execution.getVariable("operationStatus") as String)
+ status.setProgress("100")
+ status.setOperationContent(execution.getVariable("operationContent") as String)
+ status.setUserId(execution.getVariable("globalSubscriberId") as String)
+
+ requestDBUtil.prepareUpdateOperationStatus(execution, status)
+ logger.debug("prepareCompleteStatus end, serviceInstanceId: " + execution.getVariable("serviceInstanceId")
+ + ", operationId: " + execution.getVariable("operationId"))
+
+ logger.debug(Prefix + "prepareCompleteStatus Exit")
+ }
+
+
+ /**
+ * update NSMF complete status to AAI when the NSMF process finished
+ * @param execution
+ */
+ def updateFinishStatusInAAI = { DelegateExecution execution ->
+ logger.debug(Prefix + "updateFinishStatusInAAI Start")
+ String msg
+ try {
+
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String orchestrationStatus = execution.getVariable("orchestrationStatus")
+ // create service
+ ServiceInstance csi = new ServiceInstance()
+ csi.setOrchestrationStatus(orchestrationStatus)
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalSubscriberId, subscriptionServiceType, serviceInstanceId)
+ client.update(uri, csi)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in complete communication service " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.debug(Prefix + "updateFinishStatusInAAI Exit")
+ }
+
+
+ public sendSyncError = { DelegateExecution execution ->
+ logger.debug("sendSyncError Start")
+ try {
+ String errorMessage
+ if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
+ WorkflowException wfe = execution.getVariable("WorkflowException") as WorkflowException
+ errorMessage = wfe.getErrorMessage()
+ } else {
+ errorMessage = "Sending Sync Error."
+ }
+
+ String buildWorkflowException =
+ """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
+ <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
+ <aetgt:ErrorCode>7000</aetgt:ErrorCode>
+ </aetgt:WorkflowException>"""
+
+ logger.debug(buildWorkflowException)
+ sendWorkflowResponse(execution, 500, buildWorkflowException)
+
+ } catch (Exception ex) {
+ logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
+ }
+ logger.debug(Prefix + "sendSyncError Exit")
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatus.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatus.groovy
new file mode 100644
index 0000000000..3233bfff61
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatus.groovy
@@ -0,0 +1,333 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., Ltd.
+ #
+ # Licensed under the Apache License, Version 2.0 (the "License")
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.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.client.aai.AAIResourcesClient
+import org.onap.so.db.request.beans.OperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import java.util.concurrent.TimeUnit
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class CheckServiceProcessStatus extends AbstractServiceTaskProcessor {
+
+
+ String Prefix="CSPS_"
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ RequestDBUtil requestDBUtil = new RequestDBUtil()
+
+ JsonUtils jsonUtil = new JsonUtils()
+
+ AAIResourcesClient client = getAAIClient()
+
+ private static final Logger logger = LoggerFactory.getLogger(CheckServiceProcessStatus.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ logger.debug(Prefix + "CheckServiceProcessStatus preProcessRequest Start")
+ execution.setVariable("prefix", Prefix)
+
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ String operationId = execution.getVariable("operationId")
+ String parentServiceInstanceId = execution.getVariable("parentServiceInstanceId")
+ String parentOperationId = execution.getVariable("parentOperationId")
+
+ if (isBlank(serviceInstanceId) || isBlank(operationId)) {
+ String msg = "Exception in" + Prefix + "preProcessRequest: Input serviceInstanceId or operationId is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ if (isBlank(parentServiceInstanceId) || isBlank(parentOperationId)) {
+ execution.setVariable("isNeedUpdateParentStatus", false)
+ }
+
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ if (isBlank(globalSubscriberId)) {
+ execution.setVariable("globalSubscriberId", "5GCustomer")
+ }
+
+ // serviceType: type of service
+ String serviceType = execution.getVariable("processServiceType")
+ if (isBlank(serviceType)) {
+ execution.setVariable("processServiceType", "service")
+ }
+
+ // operationType: type of service
+ String operationType = execution.getVariable("operationType")
+ if (isBlank(operationType)) {
+ execution.setVariable("operationType", "CREATE")
+ }
+
+ //successConditions: processing end success conditions
+ List<String> successConditions = execution.getVariable("successConditions") as List
+
+ //errorConditions: processing end error conditions
+ List<String> errorConditions = execution.getVariable("errorConditions") as List
+
+ if ((successConditions == null || successConditions.size() < 1)
+ && (errorConditions == null || errorConditions.size() < 1)) {
+ String msg = "Exception in" + Prefix + "preProcessRequest: conditions is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ } else {
+ for (int i = 0; i < successConditions.size(); i++) {
+ String condition = successConditions.get(i)
+ successConditions.set(i, condition.toLowerCase())
+ }
+ for (int i = 0; i < errorConditions.size(); i++) {
+ String condition = errorConditions.get(i)
+ errorConditions.set(i, condition.toLowerCase())
+ }
+ }
+
+ execution.setVariable("startTime", System.currentTimeMillis())
+
+ String initProgress = execution.getVariable("initProgress")
+
+ if (isBlank(initProgress)) {
+ execution.setVariable("initProgress", 0)
+ }
+
+ String endProgress = execution.getVariable("endProgress")
+
+ if (isBlank(endProgress)) {
+ execution.setVariable("endProgress", 100)
+ }
+
+ execution.setVariable("progress", 0)
+ logger.debug(Prefix + "preProcessRequest Exit")
+ }
+
+
+ /**
+ * check service status through request operation id, update operation status
+ */
+ def preCheckServiceStatusReq = { DelegateExecution execution ->
+ logger.trace(Prefix + "preCheckServiceStatusReq Start")
+ String serviceInstanceId = execution.getVariable("serviceInstanceId") as String
+ String operationId = execution.getVariable("operationId") as String
+ requestDBUtil.getOperationStatus(execution, serviceInstanceId, operationId)
+ logger.trace(Prefix + "preCheckServiceStatusReq Exit")
+ }
+
+
+ /**
+ * handle service status, if service status is finished or error, set the service status
+ * @param execution
+ */
+ def handlerServiceStatusResp = { DelegateExecution execution ->
+ logger.trace(Prefix + "handlerServiceStatusResp Start")
+ String msg
+ try {
+ def dbResponseCode = execution.getVariable("dbResponseCode") as Integer
+ if (dbResponseCode >= 200 && dbResponseCode < 400) {
+ String dbResponse = execution.getVariable("dbResponse")
+ def dbResponseJson = jsonUtil.xml2json(dbResponse) as String
+
+ String result = jsonUtil.getJsonValue(dbResponseJson,
+ "Envelope.Body.getServiceOperationStatusResponse.return.result")
+
+ if (isSuccessCompleted(execution, result)) {
+
+ handlerSuccess(execution, result)
+ execution.setVariable("isAllFinished", "true")
+
+ logger.debug(Prefix + "handlerServiceStatusResp: service success finished, dbResponse_result: "
+ + result)
+
+ } else if (isErrorCompleted(execution, result)) {
+
+ handlerError(execution, result)
+ execution.setVariable("isAllFinished", "true")
+
+ logger.debug(Prefix + "handlerServiceStatusResp: service error finished, dbResponse_result: "
+ + result)
+
+ } else {
+ String progress = jsonUtil.getJsonValue(dbResponseJson,
+ "Envelope.Body.getServiceOperationStatusResponse.return.progress")
+
+ String oldProgress = execution.getVariable("progress")
+
+ if (progress == oldProgress) {
+ execution.setVariable("isNeedUpdateDB", false)
+ } else {
+ execution.setVariable("progress", progress)
+ execution.setVariable("isNeedUpdateDB", true)
+ }
+ execution.setVariable("isAllFinished", "false")
+ TimeUnit.SECONDS.sleep(10)
+ }
+ } else {
+ execution.setVariable("isAllFinished", "false")
+ //todo: retry
+ TimeUnit.MILLISECONDS.sleep(10)
+ }
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in " + Prefix + "handlerServiceStatusResp: " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ logger.trace(Prefix + "handlerServiceStatusResp Exit")
+ }
+
+
+ def timeWaitDelay = { DelegateExecution execution ->
+
+ Long startTime = execution.getVariable("startTime") as Long
+ Long timeOut = execution.getVariable("timeOut") as Long
+
+ timeOut = timeOut == null ? 3 * 60 * 60 * 1000 : timeOut
+
+ if (System.currentTimeMillis() - startTime > timeOut) {
+
+ handlerTimeOut(execution)
+ execution.setVariable("isTimeOut", "YES")
+
+ } else {
+ execution.setVariable("isTimeOut", "NO")
+ }
+ }
+
+
+ private handlerTimeOut = { DelegateExecution execution ->
+
+ Map<String, Object> paramMap = execution.getVariable("timeOutParamMap") as Map
+
+ handlerProcess(execution, "error", paramMap, "error", "with timeout")
+ }
+
+
+ private handlerSuccess = { DelegateExecution execution, String result ->
+
+ Map<String, Object> paramMap = execution.getVariable("successParamMap") as Map
+
+ handlerProcess(execution, result, paramMap, "deactivated", "success")
+ }
+
+
+ private handlerError = { DelegateExecution execution, String result ->
+
+ Map<String, Object> paramMap = execution.getVariable("errorParamMap") as Map
+
+ handlerProcess(execution, result, paramMap, "error", "with error")
+ }
+
+
+ private handlerProcess = { DelegateExecution execution, String result, def paramMap, def status, def msg ->
+
+ if (paramMap != null) {
+ for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
+ execution.setVariable(entry.getKey(), entry.getValue())
+ }
+ }
+
+
+ if (isBlank(execution.getVariable("operationStatus") as String)) {
+ execution.setVariable("operationStatus", result)
+ }
+
+
+ if (isBlank(execution.getVariable("operationContent") as String)) {
+ String operationContent = execution.getVariable("processServiceType") + " " +
+ execution.getVariable("operationType") + " operation finished " + msg
+ execution.setVariable("operationContent", operationContent)
+ }
+
+ if (isBlank(execution.getVariable("orchestrationStatus") as String)) {
+ execution.setVariable("orchestrationStatus", status)
+ }
+
+ }
+
+
+ /**
+ * judge if the service processing success finished
+ */
+ private isSuccessCompleted = { DelegateExecution execution, String result ->
+
+ //successConditions: processing end success conditions
+ List<String> successConditions = execution.getVariable("successConditions") as List
+
+ result = result.toLowerCase()
+ if (successConditions.contains(result)) {
+ return true
+ }
+ return false
+ }
+
+
+ /**
+ * judge if the service processing error finished
+ */
+ private isErrorCompleted = { DelegateExecution execution, String result ->
+
+ //errorConditions: processing end error conditions
+ List<String> errorConditions = execution.getVariable("errorConditions") as List
+
+ result = result.toLowerCase()
+ if (errorConditions.contains(result)) {
+ return true
+ }
+ return false
+ }
+
+
+ def preUpdateOperationProgress = { DelegateExecution execution ->
+ logger.trace(Prefix + "prepareUpdateOperationStatus Start")
+
+ def progress = execution.getVariable("progress") as Integer
+ def initProgress = execution.getVariable("initProgress") as Integer
+ def endProgress = execution.getVariable("endProgress") as Integer
+
+ def resProgress = (initProgress + (endProgress - initProgress) / 100 * progress) as Integer
+
+ def operationType = execution.getVariable("operationType")
+ def operationContent = execution.getVariable("processServiceType") + " " +
+ operationType + " operation processing " + resProgress
+
+ // update status creating
+ OperationStatus status = new OperationStatus()
+ status.setServiceId(execution.getVariable("parentServiceInstanceId") as String)
+ status.setOperationId(execution.getVariable("parentOperationId") as String)
+ status.setOperation(operationType as String)
+ status.setResult("processing")
+ status.setProgress(resProgress as String)
+ status.setOperationContent(operationContent as String)
+ status.setUserId(execution.getVariable("globalSubscriberId") as String)
+
+ requestDBUtil.prepareUpdateOperationStatus(execution, status)
+ logger.trace(Prefix + "prepareUpdateOperationStatus Exit")
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy
index 4b3c1aa7b4..3da4161953 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy
@@ -163,36 +163,20 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
String serInput = jsonUtil.getJsonValue(resourceInputTmp, "requestsInputs")
switch (modelName) {
- case ~/[\w\s\W]*OLT[\w\s\W]*/ :
+ case ~/[\w\s\W]*OLT[\w\s\W]*/ : // for backward compatibilty only, this case will be deprecated
+ case ~/[\w\s\W]*AccessConnectivity[\w\s\W]*/ :
// get the required properties and update in resource input
def resourceInput = resourceInputObj.getResourceParameters()
String incomingRequest = resourceInputObj.getRequestsInputs()
String serviceParameters = JsonUtils.getJsonValue(incomingRequest, "service.parameters")
String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs")
- String cvlan
- String svlan
- String remoteId
-
- List<Metadatum> metadatum = getMetaDatum(resourceInputObj.getGlobalSubscriberId(),
- resourceInputObj.getServiceType(),
- resourceInputObj.getServiceInstanceId())
- for(Metadatum datum: metadatum) {
- if (datum.getMetaname().equalsIgnoreCase("cvlan")) {
- cvlan = datum.getMetaval()
- }
-
- if (datum.getMetaname().equalsIgnoreCase("svlan")) {
- svlan = datum.getMetaval()
- }
-
- if (datum.getMetaname().equalsIgnoreCase("remoteId")) {
- remoteId = datum.getMetaval()
- }
- }
-
- logger.debug("cvlan: "+cvlan+" | svlan: "+svlan+" | remoteId: "+remoteId)
-
+ String cvlan = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.cvlan")
+ String svlan = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.svlan")
+ String remoteId = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.edgeinternetprofile_ip_remote_id")
String manufacturer = jsonUtil.getJsonValue(serInput,
"service.parameters.requestInputs.ont_ont_manufacturer")
String ontsn = jsonUtil.getJsonValue(serInput,
@@ -209,7 +193,8 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
logger.debug("new resource Input :" + resourceInputObj.toString())
break
- case ~/[\w\s\W]*EdgeInternetProfile[\w\s\W]*/ :
+ case ~/[\w\s\W]*EdgeInternetProfile[\w\s\W]*/ : // for backward compatibilty only, this case will be deprecated
+ case ~/[\w\s\W]*InternetProfile[\w\s\W]*/ :
// get the required properties and update in resource input
def resourceInput = resourceInputObj.getResourceParameters()
String incomingRequest = resourceInputObj.getRequestsInputs()
@@ -217,37 +202,34 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs")
JSONObject inputParameters = new JSONObject(requestInputs)
- String cvlan
- String svlan
- String remoteId
+ String cvlan = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.cvlan")
+ String svlan = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.svlan")
String manufacturer = jsonUtil.getJsonValue(serInput,
"service.parameters.requestInputs.ont_ont_manufacturer")
-
+ String remoteId = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.edgeinternetprofile_ip_remote_id")
String ontsn = jsonUtil.getJsonValue(serInput,
"service.parameters.requestInputs.ont_ont_serial_num")
-
- List<Metadatum> metadatum = getMetaDatum(resourceInputObj.getGlobalSubscriberId(),
- resourceInputObj.getServiceType(),
- resourceInputObj.getServiceInstanceId())
- for(Metadatum datum: metadatum) {
- if (datum.getMetaname().equalsIgnoreCase("cvlan")) {
- cvlan = datum.getMetaval()
- }
-
- if (datum.getMetaname().equalsIgnoreCase("svlan")) {
- svlan = datum.getMetaval()
- }
-
- if (datum.getMetaname().equalsIgnoreCase("remoteId")) {
- remoteId = datum.getMetaval()
- }
- }
+ String serviceType = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.edgeinternetprofile_ip_service_type")
+ String macAddr = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.edgeinternetprofile_ip_rg_mac_addr")
+ String upStream = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.edgeinternetprofile_ip_upstream_speed")
+ String downStream = jsonUtil.getJsonValue(serInput,
+ "service.parameters.requestInputs.edgeinternetprofile_ip_downstream_speed")
String uResourceInput = jsonUtil.addJsonValue(resourceInput, "requestInputs.c_vlan", cvlan)
uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.s_vlan", svlan)
uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.manufacturer", manufacturer)
- uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_access_id", remoteId)
+ uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_remote_id", remoteId)
uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ont_sn", ontsn)
+ uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_service_type", serviceType)
+ uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_rg_mac_addr", macAddr)
+ uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_upstream_speed", upStream)
+ uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_downstream_speed", downStream)
logger.debug("old resource input:" + resourceInputObj.toString())
resourceInputObj.setResourceParameters(uResourceInput)
execution.setVariable(Prefix + "resourceInput", resourceInputObj.toString())
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationService.groovy
new file mode 100644
index 0000000000..00b0b37b18
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCommunicationService.groovy
@@ -0,0 +1,429 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., Ltd.
+ #
+ # Licensed under the Apache License, Version 2.0 (the "License")
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.bpmn.infrastructure.scripts
+
+
+import org.camunda.bpm.engine.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.aai.domain.yang.CommunicationServiceProfile
+import org.onap.aai.domain.yang.CommunicationServiceProfiles
+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.WorkflowException
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.AAIResourcesClient
+import org.onap.so.client.aai.entities.AAIResultWrapper
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.db.request.beans.OperationStatus
+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
+
+class DeleteCommunicationService extends AbstractServiceTaskProcessor {
+ private final String PREFIX ="DeleteCommunicationService"
+ private final Long TIMEOUT = 60 * 60 * 1000
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ private RequestDBUtil requestDBUtil = new RequestDBUtil()
+ private static final Logger LOGGER = LoggerFactory.getLogger(DeleteCommunicationService.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ execution.setVariable("prefix",PREFIX)
+ String msg = ""
+
+ LOGGER.trace("Starting preProcessRequest")
+
+ try {
+ // check for incoming json message/input
+ String siRequest = execution.getVariable("bpmnRequest")
+ String requestId = execution.getVariable("mso-request-id")
+ execution.setVariable("msoRequestId", requestId)
+ execution.setVariable("operationType", "DELETE")
+
+ //communication service id
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ if (isBlank(serviceInstanceId)) {
+ msg = "communication-service id is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ LOGGER.info("Input Request: ${siRequest}, reqId: ${requestId}, serviceInstanceId: ${serviceInstanceId}")
+
+ //requestParameters
+ checkAndSetRequestParam(siRequest,"globalSubscriberId",false,execution)
+ checkAndSetRequestParam(siRequest,"serviceType",false,execution)
+ checkAndSetRequestParam(siRequest,"operationId",false,execution)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (any) {
+ msg = "Exception in preProcessRequest " + any.getCause()
+ LOGGER.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ LOGGER.trace("Exit preProcessRequest")
+ }
+
+
+ /**
+ * prepare update operation status
+ * @param execution
+ */
+ void preInitUpdateOperationStatus(DelegateExecution execution){
+ LOGGER.trace(" ======== STARTED initUpdateOperationStatus Process ======== ")
+ try{
+ execution.setVariable("result","processing")
+ execution.setVariable("progress","0")
+ execution.setVariable("operationContent","delete communication service operation start")
+ setOperationStatus(execution)
+
+ }catch(Exception e){
+ LOGGER.error("Exception Occured Processing initUpdateOperationStatus. Exception is:\n" + e)
+ execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during initUpdateOperationStatus Method:\n" + e.getMessage())
+ }
+ LOGGER.trace("======== COMPLETED initUpdateOperationStatus Process ======== ")
+ }
+
+ /**
+ * send sync response
+ * @param execution
+ */
+ void sendSyncResponse(DelegateExecution execution) {
+ LOGGER.debug("Begin sendSyncResponse")
+
+ try {
+ String operationId = execution.getVariable("operationId")
+ String syncResponse = """{"operationId":"${operationId}"}""".trim()
+ sendWorkflowResponse(execution, 202, syncResponse)
+
+ } catch (Exception ex) {
+ String msg = "Exception in sendSyncResponse: " + ex.getMessage()
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ LOGGER.debug("Exit sendSyncResponse")
+ }
+
+ /**
+ * query CommunicationSerive from AAI
+ * save e2eslice-service instance id and service name
+ * @param execution
+ */
+ private void queryCommunicationSeriveFromAAI(DelegateExecution execution)
+ {
+ LOGGER.trace(" ***** begin queryCommunicationSeriveFromAAI *****")
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+
+ String errorMsg = "query communication service from aai failed"
+ AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
+ Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
+ if(si.isPresent())
+ {
+ String serviceInstName = si.get()?.getServiceInstanceName()
+ String e2eSliceServiceInstId
+ if(si.isPresent())
+ {
+ List<Relationship> relationshipList = si.get().getRelationshipList()?.getRelationship()
+ for (Relationship relationship : relationshipList)
+ {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo == "service-instance")
+ {
+ String relatedLink = relationship.getRelatedLink()?:""
+ e2eSliceServiceInstId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
+ break
+ }
+ }
+ }
+ execution.setVariable("e2eSliceServiceInstanceId", e2eSliceServiceInstId)
+ execution.setVariable("serviceInstanceName", serviceInstName ?: "")
+ LOGGER.info("communication-service Id: ${serviceInstanceId}, e2eslice-service Id: ${e2eSliceServiceInstId}, serviceName: ${serviceInstName}")
+ }
+ LOGGER.debug(" ***** Exit queryCommunicationSeriveFromAAI *****")
+ }
+
+ /**
+ * query AAI
+ * @param execution
+ * @param aaiObjectType
+ * @param instanceId
+ * @return AAIResultWrapper
+ */
+ private AAIResultWrapper queryAAI(DelegateExecution execution, AAIObjectType aaiObjectType, String instanceId, String errorMsg)
+ {
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("serviceType")
+
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(aaiObjectType, globalSubscriberId, serviceType, instanceId)
+ if (!resourceClient.exists(resourceUri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMsg)
+ }
+ AAIResultWrapper wrapper = resourceClient.get(resourceUri, NotFoundException.class)
+ return wrapper
+ }
+
+
+ /**
+ * 再次调用deleteE2EServiceInstance接口,然后获取到operationid,
+ */
+ void sendRequest2NSMFWF(DelegateExecution execution) {
+ LOGGER.trace("begin preRequestSend2NSMF")
+ try {
+ //url:/onap/so/infra/e2eServiceInstances/v3/{serviceInstanceId}"
+ def NSMF_endpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
+ String url = "${NSMF_endpoint}/e2eServiceInstances/v3/${execution.getVariable("e2eSliceServiceInstanceId")}"
+
+ String requestBody = """
+ {
+ "globalSubscriberId": "${execution.getVariable("globalSubscriberId")}",
+ "serviceType": "${execution.getVariable("serviceType")}"
+ }
+ """
+ requestBody.replaceAll("\\s+", "")
+
+ String basicAuthValue = UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(new URL(url), ONAPComponents.SO)
+ httpClient.addAdditionalHeader("Authorization", basicAuthValue)
+ httpClient.addAdditionalHeader("Accept", "application/json")
+ Response httpResponse = httpClient.delete(requestBody)
+ handleNSSMFWFResponse(httpResponse, execution)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (any) {
+ String msg = "Exception in DeleteCommunicationService.preRequestSend2NSMF. " + any.getCause()
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ LOGGER.trace("exit preRequestSend2NSMF")
+ }
+
+ /**
+ * prepare to call sub process
+ * @param execution
+ */
+ void prepareCallCheckProcessStatus(DelegateExecution execution)
+ {
+ LOGGER.debug(PREFIX + "prepareCallCheckProcessStatus Start")
+
+ 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", "communication service")
+ execution.setVariable("subOperationType", "DELETE")
+ execution.setVariable("initProgress", 20)
+ execution.setVariable("endProgress",90)
+
+ execution.setVariable("timeOut", TIMEOUT)
+
+ LOGGER.debug(PREFIX + "prepareCallCheckProcessStatus Exit")
+ }
+
+ /**
+ * delete communication profile from AAI
+ * @param execution
+ */
+ void delCSProfileFromAAI(DelegateExecution execution)
+ {
+ LOGGER.debug("start delete communication service profile from AAI")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("serviceType")
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+
+ String profileId
+ try
+ {
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.COMMUNICATION_PROFILE_ALL, globalSubscriberId, serviceType, serviceInstanceId)
+ AAIResultWrapper wrapper = resourceClient.get(resourceUri, NotFoundException.class)
+ Optional<CommunicationServiceProfiles> csProfilesOpt = wrapper.asBean(CommunicationServiceProfiles.class)
+ if(csProfilesOpt.isPresent()){
+ CommunicationServiceProfiles csProf
+ iles = csProfilesOpt.get()
+ CommunicationServiceProfile csProfile = csProfiles.getCommunicationServiceProfile().get(0)
+ profileId = csProfile ? csProfile.getProfileId() : ""
+ }
+ resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.COMMUNICATION_SERVICE_PROFILE, globalSubscriberId, serviceType, serviceInstanceId, profileId)
+ if (!resourceClient.exists(resourceUri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "communication service profile was not found in aai")
+ }
+
+ resourceClient.delete(resourceUri)
+ LOGGER.debug("end delete communication service profile from AAI")
+ }
+ catch (any)
+ {
+ String msg = "delete communication service profile from aai failed! cause-"+any.getCause()
+ LOGGER.error(any.printStackTrace())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+
+ }
+
+ /**
+ * delete communication service from AAI
+ * @param execution
+ */
+ void delCSFromAAI(DelegateExecution execution)
+ {
+ try
+ {
+ LOGGER.debug("start delete communication service from AAI")
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), execution.getVariable("serviceInstanceId"))
+ resourceClient.delete(serviceInstanceUri)
+
+ execution.setVariable("progress", "100")
+ execution.setVariable("result", "finished")
+ execution.setVariable("operationContent", "CSMF completes service terminated.")
+ setOperationStatus(execution)
+ LOGGER.debug("end delete communication service from AAI")
+ }
+ catch (any)
+ {
+ LOGGER.error("Error occured within delCSFromAAI method, cause: ${any.getCause()} ")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during delete communication service from aai")
+ }
+ }
+
+ void sendSyncError(DelegateExecution execution)
+ {
+ LOGGER.debug("Starting sendSyncError")
+
+ try {
+ String errorMessage
+ if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
+ WorkflowException wfe = execution.getVariable("WorkflowException")
+ errorMessage = wfe.getErrorMessage()
+ } else {
+ errorMessage = "Sending Sync Error."
+ }
+
+ String buildworkflowException =
+ """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
+ <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
+ <aetgt:ErrorCode>7000</aetgt:ErrorCode>
+ </aetgt:WorkflowException>"""
+
+ LOGGER.debug(buildworkflowException)
+ sendWorkflowResponse(execution, 500, buildworkflowException)
+
+ } catch (Exception ex) {
+ LOGGER.error("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
+ }
+ }
+
+ /**
+ * prepare update operation status
+ * @param execution
+ */
+ void preFailedOperationStatus(DelegateExecution execution)
+ {
+ LOGGER.debug(" ======== STARTED preFailedOperationStatus Process ======== ")
+
+ execution.setVariable("progress", "100")
+ execution.setVariable("result", "error")
+ execution.setVariable("operationContent", "terminate service failure")
+
+ WorkflowException wfex = execution.getVariable("WorkflowException") as WorkflowException
+ String errorMessage = wfex.getErrorMessage()
+ errorMessage = errorMessage.length() > 200 ? errorMessage.substring(0,200) + "......" : errorMessage
+ execution.setVariable("reason", errorMessage)
+ setOperationStatus(execution)
+
+ LOGGER.debug("======== COMPLETED prepareEndOperationStatus Process ======== ")
+ }
+
+ /**
+ * prepare Operation status
+ * @param execution
+ * @param operationType
+ */
+ private void setOperationStatus(DelegateExecution execution)
+ {
+ OperationStatus operationStatus = new OperationStatus()
+ operationStatus.setServiceId(execution.getVariable("serviceInstanceId"))
+ operationStatus.setOperationId(execution.getVariable("operationId"))
+ operationStatus.setUserId(execution.getVariable("globalSubscriberId"))
+ //interface not support update
+ operationStatus.setServiceName(execution.getVariable("serviceInstanceName"))
+ operationStatus.setResult(execution.getVariable("result"))
+ operationStatus.setProgress(execution.getVariable("progress"))
+ operationStatus.setOperationContent(execution.getVariable("operationContent"))
+ operationStatus.setReason(execution.getVariable("reason")?:"")
+ operationStatus.setOperation("DELETE")
+
+ requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
+ }
+
+ void prepareFailureStatus(DelegateExecution execution)
+ {
+ execution.setVariable("progress", "100")
+ execution.setVariable("operationContent", "terminate service failure.")
+ setOperationStatus(execution)
+ LOGGER.debug("${PREFIX}-prepareFailureStatus,result:${execution.getVariable("result")}, reason: ${execution.getVariable("reason")}")
+ }
+
+ /**
+ * check request json and save parameter to execution
+ * @param siRequest
+ * @param paraName
+ * @param isErrorException
+ * @param execution
+ */
+ private void checkAndSetRequestParam(String siRequest, String paraName, boolean isErrorException, DelegateExecution execution)
+ {
+ String msg = ""
+ String paramValue = jsonUtil.getJsonValue(siRequest, paraName)
+ if (isBlank(paramValue)) {
+ msg = "Input ${paraName} is null"
+ LOGGER.error(msg)
+ if(isErrorException)
+ {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ } else {
+ execution.setVariable(paraName, paramValue)
+ }
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceService.groovy
new file mode 100644
index 0000000000..f0d43cf8d7
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSliceService.groovy
@@ -0,0 +1,263 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (c) 2019, CMCC Technologies Co., Ltd.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+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.MsoUtils
+import org.onap.so.bpmn.common.scripts.RequestDBUtil
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.AAIResourcesClient
+import org.onap.so.client.aai.entities.AAIResultWrapper
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.db.request.beans.OperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import javax.ws.rs.NotFoundException
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+class DeleteSliceService extends AbstractServiceTaskProcessor {
+
+ String Prefix="DELSS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ private RequestDBUtil requestDBUtil = new RequestDBUtil()
+
+ private static final Logger logger = LoggerFactory.getLogger( DeleteSliceService.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ execution.setVariable("prefix", Prefix)
+ String msg = ""
+
+ logger.trace("Starting preProcessRequest")
+
+ try {
+ // check for incoming json message/input
+ String siRequest = execution.getVariable("bpmnRequest")
+ String requestId = execution.getVariable("mso-request-id")
+ execution.setVariable("msoRequestId", requestId)
+
+ //e2eslice-service instance id
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ if (isBlank(serviceInstanceId)) {
+ msg = "e2eslice-service id is null"
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+ logger.info("Input Request: ${siRequest}, reqId: ${requestId}, e2eslice-service: ${serviceInstanceId}")
+
+ //subscriberInfo
+ checkAndSetRequestParam(siRequest,"globalSubscriberId",false, execution)
+ checkAndSetRequestParam(siRequest,"serviceType",false, execution)
+ checkAndSetRequestParam(siRequest,"operationId",false, execution)
+
+ //prepare init operation status
+ execution.setVariable("progress", "0")
+ execution.setVariable("result", "processing")
+ execution.setVariable("operationType", "DELETE")
+ execution.setVariable("operationContent", "Prepare init service")
+ updateServiceOperationStatus(execution)
+
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex) {
+ msg = "Exception in preProcessRequest " + ex.getMessage()
+ logger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.trace("Exit preProcessRequest")
+ }
+
+ /**
+ * send asynchronous response
+ * @param execution
+ */
+ void sendAsyncResponse(DelegateExecution execution) {
+ logger.trace("Staring sendSyncResponse")
+
+ try {
+ String operationId = execution.getVariable("operationId")
+ String syncResponse = """{"operationId":"${operationId}"}""".trim()
+ logger.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
+ sendWorkflowResponse(execution, 202, syncResponse)
+
+ } catch (Exception ex) {
+ String msg = "Exception in sendSyncResponse: " + ex.getMessage()
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ logger.trace("Exit sendSyncResponse")
+ }
+
+ /**
+ * Deletes the slice service instance in aai
+ */
+ void deleteSliceServiceInstance(DelegateExecution execution) {
+ logger.trace("Entered deleteSliceServiceInstance")
+ try {
+
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), execution.getVariable("serviceInstanceId"))
+ resourceClient.delete(serviceInstanceUri)
+
+ execution.setVariable("progress", "100")
+ execution.setVariable("result", "finished")
+ execution.setVariable("operationContent", "NSMF completes slicing service termination.")
+ updateServiceOperationStatus(execution)
+
+ logger.trace("Exited deleteSliceServiceInstance")
+ }catch(Exception e){
+ logger.debug("Error occured within deleteSliceServiceInstance method: " + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteSliceServiceInstance from aai")
+ }
+ }
+
+ /**
+ * update operation status
+ * @param execution
+ */
+ private void updateServiceOperationStatus(DelegateExecution execution){
+
+ OperationStatus operationStatus = new OperationStatus()
+ operationStatus.setServiceId(execution.getVariable("serviceInstanceId"))
+ operationStatus.setOperationId(execution.getVariable("operationId"))
+ operationStatus.setUserId(execution.getVariable("globalSubscriberId"))
+ operationStatus.setResult(execution.getVariable("result"))
+ operationStatus.setProgress(execution.getVariable("progress"))
+ operationStatus.setOperationContent(execution.getVariable("operationContent"))
+ operationStatus.setReason(execution.getVariable("reason"))
+ operationStatus.setOperation(execution.getVariable("operationType"))
+
+ requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
+ }
+
+ /**
+ * delete service profile from aai
+ * @param execution
+ */
+ private void delServiceProfileFromAAI(DelegateExecution execution)
+ {
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("serviceType")
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ String profileId = ""
+
+ try
+ {
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE_ALL, globalSubscriberId, serviceType, serviceInstanceId)
+ AAIResultWrapper wrapper = resourceClient.get(resourceUri, NotFoundException.class)
+ Optional<ServiceProfiles> serviceProfilesOpt =wrapper.asBean(ServiceProfiles.class)
+ if(serviceProfilesOpt.isPresent()){
+ ServiceProfiles serviceProfiles = serviceProfilesOpt.get()
+ ServiceProfile serviceProfile = serviceProfiles.getServiceProfile().get(0)
+ profileId = serviceProfile ? serviceProfile.getProfileId() : ""
+ }
+ resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE, globalSubscriberId, serviceType, serviceInstanceId, profileId)
+ if (!resourceClient.exists(resourceUri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
+ }
+ resourceClient.delete(resourceUri)
+ }
+ catch (any)
+ {
+ String msg = "delete service profile from aai failed! cause-"+any.getCause()
+ logger.error(any.printStackTrace())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+ }
+
+ void sendSyncError(DelegateExecution execution) {
+ logger.info("Starting sendSyncError")
+
+ try {
+ String errorMessage
+ if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
+ WorkflowException wfe = execution.getVariable("WorkflowException")
+ errorMessage = wfe.getErrorMessage()
+ } else {
+ errorMessage = "Sending Sync Error."
+ }
+
+ String buildworkflowException =
+ """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
+ <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
+ <aetgt:ErrorCode>7000</aetgt:ErrorCode>
+ </aetgt:WorkflowException>"""
+
+ logger.debug(buildworkflowException)
+ sendWorkflowResponse(execution, 500, buildworkflowException)
+
+ } catch (Exception ex) {
+ logger.error("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
+ }
+
+ }
+
+ void prepareEndOperationStatus(DelegateExecution execution){
+ logger.debug(" ======== STARTED prepareEndOperationStatus Process ======== ")
+
+ execution.setVariable("progress", "100")
+ execution.setVariable("result", "error")
+ execution.setVariable("operationContent", "NSSMF Terminate service failure")
+
+ WorkflowException wfex = execution.getVariable("WorkflowException") as WorkflowException
+ String errorMessage = wfex.getErrorMessage()
+ errorMessage = errorMessage.length() > 200 ? errorMessage.substring(0,200) + "......" : errorMessage
+ execution.setVariable("reason",errorMessage)
+ updateServiceOperationStatus(execution)
+
+ logger.debug("======== COMPLETED prepareEndOperationStatus Process ======== ")
+ }
+
+ /**
+ * check parameters from request body
+ * set to execution
+ * @param siRequest
+ * @param paraName
+ * @param isErrorException
+ * @param execution
+ */
+ private void checkAndSetRequestParam(String siRequest, String paraName, boolean isErrorException, DelegateExecution execution)
+ {
+ String msg = ""
+ String paramValue = jsonUtil.getJsonValue(siRequest, paraName)
+ if (isBlank(paramValue)) {
+ msg = "Input ${paraName} is null"
+ logger.error(msg)
+ if(isErrorException)
+ {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+
+ } else {
+ execution.setVariable(paraName, paramValue)
+ }
+ }
+}
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
new file mode 100644
index 0000000000..d8897a2468
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy
@@ -0,0 +1,309 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., Ltd.
+ #
+ # Licensed under the Apache License, Version 2.0 (the "License")
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.bpmn.infrastructure.scripts
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import 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.EsrInfo
+import org.onap.so.beans.nsmf.JobStatusRequest
+import org.onap.so.beans.nsmf.JobStatusResponse
+import org.onap.so.beans.nsmf.NetworkType
+import org.onap.so.beans.nsmf.NssiDeAllocateRequest
+import org.onap.so.beans.nsmf.NssiResponse
+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.ServiceArtifact
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.AAIResourcesClient
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+import org.onap.so.db.request.beans.OperationStatus
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import javax.ws.rs.core.Response
+
+
+class DoDeallocateNSSI extends AbstractServiceTaskProcessor
+{
+ private final String PREFIX ="DoDeallocateNSSI"
+
+ private ExceptionUtil exceptionUtil = new ExceptionUtil()
+ private JsonUtils jsonUtil = new JsonUtils()
+ private RequestDBUtil requestDBUtil = new RequestDBUtil()
+ private static final Logger LOGGER = LoggerFactory.getLogger( DoDeallocateNSSI.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 *****")
+ }
+
+ /**
+ *
+ * @param execution
+ */
+ private void prepareDecomposeService(DelegateExecution execution)
+ {
+ LOGGER.trace(" *****${PREFIX} Start prepareDecomposeService *****")
+ try
+ {
+ def currentNSSI = execution.getVariable("currentNSSI")
+ String modelInvariantUuid = currentNSSI['modelInvariantId']
+ String modelVersionId = currentNSSI['modelVersionId']
+ String serviceModelInfo = """{
+ "modelInvariantUuid":"${modelInvariantUuid}",
+ "modelUuid":"${modelVersionId}",
+ "modelVersion":""
+ }"""
+ execution.setVariable("serviceModelInfo", serviceModelInfo)
+ }
+ catch (any)
+ {
+ String exceptionMessage = "Bpmn error encountered in deallocate nssi. Unexpected Error from method prepareDecomposeService() - " + any.getMessage()
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
+ }
+ LOGGER.debug(" ***** ${PREFIX} Exit prepareDecomposeService *****")
+ }
+
+ /**
+ * get vendor Info
+ * @param execution
+ */
+ private void processDecomposition(DelegateExecution execution) {
+ LOGGER.debug("*****${PREFIX} start processDecomposition *****")
+
+ try {
+ ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") as ServiceDecomposition
+ ServiceArtifact serviceArtifact = serviceDecomposition ?.getServiceInfo()?.getServiceArtifact()?.get(0)
+ String content = serviceArtifact.getContent()
+ String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
+ String domainType = jsonUtil.getJsonValue(content, "metadata.domainType")
+
+ def currentNSSI = execution.getVariable("currentNSSI")
+ currentNSSI['vendor'] = vendor
+ currentNSSI['domainType'] = domainType
+ LOGGER.info("processDecomposition, current vendor-domainType:" +String.join("-", vendor, domainType))
+
+ } catch (any) {
+ String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
+ LOGGER.debug(exceptionMessage)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
+ }
+ LOGGER.debug("*****${PREFIX} Exit processDecomposition *****")
+ }
+
+ /**
+ * send deallocate request to nssmf
+ * @param execution
+ */
+ private void sendRequestToNSSMF(DelegateExecution execution)
+ {
+ LOGGER.debug("*****${PREFIX} start sendRequestToNSSMF *****")
+ def currentNSSI = execution.getVariable("currentNSSI")
+ String snssai= currentNSSI['snssai']
+ String profileId = currentNSSI['profileId']
+ String nssiId = currentNSSI['nssiServiceInstanceId']
+ String nsiId = currentNSSI['nsiServiceInstanceId']
+
+ DeAllocateNssi deAllocateNssi = new DeAllocateNssi()
+ deAllocateNssi.setNsiId(nsiId)
+ deAllocateNssi.setNssiId(nssiId)
+ deAllocateNssi.setTerminateNssiOption(0)
+ deAllocateNssi.setSnssaiList(Arrays.asList(snssai))
+
+ NssiDeAllocateRequest deAllocateRequest = new NssiDeAllocateRequest()
+ deAllocateRequest.setDeAllocateNssi(deAllocateNssi)
+ deAllocateRequest.setEsrInfo(getEsrInfo(currentNSSI))
+
+ ObjectMapper mapper = new ObjectMapper()
+ String json = mapper.writeValueAsString(deAllocateRequest)
+
+ //Prepare auth for NSSMF - Begin
+ String nssmfRequest = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
+ nssmfRequest = nssmfRequest + String.format("/api/rest/provMns/v1/NSS/SliceProfiles/%s",profileId)
+ //nssmfRequest = nssmfRequest + String.format(NssmfAdapterUtil.NSSMI_DEALLOCATE_URL,profileId)
+ //send request to active NSSI TN option
+ URL url = new URL(nssmfRequest)
+ LOGGER.info("deallocate nssmfRequest:${nssmfRequest}, reqBody: ${json}")
+
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
+ Response httpResponse = httpClient.post(json)
+ checkNssmfResponse(httpResponse, execution)
+
+ NssiResponse nssmfResponse = httpResponse.readEntity(NssiResponse.class)
+ currentNSSI['jobId']= nssmfResponse.getJobId() ?: ""
+ currentNSSI['jobProgress'] = 0
+ execution.setVariable("currentNSSI", currentNSSI)
+
+ LOGGER.debug("*****${PREFIX} Exit sendRequestToNSSMF *****")
+ }
+
+ /**
+ * send to nssmf query progress
+ * @param execution
+ */
+ private void getJobStatus(DelegateExecution execution)
+ {
+ def currentNSSI = execution.getVariable("currentNSSI")
+ String jobId = currentNSSI['jobId']
+ String nssiId = currentNSSI['nssiServiceInstanceId']
+ String nsiId = currentNSSI['nsiServiceInstanceId']
+
+ JobStatusRequest jobStatusRequest = new JobStatusRequest()
+ jobStatusRequest.setNssiId(nssiId)
+ jobStatusRequest.setNsiId(nsiId)
+ jobStatusRequest.setEsrInfo(getEsrInfo(currentNSSI))
+
+ ObjectMapper mapper = new ObjectMapper()
+ String json = mapper.writeValueAsString(jobStatusRequest)
+
+ //Prepare auth for NSSMF - Begin
+ String nssmfRequest = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
+ nssmfRequest = nssmfRequest + String.format("/api/rest/provMns/v1/NSS/jobs/%s",jobId)
+ //send request to active NSSI TN option
+ URL url = new URL(nssmfRequest)
+ LOGGER.info("get deallocate job status, nssmfRequest:${nssmfRequest}, requestBody: ${json}")
+
+ HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
+ Response httpResponse = httpClient.post(json)
+ checkNssmfResponse(httpResponse, execution)
+
+ JobStatusResponse jobStatusResponse = httpResponse.readEntity(JobStatusResponse.class)
+ def progress = jobStatusResponse?.getResponseDescriptor()?.getProgress()
+ if(!progress)
+ {
+ LOGGER.error("job progress is null or empty!")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Job progress from NSSMF.")
+ }
+ int oldProgress = currentNSSI['jobProgress']
+ int currentProgress = progress
+
+ execution.setVariable("isNSSIDeAllocated", (currentProgress == 100))
+ execution.setVariable("isNeedUpdateDB", (oldProgress != currentProgress))
+ currentNSSI['jobProgress'] = currentProgress
+
+ def statusDescription = jobStatusResponse?.getResponseDescriptor()?.getStatusDescription()
+ currentNSSI['statusDescription'] = statusDescription
+
+ LOGGER.debug("job status result: nsiId = ${nsiId}, nssiId=${nssiId}, oldProgress=${oldProgress}, progress = ${currentProgress}" )
+ }
+
+ private void checkNssmfResponse(Response httpResponse, DelegateExecution execution) {
+ int responseCode = httpResponse.getStatus()
+ LOGGER.debug("NSSMF response code is: " + responseCode)
+
+ if ( responseCode < 200 || responseCode > 204 || !httpResponse.hasEntity()) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Response from NSSMF.")
+ }
+ }
+
+
+ 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
+ */
+ private void handleJobStatus(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)
+
+ OperationStatus operationStatus = new OperationStatus()
+ operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
+ operationStatus.setOperationId(currentNSSI['operationId'] as String)
+ operationStatus.setOperation("DELETE")
+ operationStatus.setResult("processing")
+ operationStatus.setProgress(progress as String)
+ operationStatus.setOperationContent(statusDes as String)
+ requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
+ LOGGER.debug("update operation, currentProgress=${currentProgress}, proportion=${proportion}, progress = ${progress}" )
+ }
+
+ private void timeDelay(DelegateExecution execution) {
+ try {
+ Thread.sleep(10000);
+ } catch(InterruptedException e) {
+ LOGGER.error("Time Delay exception" + e)
+ }
+ }
+
+ /**
+ * delete slice profile from aai
+ * @param execution
+ */
+ private void delSliceProfileFromAAI(DelegateExecution execution)
+ {
+ LOGGER.debug("*****${PREFIX} start delSliceProfileFromAAI *****")
+ def currentNSSI = execution.getVariable("currentNSSI")
+ String nssiServiceInstanceId = currentNSSI['nssiServiceInstanceId']
+ String profileId = currentNSSI['profileId']
+ String globalSubscriberId = currentNSSI["globalSubscriberId"]
+ String serviceType = currentNSSI["serviceType"]
+
+ try
+ {
+ LOGGER.debug("delete nssiServiceInstanceId:${nssiServiceInstanceId}, profileId:${profileId}")
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, globalSubscriberId, serviceType, nssiServiceInstanceId, profileId)
+ if (!resourceClient.exists(resourceUri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
+ }
+ resourceClient.delete(resourceUri)
+ }
+ catch (any)
+ {
+ String msg = "delete slice profile from aai failed! cause-"+any.getCause()
+ LOGGER.error(any.printStackTrace())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ LOGGER.debug("*****${PREFIX} Exist delSliceProfileFromAAI *****")
+ }
+}
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
new file mode 100644
index 0000000000..7c2a2be6ac
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceService.groovy
@@ -0,0 +1,322 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., Ltd.
+ #
+ # Licensed under the Apache License, Version 2.0 (the "License")
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+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.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.client.aai.AAIObjectType
+import org.onap.so.client.aai.AAIResourcesClient
+import org.onap.so.client.aai.entities.AAIResultWrapper
+import org.onap.so.client.aai.entities.uri.AAIResourceUri
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+import javax.ws.rs.NotFoundException
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+/**
+ * This groovy class supports the <class>DoDeleteSliceService.bpmn</class> process.
+ *
+ * Inputs:
+ * @param - msoRequestId
+ * @param - globalSubscriberId - O
+ * @param - subscriptionServiceType - O
+ * @param - serviceInstanceId
+ *
+ */
+class DoDeleteSliceService extends AbstractServiceTaskProcessor {
+ private final String PREFIX ="DoDeleteSliceService"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ private static final Logger LOGGER = LoggerFactory.getLogger( DoDeleteSliceService.class)
+
+ @Override
+ void preProcessRequest(DelegateExecution execution) {
+ LOGGER.debug(" *****${PREFIX} preProcessRequest *****")
+ String msg = ""
+
+ try {
+ //String requestId = execution.getVariable("msoRequestId")
+ execution.setVariable("prefix",PREFIX)
+
+ //Inputs
+ //requestDetails.subscriberInfo. for AAI GET & PUT
+ execution.getVariable("globalSubscriberId") ?: execution.setVariable("globalSubscriberId", "")
+
+ //requestDetails.requestParameters. for AAI PUT
+ execution.getVariable("serviceType") ?: execution.setVariable("serviceType", "")
+
+ //Generated in parent for AAI PUT
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ if (isBlank(serviceInstanceId)){
+ msg = "Input serviceInstanceId is null"
+ LOGGER.info(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
+ }
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception ex){
+ msg = "Exception in preProcessRequest " + ex.getMessage()
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ LOGGER.debug("*****${PREFIX} Exit preProcessRequest *****")
+ }
+
+ /**
+ * query E2ESliceService from AAI
+ * save snssai
+ * @param execution
+ */
+ void queryE2ESliceSeriveFromAAI(DelegateExecution execution)
+ {
+ LOGGER.trace(" *****${PREFIX} Start queryE2ESliceSeriveFromAAI *****")
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+
+ 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()
+ execution.setVariable("snssai", snssai ?: "")
+ LOGGER.info("serviceInstanceId: ${serviceInstanceId}, snssai: ${snssai}")
+ }
+ LOGGER.trace(" *****${PREFIX} Exit queryE2ESliceSeriveFromAAI *****")
+ }
+
+ /**
+ * get allotted resource from AAI
+ * save nsi id
+ * @param execution
+ */
+ void getAllottedResFromAAI(DelegateExecution execution)
+ {
+ LOGGER.trace(" *****${PREFIX} Start getAllottedResFromAAI *****")
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ try
+ {
+ String errorMsg = "query allotted resource from aai failed."
+ AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.ALLOTTED_RESOURCE_ALL, serviceInstanceId, errorMsg)
+ Optional<AllottedResources> ars = wrapper?.asBean(AllottedResources.class)
+ if(ars.isPresent() && ars.get().getAllottedResource())
+ {
+ List<AllottedResource> allottedResourceList = ars.get().getAllottedResource()
+ AllottedResource ar = allottedResourceList.first()
+ String relatedLink = ar?.getRelationshipList()?.getRelationship()?.first()?.getRelatedLink()
+ String nsiId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
+ execution.setVariable("nsiId", nsiId)
+ LOGGER.info("serviceInstanceId: ${serviceInstanceId}, nsiId:${nsiId}")
+ }
+ }
+ catch(BpmnError e){
+ throw e
+ }
+ catch (Exception ex){
+ String msg = "Exception in getAllottedResFromAAI " + ex.getMessage()
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ LOGGER.trace(" *****${PREFIX} Exit getAllottedResFromAAI *****")
+ }
+
+ /**
+ * get nsi service instance from aai
+ * save nssi id
+ * @param execution
+ */
+ void getNSIFromAAI(DelegateExecution execution)
+ {
+ LOGGER.trace(" *****${PREFIX} Start getNSIFromAAI *****")
+ String nsiId = execution.getVariable("nsiId")
+ try
+ {
+ String errorMsg = "query nsi from aai failed."
+ AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, nsiId, errorMsg)
+ Optional<ServiceInstance> si =wrapper.asBean(ServiceInstance.class)
+ List<String> nssiIdList = []
+ String msg = "nsiId:${nsiId},nssiIdList:"
+ if(si.isPresent())
+ {
+ List<Relationship> relationshipList = si.get().getRelationshipList()?.getRelationship()
+ for (Relationship relationship : relationshipList)
+ {
+ String relatedTo = relationship.getRelatedTo()
+ if (relatedTo == "service-instance")
+ {
+ String relatedLink = relationship.getRelatedLink()?:""
+ String nssiId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
+ nssiIdList.add(nssiId)
+ msg+="${nssiId}, "
+ }
+ }
+ }
+ LOGGER.info(msg)
+ execution.setVariable("nssiIdList", nssiIdList)
+ }
+ catch(BpmnError e){
+ throw e
+ }
+ catch (Exception ex){
+ String msg = "Exception in getNSIFromAAI " + ex.getMessage()
+ LOGGER.error(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ LOGGER.trace(" *****${PREFIX} Exit getNSIFromAAI *****")
+ }
+
+ /**
+ * get nssi service from AAI
+ * prepare list
+ * @param execution
+ */
+ void getNSSIListFromAAI(DelegateExecution execution)
+ {
+ LOGGER.trace("*****${PREFIX} Start getNSSIListFromAAI *****")
+ List<String> nssiIdList = execution.getVariable("nssiIdList")
+ List<ServiceInstance> nssiInstanceList = []
+ String errorMsg = "query nssi list from aai failed"
+ for(String nssiId : nssiIdList)
+ {
+ AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, nssiId, errorMsg)
+ Optional<ServiceInstance> si =wrapper.asBean(ServiceInstance.class)
+ if(si.isPresent())
+ {
+ nssiInstanceList.add(si.get())
+ }
+ }
+ int size = nssiInstanceList.size()
+ int proportion = size >0 ?((90/size) as int) : 90
+ execution.setVariable("nssiInstanceList", nssiInstanceList)
+ execution.setVariable("currentNSSIIndex", 0)
+ execution.setVariable("proportion", proportion)
+ String msg ="nssiInstanceList size: ${nssiInstanceList.size()}, proportion:${proportion}"
+ LOGGER.info(msg)
+ LOGGER.trace(" *****${PREFIX} Exit getNSSIListFromAAI *****")
+ }
+
+ /**
+ * get current NSSI
+ * @param execution
+ */
+ void getCurrentNSSI(DelegateExecution execution)
+ {
+ LOGGER.trace(" *****${PREFIX} Start getCurrentNSSI *****")
+ List<ServiceInstance> nssiInstanceList = execution.getVariable("nssiInstanceList")
+ int currentIndex = execution.getVariable("currentNSSIIndex") as int
+ ServiceInstance nssi = nssiInstanceList?.get(currentIndex)
+ def currentNSSI = [:]
+ currentNSSI['nssiServiceInstanceId'] = nssi?.getServiceInstanceId()
+ currentNSSI['modelInvariantId'] = nssi?.getModelInvariantId()
+ currentNSSI['modelVersionId'] = nssi?.getModelVersionId()
+ currentNSSI['snssai'] = execution.getVariable("snssai") ?: ""
+ currentNSSI['nsiServiceInstanceId'] = execution.getVariable("nsiId") ?: ""
+ currentNSSI['operationId'] = execution.getVariable("operationId") ?: ""
+ currentNSSI['e2eServiceInstanceId'] = execution.getVariable("serviceInstanceId") ?: ""
+ currentNSSI['msoRequestId'] = execution.getVariable("msoRequestId") ?: ""
+ currentNSSI['globalSubscriberId'] = execution.getVariable("globalSubscriberId") ?: ""
+ currentNSSI['serviceType'] = execution.getVariable("serviceType") ?: ""
+ currentNSSI['serviceModelInfo'] = execution.getVariable("serviceModelInfo") ?: ""
+ currentNSSI['proportion'] = (execution.getVariable("proportion") as int)*(currentIndex+1)
+ execution.setVariable("currentNSSI", currentNSSI)
+ String msg = "Now we deal with nssiServiceInstanceId: ${currentNSSI['nssiServiceInstanceId']}, current Index: ${currentIndex}, current proportion:${currentNSSI['proportion']}"
+ LOGGER.info(msg)
+ LOGGER.trace(" *****${PREFIX} Exit getCurrentNSSI *****")
+ }
+
+ /**
+ * parse next nssi
+ * @param execution
+ */
+ void parseNextNSSI(DelegateExecution execution)
+ {
+ LOGGER.trace(" *****${PREFIX} Start parseNextNSSI *****")
+ if(execution.getVariable("WorkflowException") != null){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "current job failure!")
+ }
+ def currentIndex = execution.getVariable("currentNSSIIndex")
+ List<ServiceInstance> nssiInstanceList = execution.getVariable("nssiInstanceList")
+ def nextIndex = ++currentIndex
+ LOGGER.info("nextIndex: ${nextIndex}")
+ if(nextIndex >= nssiInstanceList.size()){
+ execution.setVariable("isAllNSSIFinished", "true")
+ }else{
+ execution.setVariable("isAllNSSIFinished", "false")
+ execution.setVariable("currentNSSIIndex", nextIndex)
+ }
+ 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
+ * @param aaiObjectType
+ * @param instanceId
+ * @return AAIResultWrapper
+ */
+ private AAIResultWrapper queryAAI(DelegateExecution execution, AAIObjectType aaiObjectType, String instanceId, String errorMsg)
+ {
+ LOGGER.trace(" *****${PREFIX} Start queryAAI *****")
+ String globalSubscriberId = execution.getVariable("globalSubscriberId")
+ String serviceType = execution.getVariable("serviceType")
+
+ AAIResourcesClient resourceClient = new AAIResourcesClient()
+ AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(aaiObjectType, globalSubscriberId, serviceType, instanceId)
+ if (!resourceClient.exists(resourceUri)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMsg)
+ }
+ AAIResultWrapper wrapper = resourceClient.get(resourceUri, NotFoundException.class)
+ LOGGER.trace(" *****${PREFIX} Exit queryAAI *****")
+ return wrapper
+ }
+
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java
index fb95ae3993..11707c4149 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java
@@ -7,9 +7,9 @@
* 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.
@@ -27,9 +27,15 @@ import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class AAIDeleteServiceInstance implements JavaDelegate {
+ private static final Logger logger = LoggerFactory.getLogger(AAIDeleteServiceInstance.class);
+ private static final String ERROR_MESSAGE =
+ "Exception in Delete Serivce Instance. Service Instance could not be deleted in AAI.";
+
ExceptionUtil exceptionUtil = new ExceptionUtil();
public void execute(DelegateExecution execution) throws Exception {
@@ -41,8 +47,8 @@ public class AAIDeleteServiceInstance implements JavaDelegate {
aaiRC.delete(serviceInstanceURI);
execution.setVariable("GENDS_SuccessIndicator", true);
} catch (Exception ex) {
- String msg = "Exception in Delete Serivce Instance. Service Instance could not be deleted in AAI."
- + ex.getMessage();
+ logger.debug(ERROR_MESSAGE, ex);
+ String msg = ERROR_MESSAGE + ex.getMessage();
exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java
index 2d69351744..f7b0c662db 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java
@@ -7,9 +7,9 @@
* 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.
@@ -30,17 +30,70 @@ public class AAIServiceInstance {
String environmentContext;
String workloadContext;
- public AAIServiceInstance(String serviceInstanceName, String serviceType, String serviceRole,
- String orchestrationStatus, String modelInvariantUuid, String modelVersionId, String environmentContext,
- String workloadContext) {
- this.serviceInstanceName = serviceInstanceName;
- this.serviceType = serviceType;
- this.serviceRole = serviceRole;
- this.orchestrationStatus = orchestrationStatus;
- this.modelInvariantUuid = modelInvariantUuid;
- this.modelVersionId = modelVersionId;
- this.environmentContext = environmentContext;
- this.workloadContext = workloadContext;
+ public class AAIServiceInstanceBuilder {
+ private String serviceInstanceName;
+ private String serviceType;
+ private String serviceRole;
+ private String orchestrationStatus;
+ private String modelInvariantUuid;
+ private String modelVersionId;
+ private String environmentContext;
+ private String workloadContext;
+
+ public AAIServiceInstanceBuilder setServiceInstanceName(String serviceInstanceName) {
+ this.serviceInstanceName = serviceInstanceName;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setModelInvariantUuid(String modelInvariantUuid) {
+ this.modelInvariantUuid = modelInvariantUuid;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setEnvironmentContext(String environmentContext) {
+ this.environmentContext = environmentContext;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ return this;
+ }
+
+ public AAIServiceInstance createAAIServiceInstance() {
+ return new AAIServiceInstance(this);
+ }
+ }
+
+ public AAIServiceInstance(AAIServiceInstanceBuilder aaiServiceInstanceBuilder) {
+ this.serviceInstanceName = aaiServiceInstanceBuilder.serviceInstanceName;
+ this.serviceType = aaiServiceInstanceBuilder.serviceType;
+ this.serviceRole = aaiServiceInstanceBuilder.serviceRole;
+ this.orchestrationStatus = aaiServiceInstanceBuilder.orchestrationStatus;
+ this.modelInvariantUuid = aaiServiceInstanceBuilder.modelInvariantUuid;
+ this.modelVersionId = aaiServiceInstanceBuilder.modelVersionId;
+ this.environmentContext = aaiServiceInstanceBuilder.environmentContext;
+ this.workloadContext = aaiServiceInstanceBuilder.workloadContext;
}
public String getServiceInstanceName() {
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcher.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcher.java
new file mode 100644
index 0000000000..4482d2a327
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcher.java
@@ -0,0 +1,165 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.infrastructure.pnf.delegate;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.onap.aai.domain.yang.Pnf;
+import org.onap.so.bpmn.core.json.JsonUtils;
+import org.onap.so.bpmn.infrastructure.pnf.management.PnfManagement;
+import org.onap.so.client.exception.ExceptionBuilder;
+import org.onap.so.db.catalog.beans.PnfResourceCustomization;
+import org.onap.so.db.catalog.client.CatalogDbClient;
+import org.onap.so.serviceinstancebeans.RequestDetails;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.*;
+
+/**
+ * This implementation of {@link JavaDelegate} is used to populate the execution object for pnf software upgrade
+ */
+@Component
+public class NfSoftwareUpgradeDispatcher implements JavaDelegate {
+
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+ private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName";
+ private static final String BPMN_REQUEST = "bpmnRequest";
+ private static final String RESOURCE_CUSTOMIZATION_UUID_PARAM = "resource_customization_uuid";
+ private static final String PNF_NAME = "pnfName";
+
+ // ERROR CODE for variable not found in the delegation Context
+ private static final int ERROR_CODE = 601;
+
+ @Autowired
+ private PnfManagement pnfManagement;
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+
+ @Autowired
+ private ObjectMapper mapper;
+
+ @Override
+ public void execute(DelegateExecution delegateExecution) throws Exception {
+ logger.debug("Running execute block for activity id:{}, name:{}", delegateExecution.getCurrentActivityId(),
+ delegateExecution.getCurrentActivityName());
+
+ RequestDetails bpmnRequestDetails = requestVerification(delegateExecution);
+
+ final String serviceInstanceName = bpmnRequestDetails.getRequestInfo().getInstanceName();
+ final String pnfName = bpmnRequestDetails.getRequestParameters().getUserParamValue(PNF_NAME);
+ final String serviceModelUuid = bpmnRequestDetails.getModelInfo().getModelUuid();
+ final List<Map<String, Object>> userParams = bpmnRequestDetails.getRequestParameters().getUserParams();
+ final Pnf pnf = getPnfByPnfName(delegateExecution, pnfName);
+ final List<PnfResourceCustomization> pnfCustomizations =
+ getPnfResourceCustomizations(delegateExecution, serviceModelUuid);
+ final PnfResourceCustomization pnfResourceCustomization = pnfCustomizations.get(0);
+
+ populateExecution(delegateExecution, bpmnRequestDetails, pnfResourceCustomization, pnf, serviceInstanceName,
+ pnfName, serviceModelUuid, userParams);
+
+ logger.trace("Completed preProcessRequest PnfSoftwareUpgradeServiceRequest Request ");
+ }
+
+ private RequestDetails requestVerification(DelegateExecution delegateExecution) throws IOException {
+ RequestDetails bpmnRequestDetails = mapper.readValue(
+ JsonUtils.getJsonValue(String.valueOf(delegateExecution.getVariable(BPMN_REQUEST)), "requestDetails"),
+ RequestDetails.class);
+
+ throwIfNull(delegateExecution, bpmnRequestDetails.getModelInfo(), SERVICE_MODEL_INFO);
+ throwIfNull(delegateExecution, bpmnRequestDetails.getRequestInfo(), "RequestInfo");
+ throwIfNull(delegateExecution, bpmnRequestDetails.getRequestParameters(), "RequestParameters");
+ throwIfNull(delegateExecution, bpmnRequestDetails.getRequestParameters().getUserParams(), "UserParams");
+
+ return bpmnRequestDetails;
+ }
+
+ private void populateExecution(DelegateExecution delegateExecution, RequestDetails bpmnRequestDetails,
+ PnfResourceCustomization pnfResourceCustomization, Pnf pnf, String serviceInstanceName, String pnfName,
+ String serviceModelUuid, List<Map<String, Object>> userParams) {
+
+ delegateExecution.setVariable(SERVICE_MODEL_INFO, bpmnRequestDetails.getModelInfo());
+ delegateExecution.setVariable(SERVICE_INSTANCE_NAME, serviceInstanceName);
+ delegateExecution.setVariable(PNF_CORRELATION_ID, pnfName);
+ delegateExecution.setVariable(MODEL_UUID, serviceModelUuid);
+ delegateExecution.setVariable(PNF_UUID, pnf.getPnfId());
+ delegateExecution.setVariable(PRC_BLUEPRINT_NAME, pnfResourceCustomization.getBlueprintName());
+ delegateExecution.setVariable(PRC_BLUEPRINT_VERSION, pnfResourceCustomization.getBlueprintVersion());
+ delegateExecution.setVariable(PRC_CUSTOMIZATION_UUID, pnfResourceCustomization.getModelCustomizationUUID());
+ delegateExecution.setVariable(RESOURCE_CUSTOMIZATION_UUID_PARAM,
+ pnfResourceCustomization.getModelCustomizationUUID());
+ delegateExecution.setVariable(PRC_INSTANCE_NAME, pnfResourceCustomization.getModelInstanceName());
+ delegateExecution.setVariable(PRC_CONTROLLER_ACTOR, pnfResourceCustomization.getControllerActor());
+
+ for (Map<String, Object> param : userParams) {
+ if (param.containsKey("name") && param.containsKey("value")) {
+ delegateExecution.setVariable(param.get("name").toString(), param.get("value").toString());
+ }
+ }
+ }
+
+ private Pnf getPnfByPnfName(DelegateExecution delegateExecution, String pnfName) {
+ Optional<Pnf> pnfOptional = null;
+ try {
+ pnfOptional = pnfManagement.getEntryFor(pnfName);
+ } catch (IOException e) {
+ logger.warn(e.getMessage(), e);
+ exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE,
+ "Unable to fetch from AAI" + e.getMessage());
+ }
+ if (pnfOptional == null || !pnfOptional.isPresent()) {
+ exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE,
+ "AAI entry for PNF: " + pnfName + " does not exist");
+ }
+ return pnfOptional.get();
+ }
+
+ private List<PnfResourceCustomization> getPnfResourceCustomizations(DelegateExecution delegateExecution,
+ String serviceModelUuid) {
+ List<PnfResourceCustomization> pnfCustomizations =
+ catalogDbClient.getPnfResourceCustomizationByModelUuid(serviceModelUuid);
+
+ if (pnfCustomizations == null || pnfCustomizations.isEmpty()) {
+ logger.warn("Unable to find the PNF resource customizations of model service UUID: {}", serviceModelUuid);
+ exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE,
+ "Unable to find the PNF resource customizations of model service UUID: " + serviceModelUuid);
+ }
+ return pnfCustomizations;
+ }
+
+ private void throwIfNull(DelegateExecution delegateExecution, Object obj, String param) {
+ if (obj == null) {
+ logger.warn("Unable to find the parameter: {} in the execution context", param);
+ exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE,
+ "Unable to find parameter " + param);
+ }
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/UpdatePnfEntryInAai.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/UpdatePnfEntryInAai.java
new file mode 100644
index 0000000000..f85be8aab7
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/UpdatePnfEntryInAai.java
@@ -0,0 +1,65 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.bpmn.infrastructure.pnf.delegate;
+
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.onap.aai.domain.yang.Pnf;
+import org.onap.so.bpmn.infrastructure.pnf.management.PnfManagement;
+import org.onap.so.client.exception.ExceptionBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import java.util.Optional;
+import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID;
+import static org.onap.so.client.cds.PayloadConstants.PRC_TARGET_SOFTWARE_VERSION;
+
+
+@Component
+public class UpdatePnfEntryInAai implements JavaDelegate {
+
+ private final Logger logger = LoggerFactory.getLogger(UpdatePnfEntryInAai.class);
+
+ @Autowired
+ private PnfManagement pnfManagement;
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ @Override
+ public void execute(DelegateExecution execution) throws Exception {
+ String pnfCorrelationId = String.valueOf(execution.getVariable(PNF_CORRELATION_ID));
+ Optional<Pnf> pnfAaiEntry = pnfManagement.getEntryFor(pnfCorrelationId);
+
+ if (!pnfAaiEntry.isPresent()) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 404,
+ "AAI entry for PNF: " + PNF_CORRELATION_ID + " does not exist");
+ }
+
+ Pnf pnf = pnfAaiEntry.get();
+ String pnfSoftwareVersion = String.valueOf(execution.getVariable(PRC_TARGET_SOFTWARE_VERSION));
+ pnf.setSwVersion(pnfSoftwareVersion);
+
+ pnfManagement.updateEntry(pnfCorrelationId, pnf);
+ logger.debug("AAI entry is updated for pnf correlation id: {}, pnf uuid: {} with swVersion: {}",
+ pnf.getPnfName(), pnfCorrelationId, pnfSoftwareVersion);
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagement.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagement.java
index 9e720fe0a4..46937d0d8c 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagement.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagement.java
@@ -30,5 +30,7 @@ public interface PnfManagement {
void createEntry(String pnfCorrelationId, Pnf entry) throws IOException;
+ void updateEntry(String pnfCorrelationId, Pnf entry) throws IOException;
+
void createRelation(String serviceInstanceId, String pnfName) throws IOException;
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java
index b1af8b1e0b..e6df8070a3 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java
@@ -44,6 +44,11 @@ public class PnfManagementImpl implements PnfManagement {
restClient.createPnf(pnfCorrelationId, entry);
}
+ public void updateEntry(String pnfCorrelationId, Pnf entry) {
+ AAIRestClientImpl restClient = new AAIRestClientImpl();
+ restClient.updatePnf(pnfCorrelationId, entry);
+ }
+
@Override
public void createRelation(String serviceInstanceId, String pnfName) {
AAIResourceUri serviceInstanceURI =
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatusTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatusTest.groovy
new file mode 100644
index 0000000000..f066f9e878
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatusTest.groovy
@@ -0,0 +1,344 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ # Copyright (c) 2019, CMCC Technologies Co., Ltd.
+ #
+ # Licensed under the Apache License, Version 2.0 (the "License")
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.infrastructure.scripts
+
+import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity
+import org.junit.Before
+import org.junit.Test
+import org.mockito.ArgumentCaptor
+import org.mockito.Captor
+import org.mockito.Mockito
+import org.onap.so.bpmn.common.scripts.MsoGroovyTest
+
+import static org.junit.Assert.assertEquals
+import static org.mockito.ArgumentMatchers.eq
+import static org.mockito.Mockito.times
+import static org.mockito.Mockito.when
+
+class CheckServiceProcessStatusTest extends MsoGroovyTest {
+ @Before
+ void init() throws IOException {
+ super.init("CheckServiceProcessStatus")
+ }
+
+ @Captor
+ static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class)
+
+
+ @Test
+ void testPreProcessRequest () {
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345")
+ when(mockExecution.getVariable("operationId")).thenReturn("54321")
+
+ def successConditions = new ArrayList<>()
+ successConditions.add("finished")
+ successConditions.add("completed")
+
+ def errorConditions = new ArrayList<>()
+ errorConditions.add("error")
+ errorConditions.add("failed")
+
+ when(mockExecution.getVariable("successConditions")).thenReturn(successConditions)
+ when(mockExecution.getVariable("errorConditions")).thenReturn(errorConditions)
+
+
+ CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus()
+ serviceProcessStatus.preProcessRequest(mockExecution)
+ Mockito.verify(mockExecution, times(9)).setVariable(captor.capture(), captor.capture())
+ }
+
+
+ @Test
+ void testPreCheckServiceStatusReq() {
+ when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345")
+ when(mockExecution.getVariable("operationId")).thenReturn("54321")
+
+ CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus()
+
+ serviceProcessStatus.preCheckServiceStatusReq(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("getOperationStatus"), captor.capture())
+ String res = captor.getValue()
+ String expect =
+ """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:ns="http://org.onap.so/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <ns:getServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
+ <serviceId>12345</serviceId>
+ <operationId>54321</operationId>
+ </ns:getServiceOperationStatus>
+ </soapenv:Body>
+ </soapenv:Envelope>
+ """
+ assertEquals(expect.replaceAll("\\s+", ""), res.replaceAll("\\s+", ""))
+ }
+
+
+ @Test
+ void testHandlerServiceStatusRespSuccess() {
+ mockData()
+ when(mockExecution.getVariable("dbResponseCode")).thenReturn(200)
+ when(mockExecution.getVariable("dbResponse")).thenReturn(getDBResponse("finished"))
+ def successConditions = new ArrayList<>()
+ successConditions.add("finished")
+ successConditions.add("completed")
+
+ when(mockExecution.getVariable("successConditions")).thenReturn(successConditions)
+
+ CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus()
+ serviceProcessStatus.handlerServiceStatusResp(mockExecution)
+
+ Mockito.verify(mockExecution, times(4)).setVariable(captor.capture(), captor.capture())
+ def resultSuccess = captor.getAllValues()
+
+ def expect = new ArrayList<>()
+ expect.add("operationStatus")
+ expect.add("finished")
+ expect.add("operationContent")
+ expect.add("communication service create operation finished success")
+ expect.add("orchestrationStatus")
+ expect.add("deactivated")
+ expect.add("isAllFinished")
+ expect.add("true")
+
+ assertEquals(expect, resultSuccess)
+ }
+
+
+ @Test
+ void testHandlerServiceStatusRespError() {
+ mockData()
+ when(mockExecution.getVariable("dbResponseCode")).thenReturn(200)
+ when(mockExecution.getVariable("dbResponse")).thenReturn(getDBResponse("error"))
+
+ def successConditions = new ArrayList<>()
+ successConditions.add("finished")
+ successConditions.add("completed")
+
+ def errorConditions = new ArrayList<>()
+ errorConditions.add("error")
+ errorConditions.add("failed")
+
+ when(mockExecution.getVariable("successConditions")).thenReturn(successConditions)
+ when(mockExecution.getVariable("errorConditions")).thenReturn(errorConditions)
+
+ CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus()
+ serviceProcessStatus.handlerServiceStatusResp(mockExecution)
+
+ Mockito.verify(mockExecution, times(4)).setVariable(captor.capture(), captor.capture())
+ def resultSuccess = captor.getAllValues()
+
+ def expect = new ArrayList<>()
+ expect.add("operationStatus")
+ expect.add("error")
+ expect.add("operationContent")
+ expect.add("communication service create operation finished with error")
+ expect.add("orchestrationStatus")
+ expect.add("error")
+ expect.add("isAllFinished")
+ expect.add("true")
+
+ assertEquals(expect, resultSuccess)
+ }
+
+
+ @Test
+ void testHandlerServiceStatusRespProcessingNo() {
+ mockData()
+ when(mockExecution.getVariable("dbResponseCode")).thenReturn(200)
+ when(mockExecution.getVariable("dbResponse")).thenReturn(getDBResponse("processing"))
+ when(mockExecution.getVariable("progress")).thenReturn(50)
+
+ def successConditions = new ArrayList<>()
+ successConditions.add("finished")
+ successConditions.add("completed")
+
+ def errorConditions = new ArrayList<>()
+ errorConditions.add("error")
+ errorConditions.add("failed")
+
+ when(mockExecution.getVariable("successConditions")).thenReturn(successConditions)
+ when(mockExecution.getVariable("errorConditions")).thenReturn(errorConditions)
+
+ CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus()
+ serviceProcessStatus.handlerServiceStatusResp(mockExecution)
+
+ Mockito.verify(mockExecution, times(2)).setVariable(captor.capture(), captor.capture())
+ def resultSuccess = captor.getAllValues()
+
+ def expect = new ArrayList<>()
+ expect.add("isNeedUpdateDB")
+ expect.add("false")
+ expect.add("isAllFinished")
+ expect.add("false")
+
+ assertEquals(expect as String, resultSuccess as String)
+ }
+
+
+ @Test
+ void testHandlerServiceStatusRespProcessingYes() {
+ mockData()
+ when(mockExecution.getVariable("dbResponseCode")).thenReturn(200)
+ when(mockExecution.getVariable("dbResponse")).thenReturn(getDBResponse("processing"))
+ when(mockExecution.getVariable("progress")).thenReturn(60)
+
+ def successConditions = new ArrayList<>()
+ successConditions.add("finished")
+ successConditions.add("completed")
+
+ def errorConditions = new ArrayList<>()
+ errorConditions.add("error")
+ errorConditions.add("failed")
+
+ when(mockExecution.getVariable("successConditions")).thenReturn(successConditions)
+ when(mockExecution.getVariable("errorConditions")).thenReturn(errorConditions)
+
+ CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus()
+ serviceProcessStatus.handlerServiceStatusResp(mockExecution)
+
+ Mockito.verify(mockExecution, times(3)).setVariable(captor.capture(), captor.capture())
+ def resultSuccess = captor.getAllValues()
+
+ def expect = new ArrayList<>()
+ expect.add("progress")
+ expect.add("50")
+ expect.add("isNeedUpdateDB")
+ expect.add("true")
+ expect.add("isAllFinished")
+ expect.add("false")
+
+ assertEquals(expect as String, resultSuccess as String)
+ }
+
+
+ @Test
+ void testTimeWaitDelayNo() {
+ mockData()
+ when(mockExecution.getVariable("startTime")).thenReturn(System.currentTimeMillis())
+ CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus()
+
+ serviceProcessStatus.timeWaitDelay(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("isTimeOut"), captor.capture())
+ def res = captor.getValue()
+
+ assertEquals("NO", res)
+ }
+
+
+ @Test
+ void testTimeWaitDelayYes() {
+ mockData()
+ when(mockExecution.getVariable("startTime")).thenReturn(1000000)
+ CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus()
+
+ serviceProcessStatus.timeWaitDelay(mockExecution)
+ Mockito.verify(mockExecution, times(4)).setVariable(captor.capture(), captor.capture())
+ def res = captor.getAllValues()
+ def expect = new ArrayList<>()
+ expect.add("operationStatus")
+ expect.add("error")
+ expect.add("operationContent")
+ expect.add("communication service create operation finished with timeout")
+ expect.add("orchestrationStatus")
+ expect.add("error")
+ expect.add("isTimeOut")
+ expect.add("YES")
+
+ assertEquals(expect, res)
+ }
+
+
+ @Test
+ void testPreUpdateOperationProgress() {
+ mockData()
+ when(mockExecution.getVariable("progress")).thenReturn(50)
+ when(mockExecution.getVariable("initProgress")).thenReturn(20)
+ when(mockExecution.getVariable("endProgress")).thenReturn(90)
+ when(mockExecution.getVariable("operationType")).thenReturn("CREATE")
+ when(mockExecution.getVariable("processServiceType")).thenReturn("communication service")
+ when(mockExecution.getVariable("parentServiceInstanceId")).thenReturn("12345")
+ when(mockExecution.getVariable("parentOperationId")).thenReturn("54321")
+ when(mockExecution.getVariable("globalSubscriberId")).thenReturn("11111")
+
+ CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus()
+ serviceProcessStatus.preUpdateOperationProgress(mockExecution)
+ Mockito.verify(mockExecution, times(1)).setVariable(eq("updateOperationStatus"), captor.capture())
+ String res = captor.getValue()
+
+ String expect = getExpectPayload("55",
+ "communication service CREATE operation processing 55")
+
+ assertEquals(expect.replaceAll("\\s+", ""), res.replaceAll("\\s+", ""))
+
+
+ }
+
+
+ private static String getExpectPayload(String progress, String operationContent) {
+ String expect =
+ """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:ns="http://org.onap.so/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
+ <serviceId>12345</serviceId>
+ <operationId>54321</operationId>
+ <operationType>CREATE</operationType>
+ <userId>11111</userId>
+ <result>processing</result>
+ <operationContent>${operationContent}</operationContent>
+ <progress>${progress}</progress>
+ <reason></reason>
+ </ns:updateServiceOperationStatus>
+ </soapenv:Body>
+ </soapenv:Envelope>
+ """
+ return expect
+ }
+
+
+ private static String getDBResponse(String result) {
+ String response =
+ """<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <ns2:getServiceOperationStatusResponse xmlns:ns2="http://org.onap.so/requestsdb">
+ <return><operation>CREATE</operation>
+ <operationContent>Prepare service creation</operationContent>
+ <operationId>077995e3-eb32-44ae-b35d-491fc6983a44</operationId>
+ <progress>50</progress>
+ <reason></reason>
+ <result>${result}</result>
+ <serviceId>3324f117-696d-4518-b8b5-b01fcc127a03</serviceId>
+ <userId>5GCustomer</userId>
+ </return></ns2:getServiceOperationStatusResponse>
+ </soap:Body>
+ </soap:Envelope>
+ """
+ return response
+ }
+
+
+ private mockData() {
+ when(mockExecution.getVariable("processServiceType")).thenReturn("communication service")
+ when(mockExecution.getVariable("operationType")).thenReturn("create")
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcherTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcherTest.java
new file mode 100644
index 0000000000..3c568ffc83
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/NfSoftwareUpgradeDispatcherTest.java
@@ -0,0 +1,182 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.infrastructure.pnf.delegate;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.onap.aai.domain.yang.Pnf;
+import org.onap.so.bpmn.core.json.JsonUtils;
+import org.onap.so.bpmn.infrastructure.pnf.management.PnfManagement;
+import org.onap.so.db.catalog.beans.PnfResourceCustomization;
+import org.onap.so.db.catalog.client.CatalogDbClient;
+import org.onap.so.serviceinstancebeans.ModelInfo;
+import org.onap.so.serviceinstancebeans.RequestDetails;
+import org.onap.so.serviceinstancebeans.RequestInfo;
+import org.onap.so.serviceinstancebeans.RequestParameters;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import java.io.IOException;
+import java.util.*;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.when;
+import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.*;
+import static org.onap.so.client.cds.PayloadConstants.PRC_TARGET_SOFTWARE_VERSION;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+public class NfSoftwareUpgradeDispatcherTest {
+
+ private static final String TEST_PROCESS_KEY = "processKey1";
+ private static final String PROCESS_KEY = "testProcessKey";
+ private static final String TEST_PNF_RESOURCE_INSTANCE_NAME = "PNF_demo_resource";
+ private static final String TEST_PNF_RESOURCE_BLUEPRINT_NAME = "blueprintOnap";
+ private static final String TEST_PNF_RESOURCE_BLUEPRINT_VERSION = "1.0.1";
+ private static final String TEST_PNF_RESOURCE_CUSTOMIZATION_UUID = "9acb3a83-8a52-412c-9a45-901764938144";
+ private static final String TEST_PNF_CORRELATION_ID = "PNFDemo";
+ private static final String TEST_PNF_UUID = "FakeID";
+ private static final String TEST_PRC_CONTROLLER_ACTOR = "cds";
+ private static final String TEST_TARGET_SOFTWARE_VERSION = "demo-sw-ver2.0.0";
+
+ private static final String TEST_BPMN_REQUEST = "{\"requestDetails\":{" + "\"requestInfo\":{"
+ + "\"source\":\"VID\"," + "\"suppressRollback\":false," + "\"requestorId\":\"demo\","
+ + "\"productFamilyId\":\"SWUPid\"}," + "\"modelInfo\":{"
+ + "\"modelType\":\"service\",\"modelInvariantUuid\":\"439b7a2f-9524-4dbf-9eee-f2e05521df3f\","
+ + "\"modelInvariantId\":\"439b7a2f-9524-4dbf-9eee-f2e05521df3f\","
+ + "\"modelUuid\":\"42daaac6-5017-4e1e-96c8-6a27dfbe1421\",\"modelName\":\"PNF_int_service_2\","
+ + "\"modelVersion\":\"1.0\"},\"requestParameters\":{\"userParams\":[{\"name\":\"aic_zone\","
+ + "\"value\":\"nova\"},{\"name\":\"pnfId\",\"value\":\"PNFDemo\"},{\"name\":\"targetSoftwareVersion\",\"value\":\"demo-sw-ver2.0.0\"}],"
+ + "\"subscriptionServiceType\":\"SWUP\",\"aLaCarte\":false,\"pnfCorrelationId\":\"PNFDemo\"},"
+ + "\"cloudConfiguration\":{\"lcpCloudRegionId\":\"regionOne\",\"tenantId\":\"09a63533072f4a579d5c99c3b8fe94c6\"},"
+ + "\"subscriberInfo\":{\"globalSubscriberId\":\"ADemoCustomerInEric\"},\"project\":{\"projectName\":\"Project-Demonstration\"},"
+ + "\"owningEntity\":{\"owningEntityId\":\"5eae949c-1c50-4780-b8b5-7cbeb08856b4\",\"owningEntityName\":\"OE-Demonstration\"}}}";
+ /**
+ * Testing model UUID, should be the same as specified in the TEST_SERVICE_MODEL_INFO.
+ */
+ private static final String TEST_MODEL_UUID = "42daaac6-5017-4e1e-96c8-6a27dfbe1421";
+
+ @InjectMocks
+ private NfSoftwareUpgradeDispatcher nfSoftwareUpgradeDispatcher;
+
+ @Mock
+ private PnfManagement pnfManagement;
+
+ @Mock
+ private CatalogDbClient catalogDbClient;
+
+ @Mock
+ private ObjectMapper mapper;
+
+ private DelegateExecution execution = new DelegateExecutionFake();
+
+ @Before
+ public void setUp() throws IOException {
+ List<PnfResourceCustomization> pnfResourceCustomizations = new ArrayList<>();
+ pnfResourceCustomizations.add(buildPnfResourceCustomization());
+ given(catalogDbClient.getPnfResourceCustomizationByModelUuid(TEST_MODEL_UUID))
+ .willReturn(pnfResourceCustomizations);
+ execution.setVariable(PROCESS_KEY, TEST_PROCESS_KEY);
+ execution.setVariable("bpmnRequest", TEST_BPMN_REQUEST);
+ mockMapper();
+ mockAai();
+
+ }
+
+
+ @Test
+ public void testExecution_validCatalogDb_skipVariableSet() {
+ try {
+ nfSoftwareUpgradeDispatcher.execute(execution);
+ assertThat(execution.getVariable(MODEL_UUID)).isEqualTo(TEST_MODEL_UUID);
+ assertThat(execution.getVariable(PRC_TARGET_SOFTWARE_VERSION)).isEqualTo(TEST_TARGET_SOFTWARE_VERSION);
+ assertThat(execution.getVariable(PRC_BLUEPRINT_NAME)).isEqualTo(TEST_PNF_RESOURCE_BLUEPRINT_NAME);
+ assertThat(execution.getVariable(PRC_BLUEPRINT_VERSION)).isEqualTo(TEST_PNF_RESOURCE_BLUEPRINT_VERSION);
+ assertThat(execution.getVariable(PRC_CUSTOMIZATION_UUID)).isEqualTo(TEST_PNF_RESOURCE_CUSTOMIZATION_UUID);
+ assertThat(execution.getVariable(PRC_INSTANCE_NAME)).isEqualTo(TEST_PNF_RESOURCE_INSTANCE_NAME);
+ assertThat(execution.getVariable(PNF_CORRELATION_ID)).isEqualTo(TEST_PNF_CORRELATION_ID);
+ assertThat(execution.getVariable(PNF_UUID)).isEqualTo(TEST_PNF_UUID);
+ assertThat(execution.getVariable(PRC_CONTROLLER_ACTOR)).isEqualTo(TEST_PRC_CONTROLLER_ACTOR);
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail("Exception thrown" + e.getMessage());
+ }
+ }
+
+ private void mockAai() throws IOException {
+ Pnf pnf = new Pnf();
+ pnf.setPnfId(TEST_PNF_UUID);
+ when(pnfManagement.getEntryFor(TEST_PNF_CORRELATION_ID)).thenReturn(Optional.of(pnf));
+ }
+
+ private PnfResourceCustomization buildPnfResourceCustomization() {
+ PnfResourceCustomization pnfResourceCustomization = new PnfResourceCustomization();
+ pnfResourceCustomization.setSkipPostInstConf(true);
+ pnfResourceCustomization.setBlueprintName(TEST_PNF_RESOURCE_BLUEPRINT_NAME);
+ pnfResourceCustomization.setBlueprintVersion(TEST_PNF_RESOURCE_BLUEPRINT_VERSION);
+ pnfResourceCustomization.setModelInstanceName(TEST_PNF_RESOURCE_INSTANCE_NAME);
+ pnfResourceCustomization.setModelCustomizationUUID(TEST_PNF_RESOURCE_CUSTOMIZATION_UUID);
+ pnfResourceCustomization.setControllerActor(TEST_PRC_CONTROLLER_ACTOR);
+ return pnfResourceCustomization;
+ }
+
+ private void mockMapper() throws IOException {
+ RequestDetails bpmnRequestDetails = new RequestDetails();
+
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("demo");
+ bpmnRequestDetails.setRequestInfo(requestInfo);
+
+ RequestParameters requestParameters = new RequestParameters();
+ List<Map<String, Object>> userParams = new ArrayList<>();
+ Map<String, Object> map = new HashMap<>();
+ map.put("name", "targetSoftwareVersion");
+ map.put("value", TEST_TARGET_SOFTWARE_VERSION);
+ userParams.add(map);
+ map = new HashMap<>();
+ map.put("name", "pnfName");
+ map.put("value", "PNFDemo");
+ userParams.add(map);
+ requestParameters.setUserParams(userParams);
+
+ bpmnRequestDetails.setRequestParameters(requestParameters);
+
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelInvariantUuid("439b7a2f-9524-4dbf-9eee-f2e05521df3f");
+ modelInfo.setModelInvariantId("439b7a2f-9524-4dbf-9eee-f2e05521df3f");
+ modelInfo.setModelUuid("42daaac6-5017-4e1e-96c8-6a27dfbe1421");
+ modelInfo.setModelName("PNF_int_service_2");
+ modelInfo.setModelVersion("1.0");
+
+ bpmnRequestDetails.setModelInfo(modelInfo);
+
+
+ doReturn(bpmnRequestDetails).when(mapper).readValue(
+ JsonUtils.getJsonValue(String.valueOf(execution.getVariable("bpmnRequest")), "requestDetails"),
+ RequestDetails.class);
+ }
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java
index 8577d9555b..b93902d9f7 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java
@@ -50,6 +50,11 @@ public class PnfManagementTestImpl implements PnfManagement {
}
@Override
+ public void updateEntry(String pnfCorrelationId, Pnf entry) throws IOException {
+ created.put(pnfCorrelationId, entry);
+ }
+
+ @Override
public void createRelation(String serviceInstanceId, String pnfName) {}
public Map<String, Pnf> getCreated() {
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementThrowingException.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementThrowingException.java
index f9b467c650..77377db9d9 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementThrowingException.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementThrowingException.java
@@ -38,6 +38,11 @@ public class PnfManagementThrowingException implements PnfManagement {
}
@Override
+ public void updateEntry(String pnfCorrelationId, Pnf entry) throws IOException {
+ throw new IOException();
+ }
+
+ @Override
public void createRelation(String serviceInstanceId, String pnfName) throws IOException {
throw new IOException();
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/UpdatePnfEntryInAaiTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/UpdatePnfEntryInAaiTest.java
new file mode 100644
index 0000000000..bddfe5b180
--- /dev/null
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/UpdatePnfEntryInAaiTest.java
@@ -0,0 +1,91 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.bpmn.infrastructure.pnf.delegate;
+
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.onap.aai.domain.yang.Pnf;
+import org.onap.so.bpmn.infrastructure.pnf.management.PnfManagement;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import static org.junit.Assert.*;
+import java.io.IOException;
+import java.util.Optional;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.*;
+import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID;
+import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
+import static org.onap.so.client.cds.PayloadConstants.PRC_TARGET_SOFTWARE_VERSION;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+public class UpdatePnfEntryInAaiTest {
+
+ @InjectMocks
+ private UpdatePnfEntryInAai updatePnfEntryInAai;
+
+ @Mock
+ private PnfManagement pnfManagementTest;
+
+ private DelegateExecution execution;
+
+
+
+ @Test
+ public void shouldSetSwVersion() throws Exception {
+ // given
+ setupPnf();
+ setupExecution();
+
+ // when
+ updatePnfEntryInAai.execute(execution);
+
+ // verify
+ Optional<Pnf> modifiedEntry = pnfManagementTest.getEntryFor("testPnfCorrelationId");
+ assertNotNull(modifiedEntry.get());
+ assertThat(modifiedEntry.get().getPnfId()).isEqualTo("testtest");
+ assertThat(modifiedEntry.get().getPnfName()).isEqualTo("testPnfCorrelationId");
+ assertThat(modifiedEntry.get().getSwVersion()).isEqualTo("demo-1.2");
+ verify(pnfManagementTest, times(2)).getEntryFor(anyString());
+ }
+
+ private void setupPnf() {
+ try {
+ Pnf pnf = new Pnf();
+ pnf.setSwVersion("1");
+ pnf.setPnfId("testtest");
+ pnf.setPnfName("testPnfCorrelationId");
+ doReturn(Optional.of(pnf)).when(pnfManagementTest).getEntryFor(anyString());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void setupExecution() {
+ execution = mock(DelegateExecution.class);
+ given(execution.getVariable(eq(PNF_CORRELATION_ID))).willReturn("testPnfCorrelationId");
+ given(execution.getVariable(eq(PNF_UUID))).willReturn("testtest");
+ given(execution.getVariable(eq(PRC_TARGET_SOFTWARE_VERSION))).willReturn("demo-1.2");
+ }
+}