2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  # Copyright (c) 2019, CMCC Technologies Co., Ltd.
 
   7  # Licensed under the Apache License, Version 2.0 (the "License")
 
   8  # you may not use this file except in compliance with the License.
 
   9  # You may obtain a copy of the License at
 
  11  #       http://www.apache.org/licenses/LICENSE-2.0
 
  13  # Unless required by applicable law or agreed to in writing, software
 
  14  # distributed under the License is distributed on an "AS IS" BASIS,
 
  15  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  16  # See the License for the specific language governing permissions and
 
  17  # limitations under the License.
 
  18  * ============LICENSE_END=========================================================
 
  21 package org.onap.so.bpmn.infrastructure.scripts
 
  23 import org.camunda.bpm.engine.delegate.BpmnError
 
  24 import org.camunda.bpm.engine.delegate.DelegateExecution
 
  25 import org.onap.aai.domain.yang.Relationship
 
  26 import org.onap.aai.domain.yang.RelationshipData
 
  27 import org.onap.aai.domain.yang.RelationshipList
 
  28 import org.onap.aai.domain.yang.ServiceInstance
 
  29 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
 
  30 import org.onap.so.bpmn.common.scripts.ExceptionUtil
 
  31 import org.onap.so.bpmn.common.scripts.MsoUtils
 
  32 import org.onap.so.bpmn.common.scripts.RequestDBUtil
 
  33 import org.onap.so.bpmn.core.UrnPropertiesReader
 
  34 import org.onap.so.bpmn.core.WorkflowException
 
  35 import org.onap.so.bpmn.core.json.JsonUtils
 
  36 import org.onap.so.client.aai.AAIObjectType
 
  37 import org.onap.so.client.aai.AAIResourcesClient
 
  38 import org.onap.so.client.aai.entities.AAIResultWrapper
 
  39 import org.onap.so.client.aai.entities.uri.AAIResourceUri
 
  40 import org.onap.so.client.aai.entities.uri.AAIUriFactory
 
  41 import org.onap.so.db.request.beans.OperationStatus
 
  42 import org.slf4j.Logger
 
  43 import org.slf4j.LoggerFactory
 
  45 import javax.ws.rs.NotFoundException
 
  47 import static org.apache.commons.lang3.StringUtils.isBlank
 
  49 class ActivateCommunicationService extends AbstractServiceTaskProcessor {
 
  53     ExceptionUtil exceptionUtil = new ExceptionUtil()
 
  55     RequestDBUtil requestDBUtil = new RequestDBUtil()
 
  57     JsonUtils jsonUtil = new JsonUtils()
 
  59     AAIResourcesClient client = getAAIClient()
 
  61     private static final Logger logger = LoggerFactory.getLogger(ActivateCommunicationService.class)
 
  64     void preProcessRequest(DelegateExecution execution) {
 
  65         logger.debug(Prefix + "preProcessRequest Start")
 
  66         execution.setVariable("prefix", Prefix)
 
  70             // check for incoming json message/input
 
  71             String siRequest = execution.getVariable("bpmnRequest")
 
  72             logger.debug(siRequest)
 
  74             String requestId = execution.getVariable("mso-request-id")
 
  75             execution.setVariable("msoRequestId", requestId)
 
  76             logger.info("Input Request:" + siRequest + " reqId:" + requestId)
 
  78             String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
  79             if (isBlank(serviceInstanceId)) {
 
  80                 msg = "Input serviceInstanceId' is null"
 
  81                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
 
  84             String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "globalSubscriberId")
 
  85             if (isBlank(globalSubscriberId)) {
 
  86                 msg = "Input globalSubscriberId' is null"
 
  88                 execution.setVariable("globalSubscriberId", "5GCustomer")
 
  90                 execution.setVariable("globalSubscriberId", globalSubscriberId)
 
  93             String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "serviceType")
 
  94             if (isBlank(subscriptionServiceType)) {
 
  95                 msg = "Input subscriptionServiceType is null"
 
  97                 execution.setVariable("subscriptionServiceType", "5G")
 
  99                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
 
 102             String operationId = jsonUtil.getJsonValue(siRequest, "operationId")
 
 103             execution.setVariable("operationId", operationId)
 
 105             String operationType = execution.getVariable("operationType")
 
 106             execution.setVariable("operationType", operationType.toUpperCase())
 
 108         } catch (BpmnError e) {
 
 110         } catch (Exception ex) {
 
 111             msg = "Exception in preProcessRequest " + ex.getMessage()
 
 113             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 115         logger.debug(Prefix + "preProcessRequest Exit")
 
 119     def checkAAIOrchStatus = { DelegateExecution execution ->
 
 121         logger.debug(Prefix + "checkAAIOrchStatus Start")
 
 124         String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 125         String globalSubscriberId = execution.getVariable("globalSubscriberId")
 
 126         String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
 
 127         String operationType = execution.getVariable("operationType")
 
 129         logger.debug("serviceInstanceId: " + serviceInstanceId)
 
 131         //check the cms status
 
 133             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
 
 134                     globalSubscriberId, subscriptionServiceType, serviceInstanceId)
 
 136             if (!client.exists(uri)) {
 
 137                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
 
 140             AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
 
 141             Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
 
 144                 if (si.get().getOrchestrationStatus().toLowerCase() == "activated" &&
 
 145                         operationType.equalsIgnoreCase("deactivation")) {
 
 146                     logger.info("Service is in active state")
 
 147                     execution.setVariable("serviceExpectStatus", "deactivated")
 
 148                     execution.setVariable("isContinue", "true")
 
 149                     execution.setVariable("requestParam", "deactivate")
 
 151                 } else if (si.get().getOrchestrationStatus().toLowerCase()  == "deactivated" &&
 
 152                         operationType.equalsIgnoreCase("activation")){
 
 153                     logger.info("Service is  in de-activated state")
 
 154                     execution.setVariable("serviceExpectStatus", "activated")
 
 155                     execution.setVariable("isContinue", "true")
 
 156                     execution.setVariable("requestParam", "activate")
 
 159                     execution.setVariable("isContinue", "false")
 
 162                 RelationshipList relationshipList = si.get().getRelationshipList()
 
 163                 List<Relationship> relationship
 
 164                 if (relationshipList != null && (relationship = relationshipList.getRelationship()) != null
 
 165                         && relationship.size() > 0) {
 
 166                     List<RelationshipData> relationshipDatas = relationship.get(0).getRelationshipData()
 
 168                     for (RelationshipData relationshipData : relationshipDatas) {
 
 169                         execution.setVariable("e2e_" + relationshipData.getRelationshipKey(),
 
 170                                 relationshipData.getRelationshipValue())
 
 173                     msg = "the communication service has no e2e service"
 
 174                     exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
 
 178         } catch (BpmnError e) {
 
 180         } catch (Exception ex) {
 
 181             msg = "Exception in " + Prefix + "checkAAIOrchStatus: " + ex.getMessage()
 
 183             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 186         logger.debug(Prefix + "checkAAIOrchStatus Exit")
 
 190     def prepareInitOperationStatus = { DelegateExecution execution ->
 
 191         logger.debug(Prefix + "prepareInitOperationStatus Start")
 
 193         String serviceId = execution.getVariable("serviceInstanceId")
 
 196         String operationId = execution.getVariable("operationId")
 
 198         String operationType = execution.getVariable("operationType")
 
 200         OperationStatus initStatus = new OperationStatus()
 
 201         initStatus.setServiceId(serviceId)
 
 202         initStatus.setOperationId(operationId)
 
 203         initStatus.setOperation(operationType)
 
 204         initStatus.setUserId(execution.getVariable("globalSubscriberId") as String)
 
 205         initStatus.setResult("processing")
 
 206         initStatus.setProgress("0")
 
 207         initStatus.setReason("")
 
 208         initStatus.setOperationContent("communication service active operation start")
 
 210         requestDBUtil.prepareUpdateOperationStatus(execution, initStatus)
 
 212         logger.debug(Prefix + "prepareInitOperationStatus Exit")
 
 216     def sendSyncResponse = { DelegateExecution execution ->
 
 217         logger.debug(Prefix + "sendSyncResponse Start")
 
 219             String operationId = execution.getVariable("operationId")
 
 221             String restRequest = """{"operationId":"${operationId}"}""".trim()
 
 222             logger.debug(" sendSyncResponse to APIH:" + "\n" + restRequest)
 
 224             sendWorkflowResponse(execution, 202, restRequest)
 
 225             execution.setVariable("sentSyncResponse", true)
 
 226         } catch (Exception ex) {
 
 227             String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
 
 229             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 231         logger.debug(Prefix + "sendSyncResponse Exit")
 
 235     def preRequestSend2NSMF = { DelegateExecution execution ->
 
 236         logger.debug(Prefix + "preRequestSend2NSMF Start")
 
 239             String e2eServiceInstanceId = execution.getVariable("e2e_service-instance.service-instance-id")
 
 240             execution.setVariable("e2eServiceInstanceId", e2eServiceInstanceId)
 
 242             String requestParam = execution.getVariable("requestParam")
 
 243             //String NSMF_endpoint = "/onap/so/infra/e2eServiceInstances/v3"
 
 244             def NSMF_endpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
 
 245             def url = NSMF_endpoint + "/e2eServiceInstances/v3/${e2eServiceInstanceId}/${requestParam}"
 
 246             execution.setVariable("NSMF_endpoint", url)
 
 248             //get from model catalog inputs
 
 251                     "globalSubscriberId": "${execution.getVariable("globalSubscriberId")}",
 
 252                     "serviceType": "${execution.getVariable("subscriptionServiceType")}"
 
 255             execution.setVariable("CSMF_NSMFRequest", payload.replaceAll("\\s+", ""))
 
 257         } catch (BpmnError e) {
 
 259         } catch (Exception ex) {
 
 260             String msg = "Exception in " + Prefix + "preRequestSend2NSMF. " + ex.getMessage()
 
 262             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 265         logger.debug(Prefix + "preRequestSend2NSMF Exit")
 
 269     def processNSMFResponse = { DelegateExecution execution ->
 
 270         logger.debug(Prefix + "processNSMFResponse Start")
 
 273             def CSMF_NSMFResponseCode = execution.getVariable("CSMF_NSMFResponseCode") as Integer
 
 274             if (CSMF_NSMFResponseCode >= 200 && CSMF_NSMFResponseCode < 400) {
 
 275                 def CSMF_NSMFResponse = execution.getVariable("CSMF_NSMFResponse") as String
 
 276                 def e2eOperationId = jsonUtil.getJsonValue(CSMF_NSMFResponse, "operationId")
 
 278                 execution.setVariable("e2eOperationId", e2eOperationId)
 
 279                 execution.setVariable("ProcessNsmfSuccess", "OK")
 
 281                 execution.setVariable("ProcessNsmfSuccess", "ERROR")
 
 282                 execution.setVariable("operationStatus", "error")
 
 283                 execution.setVariable("operationContent",
 
 284                         "communication service " + execution.getVariable("operationType")
 
 285                                 + " operation error: nsmf response fail")
 
 286                 execution.setVariable("orchestrationStatus", "error")
 
 289         } catch (BpmnError e) {
 
 291         } catch (Exception ex) {
 
 292             String msg = "Exception in " + Prefix + "processOOFResponse. " + ex.getMessage()
 
 294             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 296         logger.debug(Prefix + "processNSMFResponse Exit")
 
 300     def prepareUpdateOperationStatus = { DelegateExecution execution ->
 
 301         logger.debug(Prefix + "prepareUpdateOperationStatus Start")
 
 302         // update status creating
 
 303         OperationStatus status = new OperationStatus()
 
 304         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
 
 305         status.setOperationId(execution.getVariable("operationId") as String)
 
 306         status.setOperation(execution.getVariable("operationType") as String)
 
 307         status.setResult("processing")
 
 308         status.setProgress("20")
 
 309         status.setOperationContent("communication service "+ execution.getVariable("operationType")
 
 310                 + " operation processing: waiting nsmf service create finished")
 
 311         status.setUserId(execution.getVariable("globalSubscriberId") as String)
 
 313         requestDBUtil.prepareUpdateOperationStatus(execution, status)
 
 314         logger.debug(Prefix + "prepareUpdateOperationStatus Exit")
 
 319     def prepareCallCheckProcessStatus = { DelegateExecution execution ->
 
 320         logger.debug(Prefix + "prepareCallCheckProcessStatus Start")
 
 322         def successConditions = new ArrayList<>()
 
 323         successConditions.add("finished")
 
 324         execution.setVariable("successConditions", successConditions)
 
 326         def errorConditions = new ArrayList<>()
 
 327         errorConditions.add("error")
 
 328         execution.setVariable("errorConditions", errorConditions)
 
 330         execution.setVariable("processServiceType", "communication service")
 
 332         execution.setVariable("timeOut", 3 * 60 * 60 * 1000)
 
 334         def successParamMap = new HashMap<String, Object>()
 
 335         successParamMap.put("orchestrationStatus", execution.getVariable("serviceExpectStatus"))
 
 337         execution.setVariable("successParamMap", successParamMap)
 
 339         def errorParamMap = new HashMap<String, Object>()
 
 340         errorParamMap.put("orchestrationStatus", "error")
 
 342         execution.setVariable("errorParamMap", errorParamMap)
 
 344         def timeOutParamMap = new HashMap<String, Object>()
 
 345         timeOutParamMap.put("orchestrationStatus", "error")
 
 347         execution.setVariable("timeOutParamMap", timeOutParamMap)
 
 349         execution.setVariable("initProgress", 20)
 
 350         execution.setVariable("endProgress", 90)
 
 352         logger.debug(Prefix + "prepareCallCheckProcessStatus Exit")
 
 357      * prepare update operation status to complete after NSMF process success
 
 360     def prepareCompleteStatus = { DelegateExecution execution ->
 
 362         logger.debug(Prefix + "prepareCompleteStatus Start")
 
 363         String operationType = execution.getVariable("operationType")
 
 364         OperationStatus status = new OperationStatus()
 
 365         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
 
 366         status.setOperationId(execution.getVariable("operationId") as String)
 
 367         status.setOperation(operationType)
 
 368         status.setResult(execution.getVariable("operationStatus") as String)
 
 369         status.setProgress("100")
 
 370         status.setOperationContent(execution.getVariable("operationContent") as String)
 
 371         status.setUserId(execution.getVariable("globalSubscriberId") as String)
 
 373         requestDBUtil.prepareUpdateOperationStatus(execution, status)
 
 374         logger.debug("prepareCompleteStatus end, serviceInstanceId: " + execution.getVariable("serviceInstanceId")
 
 375                 + ", operationId: " + execution.getVariable("operationId"))
 
 377         logger.debug(Prefix + "prepareCompleteStatus Exit")
 
 382      * update NSMF complete status to AAI when the NSMF process finished
 
 385     def updateFinishStatusInAAI = { DelegateExecution execution ->
 
 386         logger.debug(Prefix + "updateFinishStatusInAAI Start")
 
 390             String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 391             String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
 
 392             String globalSubscriberId = execution.getVariable("globalSubscriberId")
 
 393             String orchestrationStatus = execution.getVariable("orchestrationStatus")
 
 395             ServiceInstance csi = new ServiceInstance()
 
 396             csi.setOrchestrationStatus(orchestrationStatus)
 
 397             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
 
 398                     globalSubscriberId, subscriptionServiceType, serviceInstanceId)
 
 399             client.update(uri, csi)
 
 401         } catch (BpmnError e) {
 
 403         } catch (Exception ex) {
 
 404             msg = "Exception in complete communication service " + ex.getMessage()
 
 406             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 408         logger.debug(Prefix + "updateFinishStatusInAAI Exit")
 
 412     public sendSyncError = { DelegateExecution execution ->
 
 413         logger.debug("sendSyncError Start")
 
 416             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
 
 417                 WorkflowException wfe = execution.getVariable("WorkflowException") as WorkflowException
 
 418                 errorMessage = wfe.getErrorMessage()
 
 420                 errorMessage = "Sending Sync Error."
 
 423             String buildWorkflowException =
 
 424                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
 
 425                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
 
 426                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
 
 427                                    </aetgt:WorkflowException>"""
 
 429             logger.debug(buildWorkflowException)
 
 430             sendWorkflowResponse(execution, 500, buildWorkflowException)
 
 432         } catch (Exception ex) {
 
 433             logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
 
 435         logger.debug(Prefix + "sendSyncError Exit")