2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * ================================================================================
 
   7  * Modifications Copyright (c) 2019 Samsung
 
   8  * ================================================================================
 
   9  * Licensed under the Apache License, Version 2.0 (the "License");
 
  10  * you may not use this file except in compliance with the License.
 
  11  * You may obtain a copy of the License at
 
  13  *      http://www.apache.org/licenses/LICENSE-2.0
 
  15  * Unless required by applicable law or agreed to in writing, software
 
  16  * distributed under the License is distributed on an "AS IS" BASIS,
 
  17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  18  * See the License for the specific language governing permissions and
 
  19  * limitations under the License.
 
  20  * ============LICENSE_END=========================================================
 
  22 package org.onap.so.bpmn.vcpe.scripts
 
  24 import javax.ws.rs.NotFoundException
 
  25 import org.camunda.bpm.engine.delegate.BpmnError
 
  26 import org.camunda.bpm.engine.delegate.DelegateExecution
 
  27 import org.onap.aaiclient.client.aai.AAIObjectType
 
  28 import org.onap.aaiclient.client.aai.AAIResourcesClient
 
  29 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
 
  30 import org.onap.aaiclient.client.aai.entities.Relationships
 
  31 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
 
  32 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
 
  33 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
 
  34 import org.onap.logging.filter.base.ErrorCode
 
  35 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
 
  36 import org.onap.so.bpmn.common.scripts.ExceptionUtil
 
  37 import org.onap.so.bpmn.common.scripts.MsoUtils
 
  38 import org.onap.so.bpmn.common.scripts.NetworkUtils
 
  39 import org.onap.so.bpmn.common.scripts.VidUtils
 
  40 import org.onap.so.bpmn.core.WorkflowException
 
  41 import org.onap.so.bpmn.core.json.JsonUtils
 
  42 import org.onap.so.logger.LoggingAnchor
 
  43 import org.onap.so.logger.MessageEnum
 
  44 import org.slf4j.Logger
 
  45 import org.slf4j.LoggerFactory
 
  48  * This groovy class supports the <class>DeleteVcpeResCustService.bpmn</class> process.
 
  53 public class DeleteVcpeResCustService extends AbstractServiceTaskProcessor {
 
  54         private static final Logger logger = LoggerFactory.getLogger(DeleteVcpeResCustService.class);
 
  56         private static final String DebugFlag = "isDebugLogEnabled"
 
  58         String Prefix = "DVRCS_"
 
  59         ExceptionUtil exceptionUtil = new ExceptionUtil()
 
  60         JsonUtils jsonUtil = new JsonUtils()
 
  61         VidUtils vidUtils = new VidUtils()
 
  62         NetworkUtils networkUtils = new NetworkUtils()
 
  65          * This method is executed during the preProcessRequest task of the <class>DeleteVcpeResCustService.bpmn</class> process.
 
  68         public InitializeProcessVariables(DelegateExecution execution){
 
  69                 /* Initialize all the process variables in this block */
 
  71                 execution.setVariable("DeleteVcpeResCustServiceRequest", "")
 
  72                 execution.setVariable("msoRequestId", "")
 
  73                 execution.setVariable(Prefix+"vnfsDeletedCount", 0)
 
  74                 execution.setVariable(Prefix+"vnfsCount", 0)
 
  77         // **************************************************
 
  78         //     Pre or Prepare Request Section
 
  79         // **************************************************
 
  81          * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
 
  84         public void preProcessRequest (DelegateExecution execution) {
 
  85                 def isDebugEnabled=execution.getVariable(DebugFlag)
 
  86                 execution.setVariable("prefix",Prefix)
 
  88                 logger.trace("Inside preProcessRequest DeleteVcpeResCustService Request ")
 
  91                         // initialize flow variables
 
  92                         InitializeProcessVariables(execution)
 
  94                         // check for incoming json message/input
 
  95                         String DeleteVcpeResCustServiceRequest = execution.getVariable("bpmnRequest")
 
  96                         logger.debug(DeleteVcpeResCustServiceRequest)
 
  97                         execution.setVariable("DeleteVcpeResCustServiceRequest", DeleteVcpeResCustServiceRequest);
 
  98                         println 'DeleteVcpeResCustServiceRequest - ' + DeleteVcpeResCustServiceRequest
 
 101                         String requestId = execution.getVariable("mso-request-id")
 
 102                         execution.setVariable("msoRequestId", requestId)
 
 104                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 105                         if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) {
 
 106                                 String dataErrorMessage = " Element 'serviceInstanceId' is missing. "
 
 107                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
 
 110                         String requestAction = execution.getVariable("requestAction")
 
 111                         execution.setVariable("requestAction", requestAction)
 
 113                         String source = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestInfo.source")
 
 114                         if ((source == null) || (source.isEmpty())) {
 
 117                         execution.setVariable("source", source)
 
 119                         // extract globalSubscriberId
 
 120                         String globalSubscriberId = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.subscriberInfo.globalSubscriberId")
 
 122                         // global-customer-id is optional on Delete
 
 124                         execution.setVariable("globalSubscriberId", globalSubscriberId)
 
 125                         execution.setVariable("globalCustomerId", globalSubscriberId)
 
 127                         String suppressRollback = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestInfo.suppressRollback")
 
 128                         execution.setVariable("disableRollback", suppressRollback)
 
 129                         logger.debug("Incoming Suppress/Disable Rollback is: " + suppressRollback)
 
 131                         String productFamilyId = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestInfo.productFamilyId")
 
 132                         execution.setVariable("productFamilyId", productFamilyId)
 
 133                         logger.debug("Incoming productFamilyId is: " + productFamilyId)
 
 135                         // extract subscriptionServiceType
 
 136                         String subscriptionServiceType = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestParameters.subscriptionServiceType")
 
 137                         execution.setVariable("subscriptionServiceType", subscriptionServiceType)
 
 138                         logger.debug("Incoming subscriptionServiceType is: " + subscriptionServiceType)
 
 140                         // extract cloud configuration
 
 141                         String cloudConfiguration = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.cloudConfiguration")
 
 142                         execution.setVariable("cloudConfiguration", cloudConfiguration)
 
 143                         logger.debug("cloudConfiguration: "+ cloudConfiguration)
 
 144                         String lcpCloudRegionId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId")
 
 145                         execution.setVariable("lcpCloudRegionId", lcpCloudRegionId)
 
 146                         logger.debug("lcpCloudRegionId: "+ lcpCloudRegionId)
 
 147                         String cloudOwner = jsonUtil.getJsonValue(cloudConfiguration, "cloudOwner")
 
 148                         execution.setVariable("cloudOwner", cloudOwner)
 
 149                         logger.debug("cloudOwner: "+ cloudOwner)
 
 150                         String tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId")
 
 151                         execution.setVariable("tenantId", tenantId)
 
 152                         logger.debug("tenantId: "+ tenantId)
 
 154                         String sdncVersion = "1707"
 
 155                         execution.setVariable("sdncVersion", sdncVersion)
 
 156                         logger.debug("sdncVersion: "+ sdncVersion)
 
 158                         //For Completion Handler & Fallout Handler
 
 160                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
 
 161                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
 
 162                                         <action>DELETE</action>
 
 163                                         <source>${MsoUtils.xmlEscape(source)}</source>
 
 166                         execution.setVariable(Prefix+"requestInfo", requestInfo)
 
 168                         logger.trace("Completed preProcessRequest DeleteVcpeResCustServiceRequest Request ")
 
 170                 } catch (BpmnError e) {
 
 172                 } catch (Exception ex){
 
 173                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage()
 
 174                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
 
 178         public void sendSyncResponse(DelegateExecution execution) {
 
 179                 def isDebugEnabled=execution.getVariable(DebugFlag)
 
 181                 logger.trace("Inside sendSyncResponse of DeleteVcpeResCustService ")
 
 184                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 185                         String requestId = execution.getVariable("mso-request-id")
 
 187                         // RESTResponse (for API Handler (APIH) Reply Task)
 
 188                         String syncResponse ="""{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
 
 190                         logger.debug(" sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
 
 191                         sendWorkflowResponse(execution, 202, syncResponse)
 
 192                 } catch (Exception ex) {
 
 193                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage()
 
 194                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
 
 199          * Gets the service instance and its related resources from aai
 
 203         public void getServiceInstance(DelegateExecution execution) {
 
 205                         String serviceInstanceId = execution.getVariable('serviceInstanceId')
 
 207                         AAIResourcesClient resourceClient = new AAIResourcesClient()
 
 208                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)
 
 210                         if(resourceClient.exists(uri)){
 
 211                                 AAIResultWrapper wrapper = resourceClient.get(uri, NotFoundException.class)
 
 212                                 Optional<Relationships> relationships = wrapper.getRelationships()
 
 214                                 def (TXC_found, TXC_id) = new Tuple(false, null)
 
 215                                 def (BRG_found, BRG_id) = new Tuple(false, null)
 
 216                                 List relatedVnfIdList = []
 
 218                                 if(relationships.isPresent()){
 
 220                                         List<AAIResourceUri> vnfUris = relationships.get().getRelatedAAIUris(AAIObjectType.GENERIC_VNF)
 
 221                                         for(AAIResourceUri u:vnfUris){
 
 222                                                 Map<String, String> keys = u.getURIKeys()
 
 223                                                 String vnfId = keys.get(AAIFluentTypeBuilder.Types.GENERIC_VNF.getUriParams().vnfId)
 
 224                                                 relatedVnfIdList.add(vnfId)
 
 226                                         List<AAIResourceUri> arUris = relationships.get().getRelatedAAIUris(AAIObjectType.ALLOTTED_RESOURCE)
 
 227                                         for(AAIResourceUri u:arUris){
 
 228                                                 String ar = resourceClient.get(u).getJson()
 
 230                                                 def type = jsonUtil.getJsonValue(ar, "type")
 
 231                                                 def id = jsonUtil.getJsonValue(ar, "id")
 
 233                                                 if(type == "TunnelXConn" || type == "Tunnel XConn") {
 
 234                                                         logger.debug("TunnelXConn AR found")
 
 238                                                 }else if(type == "BRG") {
 
 239                                                         logger.debug("BRG AR found")
 
 244                                                 execution.setVariable(Prefix+"TunnelXConn", TXC_found)
 
 245                                                 execution.setVariable("TXC_allottedResourceId", TXC_id)
 
 246                                                 logger.debug("TXC_allottedResourceId: " + TXC_id)
 
 248                                                 execution.setVariable(Prefix+"BRG", BRG_found)
 
 249                                                 execution.setVariable("BRG_allottedResourceId", BRG_id)
 
 250                                                 logger.debug("BRG_allottedResourceId: " + BRG_id)
 
 255                                 execution.setVariable(Prefix+"vnfsCount", relatedVnfIdList.size())
 
 256                                 if(relatedVnfIdList.size() > 0) {
 
 257                                         execution.setVariable(Prefix+"relatedVnfIdList", relatedVnfIdList)
 
 261                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
 
 264                 }catch(BpmnError e) {
 
 266                 }catch(NotFoundException e) {
 
 267                         logger.debug("Service Instance does not exist AAI")
 
 268                         exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Service Instance was not found in aai")
 
 269                 }catch(Exception ex) {
 
 270                         String msg = "Internal Error in getServiceInstance: " + ex.getMessage()
 
 272                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 277         // *******************************
 
 279         // *******************************
 
 280         public void prepareVnfAndModulesDelete (DelegateExecution execution) {
 
 281                 def isDebugEnabled=execution.getVariable(DebugFlag)
 
 282                 logger.trace("Inside prepareVnfAndModulesDelete of DeleteVcpeResCustService ")
 
 285                         List vnfList = execution.getVariable(Prefix+"relatedVnfIdList")
 
 286                         int vnfsDeletedCount = execution.getVariable(Prefix+"vnfsDeletedCount")
 
 287                         String vnfModelInfoString = ""
 
 289                         if (vnfList.size() > 0 ) {
 
 290                                 vnfId = vnfList.get(vnfsDeletedCount.intValue())
 
 293                         execution.setVariable("vnfId", vnfId)
 
 294                         logger.debug("need to delete vnfId:" + vnfId)
 
 296                         logger.trace("Completed prepareVnfAndModulesDelete of DeleteVcpeResCustService ")
 
 297                 } catch (Exception ex) {
 
 298                         // try error in method block
 
 299                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected Error from method prepareVnfAndModulesDelete() - " + ex.getMessage()
 
 300                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
 
 304         // *******************************
 
 305         //     Validate Vnf request Section -> increment count
 
 306         // *******************************
 
 307         public void validateVnfDelete (DelegateExecution execution) {
 
 308                 def isDebugEnabled=execution.getVariable(DebugFlag)
 
 309                 logger.trace("Inside validateVnfDelete of DeleteVcpeResCustService ")
 
 312                         int vnfsDeletedCount = execution.getVariable(Prefix+"vnfsDeletedCount")
 
 315                         execution.setVariable(Prefix+"vnfsDeletedCount", vnfsDeletedCount)
 
 317                         logger.debug(" ***** Completed validateVnfDelete of DeleteVcpeResCustService ***** "+" vnf # "+vnfsDeletedCount)
 
 318                 } catch (Exception ex) {
 
 319                         // try error in method block
 
 320                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected Error from method validateVnfDelete() - " + ex.getMessage()
 
 321                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
 
 326         // *****************************************
 
 327         //     Prepare Completion request Section
 
 328         // *****************************************
 
 329         public void postProcessResponse (DelegateExecution execution) {
 
 330                 def isDebugEnabled=execution.getVariable(DebugFlag)
 
 331                 logger.trace("Inside postProcessResponse of DeleteVcpeResCustService ")
 
 334                         String source = execution.getVariable("source")
 
 335                         String requestId = execution.getVariable("msoRequestId")
 
 337                         String msoCompletionRequest =
 
 338                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
 
 339                                                                         xmlns:ns="http://org.onap/so/request/types/v1">
 
 340                                                         <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
 
 341                                                                 <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
 
 342                                                                 <action>DELETE</action>
 
 343                                                                 <source>${MsoUtils.xmlEscape(source)}</source>
 
 345                                                         <aetgt:status-message>vCPE Res Cust Service Instance has been deleted successfully.</aetgt:status-message>
 
 346                                                            <aetgt:mso-bpel-name>BPMN Service Instance macro action: DELETE</aetgt:mso-bpel-name>
 
 347                                                 </aetgt:MsoCompletionRequest>"""
 
 350                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
 
 352                         logger.debug(xmlMsoCompletionRequest)
 
 353                         execution.setVariable(Prefix+"Success", true)
 
 354                         execution.setVariable(Prefix+"CompleteMsoProcessRequest", xmlMsoCompletionRequest)
 
 355                         logger.debug(" SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
 
 356                 } catch (BpmnError e) {
 
 359                 } catch (Exception ex) {
 
 360                         // try error in method block
 
 361                         String exceptionMessage = "Bpmn error encountered in DeleteServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage()
 
 362                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
 
 366         public void prepareFalloutRequest(DelegateExecution execution){
 
 367                 def isDebugEnabled=execution.getVariable(DebugFlag)
 
 368                 logger.trace("STARTED DeleteVcpeResCustService prepareFalloutRequest Process ")
 
 371                         WorkflowException wfex = execution.getVariable("WorkflowException")
 
 372                         logger.debug(" Incoming Workflow Exception: " + wfex.toString())
 
 373                         String requestInfo = execution.getVariable(Prefix+"requestInfo")
 
 374                         logger.debug(" Incoming Request Info: " + requestInfo)
 
 376                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
 
 378                         execution.setVariable(Prefix+"falloutRequest", falloutRequest)
 
 379                 } catch (Exception ex) {
 
 380                         logger.debug("Error Occured in DeleteVcpeResCustService prepareFalloutRequest Process " + ex.getMessage())
 
 381                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteVcpeResCustService prepareFalloutRequest Process")
 
 383                 logger.trace("COMPLETED DeleteVcpeResCustService prepareFalloutRequest Process ")
 
 387         public void sendSyncError (DelegateExecution execution) {
 
 388                 def isDebugEnabled=execution.getVariable(DebugFlag)
 
 389                 logger.trace("Inside sendSyncError() of DeleteVcpeResCustService ")
 
 392                         String errorMessage = ""
 
 393                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
 
 394                                 WorkflowException wfe = execution.getVariable("WorkflowException")
 
 395                                 errorMessage = wfe.getErrorMessage()
 
 397                                 errorMessage = "Sending Sync Error."
 
 400                         String buildworkflowException =
 
 401                                 """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
 
 402                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
 
 403                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
 
 404                                    </aetgt:WorkflowException>"""
 
 406                         logger.debug(buildworkflowException)
 
 407                         sendWorkflowResponse(execution, 500, buildworkflowException)
 
 408                 } catch (Exception ex) {
 
 409                         logger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
 
 413         public void processJavaException(DelegateExecution execution){
 
 414                 def isDebugEnabled=execution.getVariable(DebugFlag)
 
 415                 execution.setVariable("prefix",Prefix)
 
 417                         logger.debug("Caught a Java Exception")
 
 418                         logger.debug("Started processJavaException Method")
 
 419                         logger.debug("Variables List: " + execution.getVariables())
 
 420                         execution.setVariable(Prefix+"unexpectedError", "Caught a Java Lang Exception")  // Adding this line temporarily until this flows error handling gets updated
 
 421                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception")
 
 423                         logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
 
 424                                         "Rethrowing MSOWorkflowException", "BPMN",
 
 425                                         ErrorCode.UnknownError.getValue());
 
 428                         logger.debug("Caught Exception during processJavaException Method: " + e)
 
 429                         execution.setVariable(Prefix+"unexpectedError", "Exception in processJavaException method")  // Adding this line temporarily until this flows error handling gets updated
 
 430                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method")
 
 432                 logger.debug("Completed processJavaException Method")