Removed MsoLogger class
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / vcpe / scripts / CreateVcpeResCustService.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
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=========================================================
21  */
22 package org.onap.so.bpmn.vcpe.scripts
23
24 import org.onap.so.logger.ErrorCode;
25
26 import static org.apache.commons.lang3.StringUtils.*
27
28 import org.camunda.bpm.engine.delegate.BpmnError
29 import org.camunda.bpm.engine.delegate.DelegateExecution
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.common.scripts.VidUtils
34 import org.onap.so.bpmn.core.WorkflowException
35 import org.onap.so.bpmn.core.domain.*
36 import org.onap.so.bpmn.core.json.JsonUtils
37 import org.onap.so.bpmn.core.UrnPropertiesReader
38 import org.onap.so.logger.MessageEnum
39 import org.springframework.web.util.UriUtils
40 import org.slf4j.Logger
41 import org.slf4j.LoggerFactory
42
43 import groovy.json.*
44
45
46
47 /**
48  * This groovy class supports the <class>CreateVcpeResCustService.bpmn</class> process.
49  *
50  * @author ek1439
51  *
52  */
53 public class CreateVcpeResCustService extends AbstractServiceTaskProcessor {
54     private static final Logger logger = LoggerFactory.getLogger(CreateVcpeResCustService.class);
55
56     private static final String DebugFlag = "isDebugLogEnabled"
57
58     String Prefix = "CVRCS_"
59     ExceptionUtil exceptionUtil = new ExceptionUtil()
60     JsonUtils jsonUtil = new JsonUtils()
61     VidUtils vidUtils = new VidUtils()
62
63     /**
64      * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
65      * @param execution
66      */
67     private InitializeProcessVariables(DelegateExecution execution) {
68         /* Initialize all the process variables in this block */
69
70         execution.setVariable("createVcpeServiceRequest", "")
71         execution.setVariable("globalSubscriberId", "")
72         execution.setVariable("serviceInstanceName", "")
73         execution.setVariable("msoRequestId", "")
74         execution.setVariable(Prefix + "VnfsCreatedCount", 0)
75         execution.setVariable("productFamilyId", "")
76         execution.setVariable("brgWanMacAddress", "")
77         execution.setVariable("customerLocation", "")
78         execution.setVariable("homingService", "")
79         execution.setVariable("cloudOwner", "")
80         execution.setVariable("cloudRegionId", "")
81         execution.setVariable("homingModelIds", "")
82
83         //TODO
84         execution.setVariable("sdncVersion", "1707")
85     }
86
87     // **************************************************
88     //     Pre or Prepare Request Section
89     // **************************************************
90     /**
91      * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
92      * @param execution
93      */
94     public void preProcessRequest(DelegateExecution execution) {
95         def isDebugEnabled = execution.getVariable(DebugFlag)
96         execution.setVariable("prefix", Prefix)
97
98         logger.trace("Inside preProcessRequest CreateVcpeResCustService Request ")
99
100         try {
101             // initialize flow variables
102             InitializeProcessVariables(execution)
103
104             //Config Inputs
105             String aaiDistDelay = UrnPropertiesReader.getVariable("aai.workflowAaiDistributionDelay", execution)
106             if (isBlank(aaiDistDelay)) {
107                 String msg = "workflowAaiDistributionDelay is null"
108                 logger.debug(msg)
109                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
110             }
111             execution.setVariable("aaiDistDelay", aaiDistDelay)
112             logger.debug("AAI distribution delay: " + aaiDistDelay)
113
114             // check for incoming json message/input
115             String createVcpeServiceRequest = execution.getVariable("bpmnRequest")
116             logger.debug(createVcpeServiceRequest)
117             execution.setVariable("createVcpeServiceRequest", createVcpeServiceRequest);
118             println 'createVcpeServiceRequest - ' + createVcpeServiceRequest
119
120             // extract requestId
121             String requestId = execution.getVariable("mso-request-id")
122             execution.setVariable("msoRequestId", requestId)
123
124             String serviceInstanceId = execution.getVariable("serviceInstanceId")
125
126             if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) {
127                 serviceInstanceId = UUID.randomUUID().toString()
128                 logger.debug(" Generated new Service Instance: " + serviceInstanceId)
129             } else {
130                 logger.debug("Using provided Service Instance ID: " + serviceInstanceId)
131             }
132
133             serviceInstanceId = UriUtils.encode(serviceInstanceId, "UTF-8")
134             execution.setVariable("serviceInstanceId", serviceInstanceId)
135             logger.debug("Incoming serviceInstanceId is: " + serviceInstanceId)
136
137             String serviceInstanceName = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.instanceName")
138             execution.setVariable("serviceInstanceName", serviceInstanceName)
139             logger.debug("Incoming serviceInstanceName is: " + serviceInstanceName)
140
141             String requestAction = execution.getVariable("requestAction")
142             execution.setVariable("requestAction", requestAction)
143
144             setBasicDBAuthHeader(execution, isDebugEnabled)
145
146             String source = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.source")
147             if ((source == null) || (source.isEmpty())) {
148                 source = "VID"
149             }
150             execution.setVariable("source", source)
151
152             // extract globalSubscriberId
153             String globalSubscriberId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.subscriberInfo.globalSubscriberId")
154
155             // verify element global-customer-id is sent from JSON input, throw exception if missing
156             if ((globalSubscriberId == null) || (globalSubscriberId.isEmpty())) {
157                 String dataErrorMessage = " Element 'globalSubscriberId' is missing. "
158                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
159
160             } else {
161                 execution.setVariable("globalSubscriberId", globalSubscriberId)
162                 execution.setVariable("globalCustomerId", globalSubscriberId)
163             }
164
165             // extract subscriptionServiceType
166             String subscriptionServiceType = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestParameters.subscriptionServiceType")
167             execution.setVariable("subscriptionServiceType", subscriptionServiceType)
168             logger.debug("Incoming subscriptionServiceType is: " + subscriptionServiceType)
169
170             String suppressRollback = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.suppressRollback")
171             execution.setVariable("disableRollback", suppressRollback)
172             logger.debug("Incoming Suppress/Disable Rollback is: " + suppressRollback)
173
174             String productFamilyId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.productFamilyId")
175             execution.setVariable("productFamilyId", productFamilyId)
176             logger.debug("Incoming productFamilyId is: " + productFamilyId)
177
178             String subscriberInfo = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.subscriberInfo")
179             execution.setVariable("subscriberInfo", subscriberInfo)
180             logger.debug("Incoming subscriberInfo is: " + subscriberInfo)
181
182             // extract cloud configuration - if underscore "_" is present treat as vimId else it's a cloudRegion
183             String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest,
184                     "requestDetails.cloudConfiguration.lcpCloudRegionId")
185             if (vimId.contains("_") && vimId.split("_").length == 2 ) {
186                 def cloudRegion = vimId.split("_")
187                 def cloudOwner = cloudRegion[0]
188                 def cloudRegionId = cloudRegion[1]
189                 execution.setVariable("cloudOwner", cloudOwner)
190                 logger.debug("cloudOwner: " + cloudOwner)
191                 execution.setVariable("cloudRegionId", cloudRegionId)
192                 logger.debug("cloudRegionId: " + cloudRegionId)
193             } else {
194                 logger.debug("vimId is not present - setting  cloudRegion/cloudOwner from request.")
195                 String cloudOwner = jsonUtil.getJsonValue(createVcpeServiceRequest,
196                         "requestDetails.cloudConfiguration.cloudOwner")
197                 if (!cloudOwner?.empty && cloudOwner != "")
198                 {
199                     execution.setVariable("cloudOwner", cloudOwner)
200                     logger.debug("cloudOwner: " + cloudOwner)
201                 }
202                 def cloudRegionId = vimId
203                 execution.setVariable("cloudRegionId", cloudRegionId)
204                 logger.debug("cloudRegionId: " + cloudRegionId)
205             }
206             /*
207             * Extracting User Parameters from incoming Request and converting into a Map
208             */
209             def jsonSlurper = new JsonSlurper()
210
211             Map reqMap = jsonSlurper.parseText(createVcpeServiceRequest)
212
213             //InputParams
214             def userParams = reqMap.requestDetails?.requestParameters?.userParams
215
216             Map<String, String> inputMap = [:]
217             if (userParams) {
218                 userParams.each {
219                     userParam ->
220                         if ("Customer_Location".equals(userParam?.name)) {
221                             Map<String, String> customerMap = [:]
222                             userParam.value.each {
223                                 param ->
224                                     inputMap.put(param.key, param.value)
225                                     customerMap.put(param.key, param.value)
226                                     }
227                             execution.setVariable("customerLocation", customerMap)
228                         }
229                         if ("Homing_Model_Ids".equals(userParam?.name)) {
230                             logger.debug("Homing_Model_Ids: " + userParam.value.toString() + "  ---- Type is:" +
231                                     userParam.value.getClass())
232                             def modelIdLst = []
233                             userParam.value.each {
234                                 param ->
235                                     def valueMap = [:]
236                                     param.each {
237                                         entry ->
238                                             valueMap.put(entry.key, entry.value)
239                                     }
240                                     modelIdLst.add(valueMap)
241                                     logger.debug("Param: " + param.toString() + "  ---- Type is:" +
242                                             param.getClass())
243                                     }
244                             execution.setVariable("homingModelIds", modelIdLst)
245                         }
246                         if ("BRG_WAN_MAC_Address".equals(userParam?.name)) {
247                             execution.setVariable("brgWanMacAddress", userParam.value)
248                             inputMap.put("BRG_WAN_MAC_Address", userParam.value)
249                         }
250                         if ("Homing_Solution".equals(userParam?.name)) {
251                                     execution.setVariable("homingService", userParam.value)
252                                     execution.setVariable("callHoming", true)
253                                     inputMap.put("Homing_Solution", userParam.value)
254                         }
255                         if ("Orchestrator".equalsIgnoreCase(userParam?.name)) {
256                             execution.setVariable("orchestrator", userParam.value)
257                             inputMap.put("orchestrator", userParam.value)
258                         }
259                         if ("VfModuleNames".equals(userParam?.name)) {
260                             logger.debug("VfModuleNames: " + userParam.value.toString())
261                             def vfModuleNames = [:]
262                             userParam.value.each {
263                                 entry ->
264                                     String vfModuleModelInvariantUuid = null;
265                                     String vfModuleName = null;
266                                     entry.each {
267                                         param ->
268                                             if ("VfModuleModelInvariantUuid".equals(param.key)) {
269                                                 vfModuleModelInvariantUuid = param.value;
270                                             } else if ("VfModuleName".equals(param.key)) {
271                                                 vfModuleName = param.value;
272                                             }
273                                     }
274
275                                     if (vfModuleModelInvariantUuid != null && !vfModuleModelInvariantUuid.isEmpty() && vfModuleName != null && !vfModuleName.isEmpty()) {
276                                         vfModuleNames.put(vfModuleModelInvariantUuid, vfModuleName)
277                                         logger.debug("VfModuleModelInvariantUuid: " + vfModuleModelInvariantUuid + " VfModuleName: " + vfModuleName)
278                                     }
279                             }
280                             execution.setVariable("vfModuleNames", vfModuleNames)
281                         }
282                 }
283             }
284
285             if (execution.getVariable("homingService") == "") {
286                 // Set Default Homing to OOF if not set
287                 execution.setVariable("homingService", "oof")
288             }
289
290             logger.debug("User Input Parameters map: " + userParams.toString())
291             execution.setVariable("serviceInputParams", inputMap) // DOES NOT SEEM TO BE USED
292
293             logger.debug("Incoming brgWanMacAddress is: " + execution.getVariable('brgWanMacAddress'))
294
295             //For Completion Handler & Fallout Handler
296             String requestInfo =
297                     """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
298                     <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
299                     <action>CREATE</action>
300                     <source>${MsoUtils.xmlEscape(source)}</source>
301                    </request-info>"""
302
303             execution.setVariable(Prefix + "requestInfo", requestInfo)
304
305             logger.trace("Completed preProcessRequest CreateVcpeResCustService Request ")
306
307         } catch (BpmnError e) {
308             throw e;
309
310         } catch (Exception ex) {
311             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage()
312             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
313         }
314     }
315
316     public void sendSyncResponse(DelegateExecution execution) {
317
318         logger.trace("Inside sendSyncResponse of CreateVcpeResCustService ")
319
320         try {
321             String serviceInstanceId = execution.getVariable("serviceInstanceId")
322             String requestId = execution.getVariable("mso-request-id")
323
324             // RESTResponse (for API Handler (APIH) Reply Task)
325             String syncResponse = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${
326                 requestId
327             }"}}""".trim()
328
329             logger.debug(" sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
330             sendWorkflowResponse(execution, 202, syncResponse)
331
332         } catch (Exception ex) {
333             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected from method sendSyncResponse() - " + ex.getMessage()
334             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
335         }
336     }
337
338     // *******************************
339     //
340     // *******************************
341     public void prepareDecomposeService(DelegateExecution execution) {
342
343         try {
344             logger.trace("Inside prepareDecomposeService of CreateVcpeResCustService ")
345
346             String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest")
347
348             //serviceModelInfo JSON string will be used as-is for DoCreateServiceInstance BB
349             String serviceModelInfo = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.modelInfo")
350             execution.setVariable("serviceModelInfo", serviceModelInfo)
351
352             logger.trace("Completed prepareDecomposeService of CreateVcpeResCustService ")
353         } catch (Exception ex) {
354             // try error in method block
355             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
356             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
357         }
358     }
359
360     // *******************************
361     //
362     // *******************************
363     public void prepareCreateServiceInstance(DelegateExecution execution) {
364
365         try {
366             logger.trace("Inside prepareCreateServiceInstance of CreateVcpeResCustService ")
367
368             /*
369              * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject
370              *      ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
371              *      ModelInfo modelInfo = serviceDecomposition.getModelInfo()
372              *
373              */
374             String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest")
375 //          String serviceInputParams = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestParameters")
376 //          execution.setVariable("serviceInputParams", serviceInputParams)
377
378
379             String serviceInstanceName = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.instanceName")
380             execution.setVariable("serviceInstanceName", serviceInstanceName)
381
382             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
383             execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonStringNoRootName())
384
385             logger.trace("Completed prepareCreateServiceInstance of CreateVcpeResCustService ")
386         } catch (Exception ex) {
387             // try error in method block
388             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
389             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
390         }
391     }
392
393     public void postProcessServiceInstanceCreate(DelegateExecution execution) {
394         def method = getClass().getSimpleName() + '.postProcessServiceInstanceCreate(' + 'execution=' + execution.getId() + ')'
395         logger.trace('Entered ' + method)
396
397         String requestId = execution.getVariable("mso-request-id")
398         String serviceInstanceId = execution.getVariable("serviceInstanceId")
399         String serviceInstanceName = execution.getVariable("serviceInstanceName")
400
401         try {
402
403             String payload = """
404             <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
405             <soapenv:Header/>
406             <soapenv:Body>
407             <req:updateInfraRequest>
408                 <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
409                 <lastModifiedBy>BPEL</lastModifiedBy>
410                 <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
411                 <serviceInstanceName>${MsoUtils.xmlEscape(serviceInstanceName)}</serviceInstanceName>
412             </req:updateInfraRequest>
413             </soapenv:Body>
414             </soapenv:Envelope>
415             """
416             execution.setVariable(Prefix + "setUpdateDbInstancePayload", payload)
417             logger.debug(Prefix + "setUpdateDbInstancePayload: " + payload)
418             logger.trace('Exited ' + method)
419
420         } catch (BpmnError e) {
421             throw e;
422         } catch (Exception e) {
423             logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
424                     'Caught exception in ' + method, "BPMN",
425                     ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
426             exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
427         }
428     }
429
430
431     public void processDecomposition(DelegateExecution execution) {
432
433         logger.trace("Inside processDecomposition() of CreateVcpeResCustService ")
434
435         try {
436
437             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
438
439             // VNFs
440             List<VnfResource> vnfList = serviceDecomposition.getVnfResources()
441             filterVnfs(vnfList)
442             serviceDecomposition.setVnfResources(vnfList)
443
444             execution.setVariable("vnfList", vnfList)
445             execution.setVariable("vnfListString", vnfList.toString())
446
447             String vnfModelInfoString = ""
448             if (vnfList != null && vnfList.size() > 0) {
449                 execution.setVariable(Prefix + "VNFsCount", vnfList.size())
450                 logger.debug("vnfs to create: " + vnfList.size())
451                 ModelInfo vnfModelInfo = vnfList[0].getModelInfo()
452
453                 vnfModelInfoString = vnfModelInfo.toString()
454                 String vnfModelInfoWithRoot = vnfModelInfo.toString()
455                 vnfModelInfoString = jsonUtil.getJsonValue(vnfModelInfoWithRoot, "modelInfo")
456             } else {
457                 execution.setVariable(Prefix + "VNFsCount", 0)
458                 logger.debug("no vnfs to create based upon serviceDecomposition content")
459             }
460
461             execution.setVariable("vnfModelInfo", vnfModelInfoString)
462             execution.setVariable("vnfModelInfoString", vnfModelInfoString)
463             logger.debug(" vnfModelInfoString :" + vnfModelInfoString)
464
465             logger.trace("Completed processDecomposition() of CreateVcpeResCustService ")
466         } catch (Exception ex) {
467             sendSyncError(execution)
468             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. processDecomposition() - " + ex.getMessage()
469             logger.debug(exceptionMessage)
470             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
471         }
472     }
473
474     private void filterVnfs(List<VnfResource> vnfList) {
475         if (vnfList == null) {
476             return
477         }
478
479         // remove BRG & TXC from VNF list
480
481         Iterator<VnfResource> it = vnfList.iterator()
482         while (it.hasNext()) {
483             VnfResource vr = it.next()
484
485             String role = vr.getNfRole()
486             if (role == "BRG" || role == "TunnelXConn" || role == "Tunnel XConn") {
487                 it.remove()
488             }
489         }
490     }
491
492
493     public void prepareCreateAllottedResourceTXC(DelegateExecution execution) {
494
495         try {
496             logger.trace("Inside prepareCreateAllottedResourceTXC of CreateVcpeResCustService ")
497
498             /*
499              * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject
500              *      ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
501              *      ModelInfo modelInfo = serviceDecomposition.getModelInfo()
502              *
503              */
504             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
505
506             //allottedResourceModelInfo
507             //allottedResourceRole
508             //The model Info parameters are a JSON structure as defined in the Service Instantiation API.
509             //It would be sufficient to only include the service model UUID (i.e. the modelVersionId), since this BB will query the full model from the Catalog DB.
510             List<AllottedResource> allottedResources = serviceDecomposition.getAllottedResources()
511             if (allottedResources != null) {
512                 Iterator iter = allottedResources.iterator();
513                 while (iter.hasNext()) {
514                     AllottedResource allottedResource = (AllottedResource) iter.next();
515
516                     logger.debug(" getting model info for AllottedResource # :" + allottedResource.toJsonStringNoRootName())
517                     logger.debug(" allottedResource.getAllottedResourceType() :" + allottedResource.getAllottedResourceType())
518                     if ("TunnelXConn".equalsIgnoreCase(allottedResource.getAllottedResourceType()) || "Tunnel XConn".equalsIgnoreCase(allottedResource.getAllottedResourceType())) {
519                         //set create flag to true
520                         execution.setVariable("createTXCAR", true)
521                         ModelInfo allottedResourceModelInfo = allottedResource.getModelInfo()
522                         execution.setVariable("allottedResourceModelInfoTXC", allottedResourceModelInfo.toJsonStringNoRootName())
523                         execution.setVariable("allottedResourceRoleTXC", allottedResource.getAllottedResourceRole())
524                         execution.setVariable("allottedResourceTypeTXC", allottedResource.getAllottedResourceType())
525                         //After decomposition and homing BBs, there should be an allotted resource object in the decomposition that represents the TXC,
526                         //and in its homingSolution section should be found the infraServiceInstanceId (i.e. infraServiceInstanceId in TXC Allotted Resource structure) (which the Homing BB would have populated).
527                         execution.setVariable("parentServiceInstanceIdTXC", allottedResource.getHomingSolution().getServiceInstanceId())
528                     }
529                 }
530             }
531
532             //unit test only
533             String allottedResourceId = execution.getVariable("allottedResourceId")
534             execution.setVariable("allottedResourceIdTXC", allottedResourceId)
535             logger.debug("setting allottedResourceId CreateVcpeResCustService " + allottedResourceId)
536
537             logger.trace("Completed prepareCreateAllottedResourceTXC of CreateVcpeResCustService ")
538         } catch (Exception ex) {
539             // try error in method block
540             String exceptionMessage = "Bpmn error encountered in prepareCreateAllottedResourceTXC flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
541             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
542         }
543     }
544
545     public void prepareCreateAllottedResourceBRG(DelegateExecution execution) {
546
547         try {
548             logger.trace("Inside prepareCreateAllottedResourceBRG of CreateVcpeResCustService ")
549
550             /*
551              * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject
552              *      ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
553              *      ModelInfo modelInfo = serviceDecomposition.getModelInfo()
554              *
555              */
556             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
557
558             //allottedResourceModelInfo
559             //allottedResourceRole
560             //The model Info parameters are a JSON structure as defined in the Service Instantiation API.
561             //It would be sufficient to only include the service model UUID (i.e. the modelVersionId), since this BB will query the full model from the Catalog DB.
562             List<AllottedResource> allottedResources = serviceDecomposition.getAllottedResources()
563             if (allottedResources != null) {
564                 Iterator iter = allottedResources.iterator();
565                 while (iter.hasNext()) {
566                     AllottedResource allottedResource = (AllottedResource) iter.next();
567
568                     logger.debug(" getting model info for AllottedResource # :" + allottedResource.toJsonStringNoRootName())
569                     logger.debug(" allottedResource.getAllottedResourceType() :" + allottedResource.getAllottedResourceType())
570                     if ("BRG".equalsIgnoreCase(allottedResource.getAllottedResourceType())) {
571                         //set create flag to true
572                         execution.setVariable("createBRGAR", true)
573                         ModelInfo allottedResourceModelInfo = allottedResource.getModelInfo()
574                         execution.setVariable("allottedResourceModelInfoBRG", allottedResourceModelInfo.toJsonStringNoRootName())
575                         execution.setVariable("allottedResourceRoleBRG", allottedResource.getAllottedResourceRole())
576                         execution.setVariable("allottedResourceTypeBRG", allottedResource.getAllottedResourceType())
577                         //After decomposition and homing BBs, there should be an allotted resource object in the decomposition that represents the BRG,
578                         //and in its homingSolution section should be found the infraServiceInstanceId (i.e. infraServiceInstanceId in BRG Allotted Resource structure) (which the Homing BB would have populated).
579                         execution.setVariable("parentServiceInstanceIdBRG", allottedResource.getHomingSolution().getServiceInstanceId())
580                     }
581                 }
582             }
583
584             //unit test only
585             String allottedResourceId = execution.getVariable("allottedResourceId")
586             execution.setVariable("allottedResourceIdBRG", allottedResourceId)
587             logger.debug("setting allottedResourceId CreateVcpeResCustService " + allottedResourceId)
588
589             logger.trace("Completed prepareCreateAllottedResourceBRG of CreateVcpeResCustService ")
590         } catch (Exception ex) {
591             // try error in method block
592             String exceptionMessage = "Bpmn error encountered in prepareCreateAllottedResourceBRG flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
593             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
594         }
595     }
596
597     // *******************************
598     //     Generate Network request Section
599     // *******************************
600     public void prepareVnfAndModulesCreate(DelegateExecution execution) {
601
602         try {
603             logger.trace("Inside prepareVnfAndModulesCreate of CreateVcpeResCustService ")
604
605             //          String disableRollback = execution.getVariable("disableRollback")
606             //          def backoutOnFailure = ""
607             //          if(disableRollback != null){
608             //              if ( disableRollback == true) {
609             //                  backoutOnFailure = "false"
610             //              } else if ( disableRollback == false) {
611             //                  backoutOnFailure = "true"
612             //              }
613             //          }
614             //failIfExists - optional
615
616             String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest")
617             String productFamilyId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.productFamilyId")
618             execution.setVariable("productFamilyId", productFamilyId)
619             logger.debug("productFamilyId: " + productFamilyId)
620
621             List<VnfResource> vnfList = execution.getVariable("vnfList")
622
623             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
624             String vnfModelInfoString = null;
625
626             if (vnfList != null && vnfList.size() > 0) {
627                 logger.debug("getting model info for vnf # " + vnfsCreatedCount)
628                 ModelInfo vnfModelInfo1 = vnfList[0].getModelInfo()
629                 logger.debug("got 0 ")
630                 ModelInfo vnfModelInfo = vnfList[vnfsCreatedCount.intValue()].getModelInfo()
631                 vnfModelInfoString = vnfModelInfo.toString()
632             } else {
633                 //TODO: vnfList does not contain data. Need to investigate why ... . Fro VCPE use model stored
634                 vnfModelInfoString = execution.getVariable("vnfModelInfo")
635             }
636
637             logger.debug(" vnfModelInfoString :" + vnfModelInfoString)
638
639             // extract cloud configuration - if underscore "_" is present treat as vimId else it's a cloudRegion
640             String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest,
641                     "requestDetails.cloudConfiguration.lcpCloudRegionId")
642             if (vimId.contains("_") && vimId.split("_").length == 2 )  {
643                 def cloudRegion = vimId.split("_")
644                 execution.setVariable("cloudOwner", cloudRegion[0])
645                 logger.debug("cloudOwner: " + cloudRegion[0])
646                 execution.setVariable("cloudRegionId", cloudRegion[1])
647                 logger.debug("cloudRegionId: " + cloudRegion[1])
648                 execution.setVariable("lcpCloudRegionId", cloudRegion[1])
649                 logger.debug("lcpCloudRegionId: " + cloudRegion[1])
650             } else {
651                 logger.debug("vimId is not present - setting cloudRegion/cloudOwner from request.")
652                 String cloudOwner = jsonUtil.getJsonValue(createVcpeServiceRequest,
653                         "requestDetails.cloudConfiguration.cloudOwner")
654                 if (!cloudOwner?.empty && cloudOwner != "")
655                 {
656                     execution.setVariable("cloudOwner", cloudOwner)
657                     logger.debug("cloudOwner: " + cloudOwner)
658                 }
659                 execution.setVariable("cloudRegionId", vimId)
660                 logger.debug("cloudRegionId: " + vimId)
661                 execution.setVariable("lcpCloudRegionId", vimId)
662                 logger.debug("lcpCloudRegionId: " + vimId)
663             }
664
665             String tenantId = jsonUtil.getJsonValue(createVcpeServiceRequest,
666                     "requestDetails.cloudConfiguration.tenantId")
667             execution.setVariable("tenantId", tenantId)
668             logger.debug("tenantId: " + tenantId)
669
670             String sdncVersion = execution.getVariable("sdncVersion")
671             logger.debug("sdncVersion: " + sdncVersion)
672
673             logger.trace("Completed prepareVnfAndModulesCreate of CreateVcpeResCustService ")
674         } catch (Exception ex) {
675             // try error in method block
676             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareVnfAndModulesCreate() - " + ex.getMessage()
677             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
678         }
679     }
680
681     // *******************************
682     //     Validate Vnf request Section -> increment count
683     // *******************************
684     public void validateVnfCreate(DelegateExecution execution) {
685
686         try {
687             logger.trace("Inside validateVnfCreate of CreateVcpeResCustService ")
688
689             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
690             vnfsCreatedCount++
691
692             execution.setVariable(Prefix + "VnfsCreatedCount", vnfsCreatedCount)
693
694             logger.debug(" ***** Completed validateVnfCreate of CreateVcpeResCustService ***** " + " vnf # " + vnfsCreatedCount)
695         } catch (Exception ex) {
696             // try error in method block
697             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method validateVnfCreate() - " + ex.getMessage()
698             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
699         }
700     }
701
702     // *****************************************
703     //     Prepare Completion request Section
704     // *****************************************
705     public void postProcessResponse(DelegateExecution execution) {
706
707         logger.trace("Inside postProcessResponse of CreateVcpeResCustService ")
708
709         try {
710             String source = execution.getVariable("source")
711             String requestId = execution.getVariable("mso-request-id")
712             String serviceInstanceId = execution.getVariable("serviceInstanceId")
713
714             String msoCompletionRequest =
715                     """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
716                                     xmlns:ns="http://org.onap/so/request/types/v1">
717                             <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
718                                 <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
719                                 <action>CREATE</action>
720                                 <source>${MsoUtils.xmlEscape(source)}</source>
721                             </request-info>
722                             <status-message>Service Instance has been created successfully via macro orchestration</status-message>
723                             <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
724                             <mso-bpel-name>BPMN macro create</mso-bpel-name>
725                         </aetgt:MsoCompletionRequest>"""
726
727             // Format Response
728             String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
729
730             logger.debug(xmlMsoCompletionRequest)
731             execution.setVariable(Prefix + "Success", true)
732             execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest)
733             logger.debug(" SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
734         } catch (BpmnError e) {
735             throw e;
736         } catch (Exception ex) {
737             // try error in method block
738             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage()
739             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
740         }
741     }
742
743     public void preProcessRollback(DelegateExecution execution) {
744         logger.trace("preProcessRollback of CreateVcpeResCustService ")
745         try {
746
747             Object workflowException = execution.getVariable("WorkflowException");
748
749             if (workflowException instanceof WorkflowException) {
750                 logger.debug("Prev workflowException: " + workflowException.getErrorMessage())
751                 execution.setVariable("prevWorkflowException", workflowException);
752                 //execution.setVariable("WorkflowException", null);
753             }
754         } catch (BpmnError e) {
755             logger.debug("BPMN Error during preProcessRollback")
756         } catch (Exception ex) {
757             String msg = "Exception in preProcessRollback. " + ex.getMessage()
758             logger.debug(msg)
759         }
760         logger.trace("Exit preProcessRollback of CreateVcpeResCustService ")
761     }
762
763     public void postProcessRollback(DelegateExecution execution) {
764         logger.trace("postProcessRollback of CreateVcpeResCustService ")
765         String msg = ""
766         try {
767             Object workflowException = execution.getVariable("prevWorkflowException");
768             if (workflowException instanceof WorkflowException) {
769                 logger.debug("Setting prevException to WorkflowException: ")
770                 execution.setVariable("WorkflowException", workflowException);
771             }
772         } catch (BpmnError b) {
773             logger.debug("BPMN Error during postProcessRollback")
774             throw b;
775         } catch (Exception ex) {
776             msg = "Exception in postProcessRollback. " + ex.getMessage()
777             logger.debug(msg)
778         }
779         logger.trace("Exit postProcessRollback of CreateVcpeResCustService ")
780     }
781
782     public void prepareFalloutRequest(DelegateExecution execution) {
783
784         logger.trace("STARTED CreateVcpeResCustService prepareFalloutRequest Process ")
785
786         try {
787             WorkflowException wfex = execution.getVariable("WorkflowException")
788             logger.debug(" Incoming Workflow Exception: " + wfex.toString())
789             String requestInfo = execution.getVariable(Prefix + "requestInfo")
790             logger.debug(" Incoming Request Info: " + requestInfo)
791
792             //TODO. hmmm. there is no way to UPDATE error message.
793 //          String errorMessage = wfex.getErrorMessage()
794 //          boolean successIndicator = execution.getVariable("DCRESI_rolledBack")
795 //          if (successIndicator){
796 //              errorMessage = errorMessage + ". Rollback successful."
797 //          } else {
798 //              errorMessage = errorMessage + ". Rollback not completed."
799 //          }
800
801             String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
802
803             execution.setVariable(Prefix + "falloutRequest", falloutRequest)
804
805         } catch (Exception ex) {
806             logger.debug("Error Occured in CreateVcpeResCustService prepareFalloutRequest Process " + ex.getMessage())
807             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVcpeResCustService prepareFalloutRequest Process")
808         }
809         logger.trace("COMPLETED CreateVcpeResCustService prepareFalloutRequest Process ")
810     }
811
812
813     public void sendSyncError(DelegateExecution execution) {
814         execution.setVariable("prefix", Prefix)
815
816         logger.trace("Inside sendSyncError() of CreateVcpeResCustService ")
817
818         try {
819             String errorMessage = ""
820             def wfe = execution.getVariable("WorkflowException")
821             if (wfe instanceof WorkflowException) {
822                 errorMessage = wfe.getErrorMessage()
823             } else {
824                 errorMessage = "Sending Sync Error."
825             }
826
827             String buildworkflowException =
828                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
829                     <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
830                     <aetgt:ErrorCode>7000</aetgt:ErrorCode>
831                     </aetgt:WorkflowException>"""
832
833             logger.debug(buildworkflowException)
834             sendWorkflowResponse(execution, 500, buildworkflowException)
835         } catch (Exception ex) {
836             logger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
837         }
838     }
839
840     public void processJavaException(DelegateExecution execution) {
841         execution.setVariable("prefix", Prefix)
842         try {
843             logger.debug("Caught a Java Exception")
844             logger.debug("Started processJavaException Method")
845             logger.debug("Variables List: " + execution.getVariables())
846             execution.setVariable(Prefix + "unexpectedError", "Caught a Java Lang Exception")
847             // Adding this line temporarily until this flows error handling gets updated
848             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception")
849         } catch (BpmnError b) {
850             logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
851                     "Rethrowing MSOWorkflowException", "BPMN",
852                     ErrorCode.UnknownError.getValue());
853             throw b
854         } catch (Exception e) {
855             logger.debug("Caught Exception during processJavaException Method: " + e)
856             execution.setVariable(Prefix + "unexpectedError", "Exception in processJavaException method")
857             // Adding this line temporarily until this flows error handling gets updated
858             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method")
859         }
860         logger.debug("Completed processJavaException Method")
861     }
862 }