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         } catch (BpmnError e) {
 
 107         } catch (Exception ex) {
 
 108             msg = "Exception in preProcessRequest " + ex.getMessage()
 
 110             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 112         logger.debug(Prefix + "preProcessRequest Exit")
 
 116     def checkAAIOrchStatus = { DelegateExecution execution ->
 
 118         logger.debug(Prefix + "checkAAIOrchStatus Start")
 
 121         String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 122         String globalSubscriberId = execution.getVariable("globalSubscriberId")
 
 123         String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
 
 124         String operationType = execution.getVariable("operationType")
 
 126         logger.debug("serviceInstanceId: " + serviceInstanceId)
 
 128         //check the cms status
 
 130             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
 
 131                     globalSubscriberId, subscriptionServiceType, serviceInstanceId)
 
 133             if (!client.exists(uri)) {
 
 134                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
 
 137             AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
 
 138             Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
 
 141                 if (si.get().getOrchestrationStatus().toLowerCase() == "activated" &&
 
 142                         operationType == "deactivation") {
 
 143                     logger.info("Service is in active state")
 
 144                     execution.setVariable("serviceExpectStatus", "deactivated")
 
 145                     execution.setVariable("isContinue", "true")
 
 146                     execution.setVariable("requestParam", "deactivate")
 
 148                 } else if (si.get().getOrchestrationStatus().toLowerCase()  == "deactivated" &&
 
 149                         operationType == "activation"){
 
 150                     logger.info("Service is  in de-activated state")
 
 151                     execution.setVariable("serviceExpectStatus", "activated")
 
 152                     execution.setVariable("isContinue", "true")
 
 153                     execution.setVariable("requestParam", "activate")
 
 156                     execution.setVariable("isContinue", "false")
 
 159                 RelationshipList relationshipList = si.get().getRelationshipList()
 
 160                 List<Relationship> relationship
 
 161                 if (relationshipList != null && (relationship = relationshipList.getRelationship()) != null
 
 162                         && relationship.size() > 0) {
 
 163                     List<RelationshipData> relationshipDatas = relationship.get(0).getRelationshipData()
 
 165                     for (RelationshipData relationshipData : relationshipDatas) {
 
 166                         execution.setVariable("e2e_" + relationshipData.getRelationshipKey(),
 
 167                                 relationshipData.getRelationshipValue())
 
 170                     msg = "the communication service has no e2e service"
 
 171                     exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
 
 175         } catch (BpmnError e) {
 
 177         } catch (Exception ex) {
 
 178             msg = "Exception in " + Prefix + "checkAAIOrchStatus: " + ex.getMessage()
 
 180             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 183         logger.debug(Prefix + "checkAAIOrchStatus Exit")
 
 187     def prepareInitOperationStatus = { DelegateExecution execution ->
 
 188         logger.debug(Prefix + "prepareInitOperationStatus Start")
 
 190         String serviceId = execution.getVariable("serviceInstanceId")
 
 193         String operationId = execution.getVariable("operationId")
 
 195         String operationType = execution.getVariable("operationType")
 
 197         OperationStatus initStatus = new OperationStatus()
 
 198         initStatus.setServiceId(serviceId)
 
 199         initStatus.setOperationId(operationId)
 
 200         initStatus.setOperation(operationType)
 
 201         initStatus.setUserId(execution.getVariable("globalSubscriberId") as String)
 
 202         initStatus.setResult("processing")
 
 203         initStatus.setProgress("0")
 
 204         initStatus.setReason("")
 
 205         initStatus.setOperationContent("communication service active operation start")
 
 207         requestDBUtil.prepareUpdateOperationStatus(execution, initStatus)
 
 209         logger.debug(Prefix + "prepareInitOperationStatus Exit")
 
 213     def sendSyncResponse = { DelegateExecution execution ->
 
 214         logger.debug(Prefix + "sendSyncResponse Start")
 
 216             String operationId = execution.getVariable("operationId")
 
 218             String restRequest = """{"operationId":"${operationId}"}""".trim()
 
 219             logger.debug(" sendSyncResponse to APIH:" + "\n" + restRequest)
 
 221             sendWorkflowResponse(execution, 202, restRequest)
 
 222             execution.setVariable("sentSyncResponse", true)
 
 223         } catch (Exception ex) {
 
 224             String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
 
 226             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 228         logger.debug(Prefix + "sendSyncResponse Exit")
 
 232     def preRequestSend2NSMF = { DelegateExecution execution ->
 
 233         logger.debug(Prefix + "preRequestSend2NSMF Start")
 
 236             String e2eServiceInstanceId = execution.getVariable("e2e_service-instance.service-instance-id")
 
 237             execution.setVariable("e2eServiceInstanceId", e2eServiceInstanceId)
 
 239             String requestParam = execution.getVariable("requestParam")
 
 240             //String NSMF_endpoint = "/onap/so/infra/e2eServiceInstances/v3"
 
 241             def NSMF_endpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
 
 242             def url = NSMF_endpoint + "/e2eServiceInstances/v3/${e2eServiceInstanceId}/${requestParam}"
 
 243             execution.setVariable("NSMF_endpoint", url)
 
 245             //get from model catalog inputs
 
 248                     "globalSubscriberId": "${execution.getVariable("globalSubscriberId")}",
 
 249                     "serviceType": "${execution.getVariable("subscriptionServiceType")}"
 
 252             execution.setVariable("CSMF_NSMFRequest", payload.replaceAll("\\s+", ""))
 
 254         } catch (BpmnError e) {
 
 256         } catch (Exception ex) {
 
 257             String msg = "Exception in " + Prefix + "preRequestSend2NSMF. " + ex.getMessage()
 
 259             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 262         logger.debug(Prefix + "preRequestSend2NSMF Exit")
 
 266     def processNSMFResponse = { DelegateExecution execution ->
 
 267         logger.debug(Prefix + "processNSMFResponse Start")
 
 270             def CSMF_NSMFResponseCode = execution.getVariable("CSMF_NSMFResponseCode") as Integer
 
 271             if (CSMF_NSMFResponseCode >= 200 && CSMF_NSMFResponseCode < 400) {
 
 272                 def CSMF_NSMFResponse = execution.getVariable("CSMF_NSMFResponse") as String
 
 273                 def e2eOperationId = jsonUtil.getJsonValue(CSMF_NSMFResponse, "operationId")
 
 275                 execution.setVariable("e2eOperationId", e2eOperationId)
 
 276                 execution.setVariable("ProcessNsmfSuccess", "OK")
 
 278                 execution.setVariable("ProcessNsmfSuccess", "ERROR")
 
 279                 execution.setVariable("operationStatus", "error")
 
 280                 execution.setVariable("operationContent",
 
 281                         "communication service " + execution.getVariable("operationType")
 
 282                                 + " operation error: nsmf response fail")
 
 283                 execution.setVariable("orchestrationStatus", "error")
 
 286         } catch (BpmnError e) {
 
 288         } catch (Exception ex) {
 
 289             String msg = "Exception in " + Prefix + "processOOFResponse. " + ex.getMessage()
 
 291             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 293         logger.debug(Prefix + "processNSMFResponse Exit")
 
 297     def prepareUpdateOperationStatus = { DelegateExecution execution ->
 
 298         logger.debug(Prefix + "prepareUpdateOperationStatus Start")
 
 299         // update status creating
 
 300         OperationStatus status = new OperationStatus()
 
 301         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
 
 302         status.setOperationId(execution.getVariable("operationId") as String)
 
 303         status.setOperation(execution.getVariable("operationType") as String)
 
 304         status.setResult("processing")
 
 305         status.setProgress("20")
 
 306         status.setOperationContent("communication service "+ execution.getVariable("operationType")
 
 307                 + " operation processing: waiting nsmf service create finished")
 
 308         status.setUserId(execution.getVariable("globalSubscriberId") as String)
 
 310         requestDBUtil.prepareUpdateOperationStatus(execution, status)
 
 311         logger.debug(Prefix + "prepareUpdateOperationStatus Exit")
 
 316     def prepareCallCheckProcessStatus = { DelegateExecution execution ->
 
 317         logger.debug(Prefix + "prepareCallCheckProcessStatus Start")
 
 319         def successConditions = new ArrayList<>()
 
 320         successConditions.add("finished")
 
 321         execution.setVariable("successConditions", successConditions)
 
 323         def errorConditions = new ArrayList<>()
 
 324         errorConditions.add("error")
 
 325         execution.setVariable("errorConditions", errorConditions)
 
 327         execution.setVariable("processServiceType", "communication service")
 
 329         execution.setVariable("timeOut", 3 * 60 * 60 * 1000)
 
 331         def successParamMap = new HashMap<String, Object>()
 
 332         successParamMap.put("orchestrationStatus", execution.getVariable("serviceExpectStatus"))
 
 334         execution.setVariable("successParamMap", successParamMap)
 
 336         def errorParamMap = new HashMap<String, Object>()
 
 337         errorParamMap.put("orchestrationStatus", "error")
 
 339         execution.setVariable("errorParamMap", errorParamMap)
 
 341         def timeOutParamMap = new HashMap<String, Object>()
 
 342         timeOutParamMap.put("orchestrationStatus", "error")
 
 344         execution.setVariable("timeOutParamMap", timeOutParamMap)
 
 346         execution.setVariable("initProgress", 20)
 
 347         execution.setVariable("endProgress", 90)
 
 349         logger.debug(Prefix + "prepareCallCheckProcessStatus Exit")
 
 354      * prepare update operation status to complete after NSMF process success
 
 357     def prepareCompleteStatus = { DelegateExecution execution ->
 
 359         logger.debug(Prefix + "prepareCompleteStatus Start")
 
 360         String operationType = execution.getVariable("operationType")
 
 361         OperationStatus status = new OperationStatus()
 
 362         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
 
 363         status.setOperationId(execution.getVariable("operationId") as String)
 
 364         status.setOperation(operationType)
 
 365         status.setResult(execution.getVariable("operationStatus") as String)
 
 366         status.setProgress("100")
 
 367         status.setOperationContent(execution.getVariable("operationContent") as String)
 
 368         status.setUserId(execution.getVariable("globalSubscriberId") as String)
 
 370         requestDBUtil.prepareUpdateOperationStatus(execution, status)
 
 371         logger.debug("prepareCompleteStatus end, serviceInstanceId: " + execution.getVariable("serviceInstanceId")
 
 372                 + ", operationId: " + execution.getVariable("operationId"))
 
 374         logger.debug(Prefix + "prepareCompleteStatus Exit")
 
 379      * update NSMF complete status to AAI when the NSMF process finished
 
 382     def updateFinishStatusInAAI = { DelegateExecution execution ->
 
 383         logger.debug(Prefix + "updateFinishStatusInAAI Start")
 
 387             String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 388             String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
 
 389             String globalSubscriberId = execution.getVariable("globalSubscriberId")
 
 390             String orchestrationStatus = execution.getVariable("orchestrationStatus")
 
 392             ServiceInstance csi = new ServiceInstance()
 
 393             csi.setOrchestrationStatus(orchestrationStatus)
 
 394             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
 
 395                     globalSubscriberId, subscriptionServiceType, serviceInstanceId)
 
 396             client.update(uri, csi)
 
 398         } catch (BpmnError e) {
 
 400         } catch (Exception ex) {
 
 401             msg = "Exception in complete communication service " + ex.getMessage()
 
 403             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 405         logger.debug(Prefix + "updateFinishStatusInAAI Exit")
 
 409     public sendSyncError = { DelegateExecution execution ->
 
 410         logger.debug("sendSyncError Start")
 
 413             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
 
 414                 WorkflowException wfe = execution.getVariable("WorkflowException") as WorkflowException
 
 415                 errorMessage = wfe.getErrorMessage()
 
 417                 errorMessage = "Sending Sync Error."
 
 420             String buildWorkflowException =
 
 421                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
 
 422                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
 
 423                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
 
 424                                    </aetgt:WorkflowException>"""
 
 426             logger.debug(buildWorkflowException)
 
 427             sendWorkflowResponse(execution, 500, buildWorkflowException)
 
 429         } catch (Exception ex) {
 
 430             logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
 
 432         logger.debug(Prefix + "sendSyncError Exit")