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