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