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