2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. 
 
   7  * ================================================================================
 
   8  * Modifications Copyright (c) 2019 Samsung
 
   9  * ================================================================================
 
  10  * Licensed under the Apache License, Version 2.0 (the "License")
 
  11  * you may not use this file except in compliance with the License.
 
  12  * You may obtain a copy of the License at
 
  14  *      http://www.apache.org/licenses/LICENSE-2.0
 
  16  * Unless required by applicable law or agreed to in writing, software
 
  17  * distributed under the License is distributed on an "AS IS" BASIS,
 
  18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  19  * See the License for the specific language governing permissions and
 
  20  * limitations under the License.
 
  21  * ============LICENSE_END=========================================================
 
  24 package org.onap.so.bpmn.infrastructure.scripts
 
  26 import static org.apache.commons.lang3.StringUtils.*
 
  27 import org.camunda.bpm.engine.delegate.BpmnError
 
  28 import org.camunda.bpm.engine.delegate.DelegateExecution
 
  29 import org.onap.aai.domain.yang.ServiceInstance
 
  30 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
 
  31 import org.onap.so.bpmn.common.scripts.ExceptionUtil
 
  32 import org.onap.so.bpmn.common.scripts.MsoUtils
 
  33 import org.onap.so.bpmn.core.UrnPropertiesReader
 
  34 import org.onap.so.bpmn.core.WorkflowException
 
  35 import org.onap.so.bpmn.core.domain.ServiceDecomposition
 
  36 import org.onap.so.bpmn.core.domain.VnfResource
 
  37 import org.onap.so.bpmn.core.json.JsonUtils
 
  38 import org.onap.so.client.aai.AAIObjectType
 
  39 import org.onap.so.client.aai.AAIResourcesClient
 
  40 import org.onap.so.client.aai.entities.uri.AAIResourceUri
 
  41 import org.onap.so.client.aai.entities.uri.AAIUriFactory
 
  42 import org.onap.logging.filter.base.ErrorCode
 
  43 import org.onap.so.logger.LoggingAnchor
 
  44 import org.onap.so.logger.MessageEnum
 
  45 import org.slf4j.Logger
 
  46 import org.slf4j.LoggerFactory
 
  47 import org.springframework.web.util.UriUtils
 
  51  * This groovy class supports the <class>CreateServiceInstance.bpmn</class> process.
 
  52  * AlaCarte flow for 1702 ServiceInstance Create
 
  55 public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor {
 
  56         String Prefix="CRESI_"
 
  57         ExceptionUtil exceptionUtil = new ExceptionUtil()
 
  58         JsonUtils jsonUtil = new JsonUtils()
 
  59     private static final Logger logger = LoggerFactory.getLogger( CreateCustomE2EServiceInstance.class)
 
  62         public void preProcessRequest (DelegateExecution execution) {
 
  63                 logger.trace("start preProcessRequest")
 
  64                 execution.setVariable("prefix",Prefix)
 
  68                         String siRequest = execution.getVariable("bpmnRequest")
 
  69                         logger.debug(siRequest)
 
  71                         String requestId = execution.getVariable("mso-request-id")
 
  72                         execution.setVariable("msoRequestId", requestId)
 
  73                         logger.debug("Input Request:" + siRequest + " reqId:" + requestId)
 
  75                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
  76                         if (isBlank(serviceInstanceId)) {
 
  77                                 serviceInstanceId = UUID.randomUUID().toString()
 
  79                         logger.debug("Generated new Service Instance:" + serviceInstanceId)
 
  80                         serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8")
 
  81                         execution.setVariable("serviceInstanceId", serviceInstanceId)
 
  84                         String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId")
 
  85                         if (isBlank(globalSubscriberId)) {
 
  86                                 msg = "Input globalSubscriberId' is null"
 
  87                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
 
  89                                 execution.setVariable("globalSubscriberId", globalSubscriberId)
 
  93                         execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source"))
 
  94                         execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName"))
 
  95                         execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback"))
 
  96                         String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
 
  97                         if (isBlank(productFamilyId))
 
  99                                 msg = "Input productFamilyId is null"
 
 101                                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
 
 103                                 execution.setVariable("productFamilyId", productFamilyId)
 
 107                         String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
 
 108                         if (isBlank(serviceModelInfo)) {
 
 109                                 msg = "Input serviceModelInfo is null"
 
 111                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
 
 114                                 execution.setVariable("serviceModelInfo", serviceModelInfo)
 
 117                         logger.debug("modelInfo: " + serviceModelInfo)
 
 120                         String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType")
 
 121                         if (isBlank(subscriptionServiceType)) {
 
 122                                 msg = "Input subscriptionServiceType is null"
 
 124                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
 
 126                                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
 
 131                          * Extracting User Parameters from incoming Request and converting into a Map
 
 133                         def jsonSlurper = new JsonSlurper()
 
 134                         def jsonOutput = new JsonOutput()
 
 136                         Map reqMap = jsonSlurper.parseText(siRequest)
 
 139                         def userParamsList = reqMap.requestDetails?.requestParameters?.userParams
 
 141                         Map<String, String> inputMap = [:]
 
 142                         if (userParamsList) {
 
 143                                 for (def i=0; i<userParamsList.size(); i++) {
 
 144                                         def userParams1 = userParamsList.get(i)
 
 145                                         userParams1.each { param -> inputMap.put(param.key, param.value)}
 
 149                         logger.debug("User Input Parameters map: " + inputMap.toString())
 
 150                         execution.setVariable("serviceInputParams", inputMap)
 
 151                         execution.setVariable("uuiRequest", inputMap.get("UUIRequest"))
 
 154                         //execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams"))
 
 155                         //execution.setVariable("failExists", true)
 
 156                 } catch (BpmnError e) {
 
 158                 } catch (Exception ex){
 
 159                         msg = "Exception in preProcessRequest " + ex.getMessage()
 
 161                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 163                 logger.trace("finished preProcessRequest")
 
 166         public void sendSyncResponse (DelegateExecution execution) {
 
 167                 logger.trace("start sendSyncResponse")
 
 169                         String operationId = execution.getVariable("operationId")
 
 170                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 171                         // RESTResponse for API Handler (APIH) Reply Task
 
 172                         String createServiceRestRequest = """{"service":{"serviceId":"${serviceInstanceId}","operationId":"${operationId}"}}""".trim()
 
 173                         logger.debug(" sendSyncResponse to APIH:" + "\n" + createServiceRestRequest)
 
 174                         sendWorkflowResponse(execution, 202, createServiceRestRequest)
 
 175                         execution.setVariable("sentSyncResponse", true)
 
 176                 } catch (Exception ex) {
 
 177                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
 
 179                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 181                 logger.trace("finished sendSyncResponse")
 
 185         public void sendSyncError (DelegateExecution execution) {
 
 186                 logger.trace("start sendSyncError")
 
 188                         String errorMessage = ""
 
 189                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
 
 190                                 WorkflowException wfe = execution.getVariable("WorkflowException")
 
 191                                 errorMessage = wfe.getErrorMessage()
 
 193                                 errorMessage = "Sending Sync Error."
 
 196                         String buildworkflowException =
 
 197                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
 
 198                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
 
 199                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
 
 200                                    </aetgt:WorkflowException>"""
 
 202                         logger.debug(buildworkflowException)
 
 203                         sendWorkflowResponse(execution, 500, buildworkflowException)
 
 205                 } catch (Exception ex) {
 
 206                         logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
 
 208                 logger.trace("finished sendSyncError")
 
 211         public void prepareCompletionRequest (DelegateExecution execution) {
 
 212                 logger.trace("start prepareCompletionRequest")
 
 214                         String requestId = execution.getVariable("msoRequestId")
 
 215                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 216                         String source = execution.getVariable("source")
 
 218                         String msoCompletionRequest =
 
 219                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
 
 220                                                                 xmlns:ns="http://org.onap/so/request/types/v1">
 
 221                                                 <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
 
 222                                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
 
 223                                                         <action>CREATE</action>
 
 224                                                         <source>${MsoUtils.xmlEscape(source)}</source>
 
 226                                                 <status-message>Service Instance was created successfully.</status-message>
 
 227                                                 <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
 
 228                                                 <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name>
 
 229                                         </aetgt:MsoCompletionRequest>"""
 
 232                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
 
 234                         execution.setVariable("completionRequest", xmlMsoCompletionRequest)
 
 235                         logger.debug("Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
 
 237                 } catch (Exception ex) {
 
 238                         String msg = " Exception in prepareCompletion:" + ex.getMessage()
 
 240                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 242                 logger.trace("finished prepareCompletionRequest")
 
 245         public void prepareFalloutRequest(DelegateExecution execution){
 
 246                 logger.trace("start prepareFalloutRequest")
 
 248                         WorkflowException wfex = execution.getVariable("WorkflowException")
 
 249                         logger.debug("Input Workflow Exception: " + wfex.toString())
 
 250                         String requestId = execution.getVariable("msoRequestId")
 
 251                         String source = execution.getVariable("source")
 
 253                                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
 
 254                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
 
 255                                         <action>CREATE</action>
 
 256                                         <source>${MsoUtils.xmlEscape(source)}</source>
 
 259                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
 
 260                         execution.setVariable("falloutRequest", falloutRequest)
 
 261                 } catch (Exception ex) {
 
 262                         logger.debug("Exception prepareFalloutRequest:" + ex.getMessage())
 
 263                         String errorException = "  Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
 
 264                         String requestId = execution.getVariable("msoRequestId")
 
 265                         String falloutRequest =
 
 266                                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
 
 267                                                                      xmlns:ns="http://org.onap/so/request/types/v1"
 
 268                                                                      xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
 
 269                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
 
 270                                               <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
 
 271                                               <action>CREATE</action>
 
 274                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
 
 275                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage>
 
 276                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
 
 277                                                 </aetgt:WorkflowException>
 
 278                                         </aetgt:FalloutHandlerRequest>"""
 
 280                         execution.setVariable("falloutRequest", falloutRequest)
 
 282                 logger.trace("finished prepareFalloutRequest")
 
 286          * Init the service Operation Status
 
 288         public void prepareInitServiceOperationStatus(DelegateExecution execution){
 
 289                 logger.trace("start prepareInitServiceOperationStatus")
 
 291             String serviceId = execution.getVariable("serviceInstanceId")
 
 292             String operationId = UUID.randomUUID().toString()
 
 293             String operationType = "CREATE"
 
 295             String result = "processing"
 
 296             String progress = "0"
 
 298             String operationContent = "Prepare service creation"
 
 299             logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId)
 
 300             serviceId = UriUtils.encode(serviceId,"UTF-8")
 
 301             execution.setVariable("serviceInstanceId", serviceId)
 
 302             execution.setVariable("operationId", operationId)
 
 303             execution.setVariable("operationType", operationType)
 
 305             def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint",execution)
 
 306             execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
 
 307             logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
 
 310                 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
 
 311                         xmlns:ns="http://org.onap.so/requestsdb">
 
 314                             <ns:initServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
 
 315                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
 
 316                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
 
 317                             <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
 
 318                             <userId>${MsoUtils.xmlEscape(userId)}</userId>
 
 319                             <result>${MsoUtils.xmlEscape(result)}</result>
 
 320                             <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent>
 
 321                             <progress>${MsoUtils.xmlEscape(progress)}</progress>
 
 322                             <reason>${MsoUtils.xmlEscape(reason)}</reason>
 
 323                         </ns:initServiceOperationStatus>
 
 325                 </soapenv:Envelope>"""
 
 327             payload = utils.formatXml(payload)
 
 328             execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
 
 329             logger.debug("Outgoing updateServiceOperStatusRequest: \n" + payload)
 
 330             logger.debug("CreateVfModuleInfra Outgoing updateServiceOperStatusRequest Request: " + payload)
 
 333                         logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
 
 334                                         "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN",
 
 335                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e)
 
 336             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage())
 
 338                 logger.trace("finished prepareInitServiceOperationStatus")
 
 341         public void updateAAIOrchStatus (DelegateExecution execution){
 
 342                 logger.debug(" ***** start updateAAIOrchStatus ***** ")
 
 344                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 345                 logger.debug("serviceInstanceId: "+serviceInstanceId)
 
 346                 ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
 
 349                         ServiceInstance si = execution.getVariable("serviceInstanceData")
 
 350                         boolean allActive = true
 
 351                         for (VnfResource resource : serviceDecomposition.vnfResources) {
 
 352                                 logger.debug("resource.modelInfo.getModelName: " + resource.modelInfo.getModelName() +" | resource.getOrchestrationStatus: "+resource.getOrchestrationStatus())
 
 353                                 if (resource.getOrchestrationStatus() != "Active") {
 
 359                                 si.setOrchestrationStatus("Assigned")
 
 361                                 si.setOrchestrationStatus("Pending")
 
 363                         AAIResourcesClient client = new AAIResourcesClient()
 
 364                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)
 
 365                         client.update(uri, si)
 
 366                 } catch (BpmnError e) {
 
 368                 } catch (Exception ex) {
 
 369                         msg = "Exception in org.onap.so.bpmn.common.scripts.CompleteMsoProcess.updateAAIOrchStatus " + ex.getMessage()
 
 371                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 374                 logger.debug(" ***** end updateAAIOrchStatus ***** ")