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