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