beac679691c9d73b12641e0c1a27d858e29d69d4
[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, split vid_ID into cloudOwner and cloudRegionId
180             String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest,
181                     "requestDetails.cloudConfiguration.lcpCloudRegionId")
182             def cloudRegion = vimId.split("_")
183             def cloudOwner = cloudRegion[0].toString()
184             def cloudRegionId = cloudRegion[1].toString()
185             execution.setVariable("cloudOwner", cloudOwner)
186             utils.log("DEBUG","cloudOwner: " + cloudOwner, isDebugEnabled)
187             execution.setVariable("cloudRegionId", cloudRegionId)
188             utils.log("DEBUG","cloudRegionId: " + cloudRegionId, isDebugEnabled)
189
190             /*
191             * Extracting User Parameters from incoming Request and converting into a Map
192             */
193             def jsonSlurper = new JsonSlurper()
194
195             Map reqMap = jsonSlurper.parseText(createVcpeServiceRequest)
196
197             //InputParams
198             def userParams = reqMap.requestDetails?.requestParameters?.userParams
199
200             Map<String, String> inputMap = [:]
201           if (userParams) {
202                 userParams.each {
203                                 userParam ->
204                         if ("Customer_Location".equals(userParam?.name)) {
205                             Map<String, String> customerMap = [:]
206                             userParam.value.each {
207                                 param ->
208
209                                     inputMap.put(param.key, param.value)
210                                     customerMap.put(param.key, param.value)
211                                     }
212                             execution.setVariable("customerLocation", customerMap)
213                         }
214                         if ("Homing_Model_Ids".equals(userParam?.name)) {
215                             utils.log("DEBUG", "Homing_Model_Ids: " + userParam.value.toString() + "  ---- Type is:" +
216                                     userParam.value.getClass() , isDebugEnabled)
217                             def modelIdLst = []
218                             userParam.value.each {
219                                 param ->
220                                     def valueMap = [:]
221                                     param.each {
222                                         entry ->
223                                             valueMap.put(entry.key, entry.value)
224                                     }
225                                     modelIdLst.add(valueMap)
226                                     utils.log("DEBUG", "Param: " + param.toString() + "  ---- Type is:" +
227                                             param.getClass() , isDebugEnabled)
228                                     }
229                             execution.setVariable("homingModelIds", modelIdLst)
230                                 }
231                         if ("BRG_WAN_MAC_Address".equals(userParam?.name)) {
232                             execution.setVariable("brgWanMacAddress", userParam.value)
233                             inputMap.put("BRG_WAN_MAC_Address", userParam.value)
234                         }
235                         if ("Homing_Solution".equals(userParam?.name)) {
236                                     execution.setVariable("homingService", userParam.value)
237                                     execution.setVariable("callHoming", true)
238                                     inputMap.put("Homing_Solution", userParam.value)
239                                 }
240                 }
241             }
242
243             if (execution.getVariable("homingService") == "") {
244                 // Set Default Homing to OOF if not set
245                 execution.setVariable("homingService", "oof")
246             }
247
248             msoLogger.debug("User Input Parameters map: " + userParams.toString())
249             execution.setVariable("serviceInputParams", inputMap)
250
251             msoLogger.debug("Incoming brgWanMacAddress is: " + execution.getVariable('brgWanMacAddress'))
252
253             //For Completion Handler & Fallout Handler
254             String requestInfo =
255                     """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
256                     <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
257                     <action>CREATE</action>
258                     <source>${MsoUtils.xmlEscape(source)}</source>
259                    </request-info>"""
260
261             execution.setVariable(Prefix + "requestInfo", requestInfo)
262
263             msoLogger.trace("Completed preProcessRequest CreateVcpeResCustService Request ")
264
265         } catch (BpmnError e) {
266             throw e;
267
268         } catch (Exception ex) {
269             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage()
270             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
271         }
272     }
273
274     public void sendSyncResponse(DelegateExecution execution) {
275
276         msoLogger.trace("Inside sendSyncResponse of CreateVcpeResCustService ")
277
278         try {
279             String serviceInstanceId = execution.getVariable("serviceInstanceId")
280             String requestId = execution.getVariable("mso-request-id")
281
282             // RESTResponse (for API Handler (APIH) Reply Task)
283             String syncResponse = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${
284                 requestId
285             }"}}""".trim()
286
287             msoLogger.debug(" sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
288             sendWorkflowResponse(execution, 202, syncResponse)
289
290         } catch (Exception ex) {
291             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected from method sendSyncResponse() - " + ex.getMessage()
292             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
293         }
294     }
295
296     // *******************************
297     //
298     // *******************************
299     public void prepareDecomposeService(DelegateExecution execution) {
300
301         try {
302             msoLogger.trace("Inside prepareDecomposeService of CreateVcpeResCustService ")
303
304             String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest")
305
306             //serviceModelInfo JSON string will be used as-is for DoCreateServiceInstance BB
307             String serviceModelInfo = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.modelInfo")
308             execution.setVariable("serviceModelInfo", serviceModelInfo)
309
310             msoLogger.trace("Completed prepareDecomposeService of CreateVcpeResCustService ")
311         } catch (Exception ex) {
312             // try error in method block
313             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
314             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
315         }
316     }
317
318     // *******************************
319     //
320     // *******************************
321     public void prepareCreateServiceInstance(DelegateExecution execution) {
322
323         try {
324             msoLogger.trace("Inside prepareCreateServiceInstance of CreateVcpeResCustService ")
325
326             /*
327              * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject
328              *      ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
329              *      ModelInfo modelInfo = serviceDecomposition.getModelInfo()
330              *
331              */
332             String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest")
333 //          String serviceInputParams = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestParameters")
334 //          execution.setVariable("serviceInputParams", serviceInputParams)
335
336
337             String serviceInstanceName = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.instanceName")
338             execution.setVariable("serviceInstanceName", serviceInstanceName)
339
340             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
341             execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonStringNoRootName())
342
343             msoLogger.trace("Completed prepareCreateServiceInstance of CreateVcpeResCustService ")
344         } catch (Exception ex) {
345             // try error in method block
346             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
347             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
348         }
349     }
350
351     public void postProcessServiceInstanceCreate(DelegateExecution execution) {
352         def method = getClass().getSimpleName() + '.postProcessServiceInstanceCreate(' + 'execution=' + execution.getId() + ')'
353         msoLogger.trace('Entered ' + method)
354
355         String requestId = execution.getVariable("mso-request-id")
356         String serviceInstanceId = execution.getVariable("serviceInstanceId")
357         String serviceInstanceName = execution.getVariable("serviceInstanceName")
358
359         try {
360
361             String payload = """
362             <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
363             <soapenv:Header/>
364             <soapenv:Body>
365             <req:updateInfraRequest>
366                 <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
367                 <lastModifiedBy>BPEL</lastModifiedBy>
368                 <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
369                 <serviceInstanceName>${MsoUtils.xmlEscape(serviceInstanceName)}</serviceInstanceName>
370             </req:updateInfraRequest>
371             </soapenv:Body>
372             </soapenv:Envelope>
373             """
374             execution.setVariable(Prefix + "setUpdateDbInstancePayload", payload)
375             msoLogger.debug(Prefix + "setUpdateDbInstancePayload: " + payload)
376             msoLogger.trace('Exited ' + method)
377
378         } catch (BpmnError e) {
379             throw e;
380         } catch (Exception e) {
381             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
382             exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
383         }
384     }
385
386
387     public void processDecomposition(DelegateExecution execution) {
388
389         msoLogger.trace("Inside processDecomposition() of CreateVcpeResCustService ")
390
391         try {
392
393             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
394
395             // VNFs
396             List<VnfResource> vnfList = serviceDecomposition.getVnfResources()
397             filterVnfs(vnfList)
398             serviceDecomposition.setVnfResources(vnfList)
399
400             execution.setVariable("vnfList", vnfList)
401             execution.setVariable("vnfListString", vnfList.toString())
402
403             String vnfModelInfoString = ""
404             if (vnfList != null && vnfList.size() > 0) {
405                 execution.setVariable(Prefix + "VNFsCount", vnfList.size())
406                 msoLogger.debug("vnfs to create: " + vnfList.size())
407                 ModelInfo vnfModelInfo = vnfList[0].getModelInfo()
408
409                 vnfModelInfoString = vnfModelInfo.toString()
410                 String vnfModelInfoWithRoot = vnfModelInfo.toString()
411                 vnfModelInfoString = jsonUtil.getJsonValue(vnfModelInfoWithRoot, "modelInfo")
412             } else {
413                 execution.setVariable(Prefix + "VNFsCount", 0)
414                 msoLogger.debug("no vnfs to create based upon serviceDecomposition content")
415             }
416
417             execution.setVariable("vnfModelInfo", vnfModelInfoString)
418             execution.setVariable("vnfModelInfoString", vnfModelInfoString)
419             msoLogger.debug(" vnfModelInfoString :" + vnfModelInfoString)
420
421             msoLogger.trace("Completed processDecomposition() of CreateVcpeResCustService ")
422         } catch (Exception ex) {
423             sendSyncError(execution)
424             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. processDecomposition() - " + ex.getMessage()
425             msoLogger.debug(exceptionMessage)
426             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
427         }
428     }
429
430     private void filterVnfs(List<VnfResource> vnfList) {
431         if (vnfList == null) {
432             return
433         }
434
435         // remove BRG & TXC from VNF list
436
437         Iterator<VnfResource> it = vnfList.iterator()
438         while (it.hasNext()) {
439             VnfResource vr = it.next()
440
441             String role = vr.getNfRole()
442             if (role == "BRG" || role == "TunnelXConn" || role == "Tunnel XConn") {
443                 it.remove()
444             }
445         }
446     }
447
448
449     public void prepareCreateAllottedResourceTXC(DelegateExecution execution) {
450
451         try {
452             msoLogger.trace("Inside prepareCreateAllottedResourceTXC of CreateVcpeResCustService ")
453
454             /*
455              * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject
456              *      ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
457              *      ModelInfo modelInfo = serviceDecomposition.getModelInfo()
458              *
459              */
460             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
461
462             //allottedResourceModelInfo
463             //allottedResourceRole
464             //The model Info parameters are a JSON structure as defined in the Service Instantiation API.
465             //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.
466             List<AllottedResource> allottedResources = serviceDecomposition.getAllottedResources()
467             if (allottedResources != null) {
468                 Iterator iter = allottedResources.iterator();
469                 while (iter.hasNext()) {
470                     AllottedResource allottedResource = (AllottedResource) iter.next();
471
472                     msoLogger.debug(" getting model info for AllottedResource # :" + allottedResource.toJsonStringNoRootName())
473                     msoLogger.debug(" allottedResource.getAllottedResourceType() :" + allottedResource.getAllottedResourceType())
474                     if ("TunnelXConn".equalsIgnoreCase(allottedResource.getAllottedResourceType()) || "Tunnel XConn".equalsIgnoreCase(allottedResource.getAllottedResourceType())) {
475                         //set create flag to true
476                         execution.setVariable("createTXCAR", true)
477                         ModelInfo allottedResourceModelInfo = allottedResource.getModelInfo()
478                         execution.setVariable("allottedResourceModelInfoTXC", allottedResourceModelInfo.toJsonStringNoRootName())
479                         execution.setVariable("allottedResourceRoleTXC", allottedResource.getAllottedResourceRole())
480                         execution.setVariable("allottedResourceTypeTXC", allottedResource.getAllottedResourceType())
481                         //After decomposition and homing BBs, there should be an allotted resource object in the decomposition that represents the TXC,
482                         //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).
483                         execution.setVariable("parentServiceInstanceIdTXC", allottedResource.getHomingSolution().getServiceInstanceId())
484                     }
485                 }
486             }
487
488             //unit test only
489             String allottedResourceId = execution.getVariable("allottedResourceId")
490             execution.setVariable("allottedResourceIdTXC", allottedResourceId)
491             msoLogger.debug("setting allottedResourceId CreateVcpeResCustService " + allottedResourceId)
492
493             msoLogger.trace("Completed prepareCreateAllottedResourceTXC of CreateVcpeResCustService ")
494         } catch (Exception ex) {
495             // try error in method block
496             String exceptionMessage = "Bpmn error encountered in prepareCreateAllottedResourceTXC flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
497             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
498         }
499     }
500
501     public void prepareCreateAllottedResourceBRG(DelegateExecution execution) {
502
503         try {
504             msoLogger.trace("Inside prepareCreateAllottedResourceBRG of CreateVcpeResCustService ")
505
506             /*
507              * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject
508              *      ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
509              *      ModelInfo modelInfo = serviceDecomposition.getModelInfo()
510              *
511              */
512             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
513
514             //allottedResourceModelInfo
515             //allottedResourceRole
516             //The model Info parameters are a JSON structure as defined in the Service Instantiation API.
517             //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.
518             List<AllottedResource> allottedResources = serviceDecomposition.getAllottedResources()
519             if (allottedResources != null) {
520                 Iterator iter = allottedResources.iterator();
521                 while (iter.hasNext()) {
522                     AllottedResource allottedResource = (AllottedResource) iter.next();
523
524                     msoLogger.debug(" getting model info for AllottedResource # :" + allottedResource.toJsonStringNoRootName())
525                     msoLogger.debug(" allottedResource.getAllottedResourceType() :" + allottedResource.getAllottedResourceType())
526                     if ("BRG".equalsIgnoreCase(allottedResource.getAllottedResourceType())) {
527                         //set create flag to true
528                         execution.setVariable("createBRGAR", true)
529                         ModelInfo allottedResourceModelInfo = allottedResource.getModelInfo()
530                         execution.setVariable("allottedResourceModelInfoBRG", allottedResourceModelInfo.toJsonStringNoRootName())
531                         execution.setVariable("allottedResourceRoleBRG", allottedResource.getAllottedResourceRole())
532                         execution.setVariable("allottedResourceTypeBRG", allottedResource.getAllottedResourceType())
533                         //After decomposition and homing BBs, there should be an allotted resource object in the decomposition that represents the BRG,
534                         //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).
535                         execution.setVariable("parentServiceInstanceIdBRG", allottedResource.getHomingSolution().getServiceInstanceId())
536                     }
537                 }
538             }
539
540             //unit test only
541             String allottedResourceId = execution.getVariable("allottedResourceId")
542             execution.setVariable("allottedResourceIdBRG", allottedResourceId)
543             msoLogger.debug("setting allottedResourceId CreateVcpeResCustService " + allottedResourceId)
544
545             msoLogger.trace("Completed prepareCreateAllottedResourceBRG of CreateVcpeResCustService ")
546         } catch (Exception ex) {
547             // try error in method block
548             String exceptionMessage = "Bpmn error encountered in prepareCreateAllottedResourceBRG flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
549             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
550         }
551     }
552
553     // *******************************
554     //     Generate Network request Section
555     // *******************************
556     public void prepareVnfAndModulesCreate(DelegateExecution execution) {
557
558         try {
559             msoLogger.trace("Inside prepareVnfAndModulesCreate of CreateVcpeResCustService ")
560
561             //          String disableRollback = execution.getVariable("disableRollback")
562             //          def backoutOnFailure = ""
563             //          if(disableRollback != null){
564             //              if ( disableRollback == true) {
565             //                  backoutOnFailure = "false"
566             //              } else if ( disableRollback == false) {
567             //                  backoutOnFailure = "true"
568             //              }
569             //          }
570             //failIfExists - optional
571
572             String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest")
573             String productFamilyId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.productFamilyId")
574             execution.setVariable("productFamilyId", productFamilyId)
575             msoLogger.debug("productFamilyId: " + productFamilyId)
576
577             List<VnfResource> vnfList = execution.getVariable("vnfList")
578
579             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
580             String vnfModelInfoString = null;
581
582             if (vnfList != null && vnfList.size() > 0) {
583                 msoLogger.debug("getting model info for vnf # " + vnfsCreatedCount)
584                 ModelInfo vnfModelInfo1 = vnfList[0].getModelInfo()
585                 msoLogger.debug("got 0 ")
586                 ModelInfo vnfModelInfo = vnfList[vnfsCreatedCount.intValue()].getModelInfo()
587                 vnfModelInfoString = vnfModelInfo.toString()
588             } else {
589                 //TODO: vnfList does not contain data. Need to investigate why ... . Fro VCPE use model stored
590                 vnfModelInfoString = execution.getVariable("vnfModelInfo")
591             }
592
593             msoLogger.debug(" vnfModelInfoString :" + vnfModelInfoString)
594
595             // extract cloud configuration
596             String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest,
597                     "requestDetails.cloudConfiguration.lcpCloudRegionId")
598             def cloudRegion = vimId.split("_")
599             execution.setVariable("cloudOwner", cloudRegion[0])
600             msoLogger.debug("cloudOwner: "+ cloudRegion[0])
601             execution.setVariable("cloudRegionId", cloudRegion[1])
602             msoLogger.debug("cloudRegionId: "+ cloudRegion[1])
603             execution.setVariable("lcpCloudRegionId", cloudRegion[1])
604             msoLogger.debug("lcpCloudRegionId: "+ cloudRegion[1])
605             String tenantId = jsonUtil.getJsonValue(createVcpeServiceRequest,
606                     "requestDetails.cloudConfiguration.tenantId")
607             execution.setVariable("tenantId", tenantId)
608             msoLogger.debug("tenantId: " + tenantId)
609
610             String sdncVersion = execution.getVariable("sdncVersion")
611             msoLogger.debug("sdncVersion: " + sdncVersion)
612
613             msoLogger.trace("Completed prepareVnfAndModulesCreate of CreateVcpeResCustService ")
614         } catch (Exception ex) {
615             // try error in method block
616             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareVnfAndModulesCreate() - " + ex.getMessage()
617             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
618         }
619     }
620
621     // *******************************
622     //     Validate Vnf request Section -> increment count
623     // *******************************
624     public void validateVnfCreate(DelegateExecution execution) {
625
626         try {
627             msoLogger.trace("Inside validateVnfCreate of CreateVcpeResCustService ")
628
629             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
630             vnfsCreatedCount++
631
632             execution.setVariable(Prefix + "VnfsCreatedCount", vnfsCreatedCount)
633
634             msoLogger.debug(" ***** Completed validateVnfCreate of CreateVcpeResCustService ***** " + " vnf # " + vnfsCreatedCount)
635         } catch (Exception ex) {
636             // try error in method block
637             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method validateVnfCreate() - " + ex.getMessage()
638             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
639         }
640     }
641
642     // *****************************************
643     //     Prepare Completion request Section
644     // *****************************************
645     public void postProcessResponse(DelegateExecution execution) {
646
647         msoLogger.trace("Inside postProcessResponse of CreateVcpeResCustService ")
648
649         try {
650             String source = execution.getVariable("source")
651             String requestId = execution.getVariable("mso-request-id")
652             String serviceInstanceId = execution.getVariable("serviceInstanceId")
653
654             String msoCompletionRequest =
655                     """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
656                                     xmlns:ns="http://org.onap/so/request/types/v1">
657                             <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
658                                 <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
659                                 <action>CREATE</action>
660                                 <source>${MsoUtils.xmlEscape(source)}</source>
661                             </request-info>
662                             <status-message>Service Instance has been created successfully via macro orchestration</status-message>
663                             <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
664                             <mso-bpel-name>BPMN macro create</mso-bpel-name>
665                         </aetgt:MsoCompletionRequest>"""
666
667             // Format Response
668             String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
669
670             msoLogger.debug(xmlMsoCompletionRequest)
671             execution.setVariable(Prefix + "Success", true)
672             execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest)
673             msoLogger.debug(" SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
674         } catch (BpmnError e) {
675             throw e;
676         } catch (Exception ex) {
677             // try error in method block
678             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage()
679             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
680         }
681     }
682
683     public void preProcessRollback(DelegateExecution execution) {
684         msoLogger.trace("preProcessRollback of CreateVcpeResCustService ")
685         try {
686
687             Object workflowException = execution.getVariable("WorkflowException");
688
689             if (workflowException instanceof WorkflowException) {
690                 msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage())
691                 execution.setVariable("prevWorkflowException", workflowException);
692                 //execution.setVariable("WorkflowException", null);
693             }
694         } catch (BpmnError e) {
695             msoLogger.debug("BPMN Error during preProcessRollback")
696         } catch (Exception ex) {
697             String msg = "Exception in preProcessRollback. " + ex.getMessage()
698             msoLogger.debug(msg)
699         }
700         msoLogger.trace("Exit preProcessRollback of CreateVcpeResCustService ")
701     }
702
703     public void postProcessRollback(DelegateExecution execution) {
704         msoLogger.trace("postProcessRollback of CreateVcpeResCustService ")
705         String msg = ""
706         try {
707             Object workflowException = execution.getVariable("prevWorkflowException");
708             if (workflowException instanceof WorkflowException) {
709                 msoLogger.debug("Setting prevException to WorkflowException: ")
710                 execution.setVariable("WorkflowException", workflowException);
711             }
712         } catch (BpmnError b) {
713             msoLogger.debug("BPMN Error during postProcessRollback")
714             throw b;
715         } catch (Exception ex) {
716             msg = "Exception in postProcessRollback. " + ex.getMessage()
717             msoLogger.debug(msg)
718         }
719         msoLogger.trace("Exit postProcessRollback of CreateVcpeResCustService ")
720     }
721
722     public void prepareFalloutRequest(DelegateExecution execution) {
723
724         msoLogger.trace("STARTED CreateVcpeResCustService prepareFalloutRequest Process ")
725
726         try {
727             WorkflowException wfex = execution.getVariable("WorkflowException")
728             msoLogger.debug(" Incoming Workflow Exception: " + wfex.toString())
729             String requestInfo = execution.getVariable(Prefix + "requestInfo")
730             msoLogger.debug(" Incoming Request Info: " + requestInfo)
731
732             //TODO. hmmm. there is no way to UPDATE error message.
733 //          String errorMessage = wfex.getErrorMessage()
734 //          boolean successIndicator = execution.getVariable("DCRESI_rolledBack")
735 //          if (successIndicator){
736 //              errorMessage = errorMessage + ". Rollback successful."
737 //          } else {
738 //              errorMessage = errorMessage + ". Rollback not completed."
739 //          }
740
741             String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
742
743             execution.setVariable(Prefix + "falloutRequest", falloutRequest)
744
745         } catch (Exception ex) {
746             msoLogger.debug("Error Occured in CreateVcpeResCustService prepareFalloutRequest Process " + ex.getMessage())
747             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVcpeResCustService prepareFalloutRequest Process")
748         }
749         msoLogger.trace("COMPLETED CreateVcpeResCustService prepareFalloutRequest Process ")
750     }
751
752
753     public void sendSyncError(DelegateExecution execution) {
754         execution.setVariable("prefix", Prefix)
755
756         msoLogger.trace("Inside sendSyncError() of CreateVcpeResCustService ")
757
758         try {
759             String errorMessage = ""
760             def wfe = execution.getVariable("WorkflowException")
761             if (wfe instanceof WorkflowException) {
762                 errorMessage = wfe.getErrorMessage()
763             } else {
764                 errorMessage = "Sending Sync Error."
765             }
766
767             String buildworkflowException =
768                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
769                     <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
770                     <aetgt:ErrorCode>7000</aetgt:ErrorCode>
771                     </aetgt:WorkflowException>"""
772
773             msoLogger.debug(buildworkflowException)
774             sendWorkflowResponse(execution, 500, buildworkflowException)
775         } catch (Exception ex) {
776             msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
777         }
778     }
779
780     public void processJavaException(DelegateExecution execution) {
781         execution.setVariable("prefix", Prefix)
782         try {
783             msoLogger.debug("Caught a Java Exception")
784             msoLogger.debug("Started processJavaException Method")
785             msoLogger.debug("Variables List: " + execution.getVariables())
786             execution.setVariable(Prefix + "unexpectedError", "Caught a Java Lang Exception")
787             // Adding this line temporarily until this flows error handling gets updated
788             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception")
789         } catch (BpmnError b) {
790             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Rethrowing MSOWorkflowException", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
791             throw b
792         } catch (Exception e) {
793             msoLogger.debug("Caught Exception during processJavaException Method: " + e)
794             execution.setVariable(Prefix + "unexpectedError", "Exception in processJavaException method")
795             // Adding this line temporarily until this flows error handling gets updated
796             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method")
797         }
798         msoLogger.debug("Completed processJavaException Method")
799     }
800 }