Merge "Simplify InfraUtils"
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / CreateGenericMacroServiceNetworkVnf.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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
21 package org.openecomp.mso.bpmn.infrastructure.scripts;
22
23 import groovy.xml.XmlUtil
24 import groovy.json.*
25
26 import org.openecomp.mso.bpmn.core.json.JsonUtils
27 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
28 import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils
29 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
30 import org.openecomp.mso.bpmn.common.scripts.VidUtils
31 import org.openecomp.mso.bpmn.core.WorkflowException
32 import org.openecomp.mso.rest.APIResponse;
33 import org.openecomp.mso.rest.RESTClient
34 import org.openecomp.mso.rest.RESTConfig
35
36 import java.util.UUID;
37
38 import org.camunda.bpm.engine.delegate.BpmnError
39 import org.camunda.bpm.engine.runtime.Execution
40 import org.json.JSONObject;
41 import org.json.JSONArray;
42 import org.apache.commons.lang3.*
43 import org.apache.commons.codec.binary.Base64;
44 import org.springframework.web.util.UriUtils;
45
46 /**
47  * This groovy class supports the <class>CreateGenericMacroServiceNetworkVnf.bpmn</class> process.
48  *
49  */
50 public class CreateGenericMacroServiceNetworkVnf extends AbstractServiceTaskProcessor {
51
52         String Prefix="CREVAS_"
53         ExceptionUtil exceptionUtil = new ExceptionUtil()
54         JsonUtils jsonUtil = new JsonUtils()
55         VidUtils vidUtils = new VidUtils()
56         CatalogDbUtils catalogDbUtils = new CatalogDbUtils()
57
58         /**
59          * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
60          * @param execution
61          */
62         public InitializeProcessVariables(Execution execution){
63                 /* Initialize all the process variables in this block */
64
65                 execution.setVariable("createGenericMacroServiceNetworkVnfRequest", "")
66                 execution.setVariable("globalSubscriberId", "")
67                 execution.setVariable("serviceInstanceName", "")
68                 execution.setVariable("msoRequestId", "")
69                 execution.setVariable("CREVAS_NetworksCreatedCount", 0)
70                 execution.setVariable("CREVAS_VnfsCreatedCount", 0)
71                 execution.setVariable("productFamilyId", "")
72                 
73                 
74                 //TODO
75                 execution.setVariable("sdncVersion", "1702")
76         }
77
78         // **************************************************
79         //     Pre or Prepare Request Section
80         // **************************************************
81         /**
82          * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
83          * @param execution
84          */
85         public void preProcessRequest (Execution execution) {
86                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
87                 execution.setVariable("prefix",Prefix)
88
89                 utils.log("DEBUG", " ***** Inside preProcessRequest CreateGenericMacroServiceNetworkVnf Request ***** ", isDebugEnabled)
90
91                 try {
92                         // initialize flow variables
93                         InitializeProcessVariables(execution)
94
95                         // check for incoming json message/input
96                         String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("bpmnRequest")
97                         utils.logAudit(createGenericMacroServiceNetworkVnfRequest)
98                         execution.setVariable("createGenericMacroServiceNetworkVnfRequest", createGenericMacroServiceNetworkVnfRequest);
99                         println 'createGenericMacroServiceNetworkVnfRequest - ' + createGenericMacroServiceNetworkVnfRequest
100
101                         // extract requestId
102                         String requestId = execution.getVariable("mso-request-id")
103                         execution.setVariable("msoRequestId", requestId)
104
105                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
106
107                         if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) {
108                                 serviceInstanceId = UUID.randomUUID().toString()
109                                 utils.log("DEBUG", " Generated new Service Instance: " + serviceInstanceId , isDebugEnabled)
110                         } else {
111                                 utils.log("DEBUG", "Using provided Service Instance ID: " + serviceInstanceId , isDebugEnabled)
112                         }
113
114                         serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8")
115                         execution.setVariable("serviceInstanceId", serviceInstanceId)
116                         
117                         String requestAction = execution.getVariable("requestAction")
118                         execution.setVariable("requestAction", requestAction)
119
120                         String source = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.source")
121                         if ((source == null) || (source.isEmpty())) {
122                                 execution.setVariable("source", "VID")
123                         } else {
124                                 execution.setVariable("source", source)
125                         }
126
127                         // extract globalSubscriberId
128                         String globalSubscriberId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.subscriberInfo.globalSubscriberId")
129
130                         // verify element global-customer-id is sent from JSON input, throw exception if missing
131                         if ((globalSubscriberId == null) || (globalSubscriberId.isEmpty())) {
132                                 String dataErrorMessage = " Element 'globalSubscriberId' is missing. "
133                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
134
135                         } else {
136                                 execution.setVariable("globalSubscriberId", globalSubscriberId)
137                                 execution.setVariable("globalCustomerId", globalSubscriberId)
138                         }
139                         
140                         // extract subscriptionServiceType
141                         String subscriptionServiceType = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestParameters.subscriptionServiceType")
142                         execution.setVariable("subscriptionServiceType", subscriptionServiceType)
143                         utils.log("DEBUG", "Incoming subscriptionServiceType is: " + subscriptionServiceType, isDebugEnabled)
144
145                         String suppressRollback = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.suppressRollback")
146                         execution.setVariable("disableRollback", suppressRollback)
147                         utils.log("DEBUG", "Incoming Suppress/Disable Rollback is: " + suppressRollback, isDebugEnabled)
148                         
149                         String productFamilyId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.productFamilyId")
150                         execution.setVariable("productFamilyId", productFamilyId)
151                         utils.log("DEBUG", "Incoming productFamilyId is: " + productFamilyId, isDebugEnabled)
152                         
153                         //For Completion Handler & Fallout Handler
154                         String requestInfo =
155                         """<request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
156                                         <request-id>${requestId}</request-id>
157                                         <action>CREATE</action>
158                                         <source>${source}</source>
159                                    </request-info>"""
160
161                         execution.setVariable("CREVAS_requestInfo", requestInfo)
162                         
163                         utils.log("DEBUG", " ***** Completed preProcessRequest CreateGenericMacroServiceNetworkVnf Request ***** ", isDebugEnabled)
164
165                 } catch (BpmnError e) {
166                         throw e;
167
168                 } catch (Exception ex){
169                         String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected from method preProcessRequest() - " + ex.getMessage()
170                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
171                 }
172         }
173
174         public void sendSyncResponse (Execution execution) {
175                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
176
177                 utils.log("DEBUG", " ***** Inside sendSyncResponse of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
178
179                 try {
180                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
181                         String requestId = execution.getVariable("mso-request-id")
182
183                         // RESTResponse (for API Handler (APIH) Reply Task)
184                         String syncResponse ="""{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
185
186                         utils.log("DEBUG", " sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse, isDebugEnabled)
187                         sendWorkflowResponse(execution, 202, syncResponse)
188
189                 } catch (Exception ex) {
190                         String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected from method sendSyncResponse() - " + ex.getMessage()
191                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
192                 }
193         }
194
195         // *******************************
196         //     
197         // *******************************
198         public void prepareCreateServiceInstance(Execution execution) {
199                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
200
201                 try {
202                         utils.log("DEBUG", " ***** Inside prepareCreateServiceInstance of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
203
204                         String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest")
205                         String serviceModelInfo = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.modelInfo")
206                         execution.setVariable("serviceModelInfo", serviceModelInfo)
207
208                         String serviceInputParams = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestParameters")
209                         execution.setVariable("serviceInputParams", serviceInputParams)
210                         
211                         String serviceInstanceName = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.instanceName")
212                         execution.setVariable("serviceInstanceName", serviceInstanceName)
213
214                         utils.log("DEBUG", " ***** Completed prepareCreateServiceInstance of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
215                 } catch (Exception ex) {
216                         // try error in method block
217                         String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareCreateService() - " + ex.getMessage()
218                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
219                 }
220          }
221         
222         
223         public void postProcessServiceInstanceCreate (Execution execution){
224                 def method = getClass().getSimpleName() + '.postProcessServiceInstanceCreate(' +'execution=' + execution.getId() +')'
225                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
226                 logDebug('Entered ' + method, isDebugLogEnabled)
227                 
228                 String source = execution.getVariable("source")
229                 String requestId = execution.getVariable("mso-request-id")
230                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
231                 String serviceInstanceName = execution.getVariable("serviceInstanceName")
232                 
233                 try {
234
235                         String payload = """
236                         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.openecomp.mso/requestsdb">
237                         <soapenv:Header/>
238                         <soapenv:Body>
239                         <req:updateInfraRequest>
240                                 <requestId>${requestId}</requestId>
241                                 <lastModifiedBy>BPEL</lastModifiedBy>
242                                 <serviceInstanceId>${serviceInstanceId}</serviceInstanceId>
243                                 <serviceInstanceName>${serviceInstanceName}</serviceInstanceName>
244                         </req:updateInfraRequest>
245                         </soapenv:Body>
246                         </soapenv:Envelope>
247                         """
248                         execution.setVariable("CREVAS_setUpdateDbInstancePayload", payload)
249                         utils.logAudit("CREVAS_setUpdateDbInstancePayload: " + payload)
250                         logDebug('Exited ' + method, isDebugLogEnabled)
251                         //println("CMSO_updateDBStatusToSuccessPayload --> " + execution.getVariable("CMSO_updateDBStatusToSuccessPayload"))
252
253                 } catch (BpmnError e) {
254                         throw e;
255                 } catch (Exception e) {
256                         logError('Caught exception in ' + method, e)
257                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
258                 }
259         }
260         
261         
262         public void callDBCatalog (Execution execution) {
263                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
264
265                 utils.log("DEBUG", " ***** Inside callDBCatalog() of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
266                 
267                 try {
268                         
269                         // get variable within incoming json
270                         String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest");
271                         
272                         String catalog_db_endpoint = execution.getVariable("URN_mso_catalog_db_endpoint")
273                         utils.log("DEBUG", "catalog_db_endpoint: "+catalog_db_endpoint, isDebugEnabled)
274                         
275                         String serviceModelInvariantId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.modelInfo.modelInvariantId")
276                         String serviceModelVersion = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.modelInfo.modelVersion")
277                         utils.log("DEBUG", "getting network list ", isDebugEnabled)
278                         
279                         JSONArray networkList = catalogDbUtils.getAllNetworksByServiceModelInvariantUuidAndServiceModelVersion(catalog_db_endpoint, serviceModelInvariantId, serviceModelVersion)
280
281                         //utils.log("DEBUG", "got network list: "+ networkList.toString(), isDebugEnabled)
282                         execution.setVariable("networkList", networkList)
283                         execution.setVariable("networkListString", networkList.toString())
284                         
285                         if (networkList != null && networkList.length() > 0) {
286
287                                 execution.setVariable("CREVAS_NetworksCount", networkList.length())
288                                 utils.log("DEBUG", "networks to create: "+ networkList.length(), isDebugEnabled)
289                         } else {
290                                 execution.setVariable("CREVAS_NetworksCount", 0)
291                                 utils.log("DEBUG", "no networks to create based upon Catalog DB response", isDebugEnabled)
292                         }       
293                         
294                         // VNFs
295                         JSONArray vnfList = catalogDbUtils.getAllVnfsByServiceModelInvariantUuidAndServiceModelVersion(catalog_db_endpoint, serviceModelInvariantId, serviceModelVersion)
296                         execution.setVariable("vnfList", vnfList)                       
297                         
298                         String vnfModelInfoString = ""
299                         if (vnfList != null && vnfList.length() > 0) {
300                                 execution.setVariable("CREVAS_VNFsCount", vnfList.length())
301                                 utils.log("DEBUG", "vnfs to create: "+ vnfList.length(), isDebugEnabled)
302                                 JSONObject vnfModelInfo = vnfList.getJSONObject(0).getJSONObject("modelInfo")
303                                 vnfModelInfoString = vnfModelInfo.toString()
304                         } else {
305                                         execution.setVariable("CREVAS_VNFsCount", 0)
306                                         utils.log("DEBUG", "no vnfs to create based upon Catalog DB response", isDebugEnabled)
307                         }
308                                 
309                         execution.setVariable("vnfModelInfo", vnfModelInfoString)
310                         //utils.log("DEBUG", " vnfModelInfoString :" + vnfModelInfoString, isDebugEnabled)
311
312                         utils.log("DEBUG", " ***** Completed callDBCatalog() of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
313                 } catch (Exception ex) {
314                         sendSyncError(execution)
315                    String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. callDBCatalog() - " + ex.getMessage()
316                    utils.log("DEBUG", exceptionMessage, isDebugEnabled)
317                    exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
318                 }
319         }
320         
321         // *******************************
322         //     Generate Network request Section
323         // *******************************
324         public void prepareNetworkCreate (Execution execution) {
325                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
326
327                 try {
328                         utils.log("DEBUG", " ***** Inside preparenNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
329
330 //                      String disableRollback = execution.getVariable("disableRollback")
331 //                      def backoutOnFailure = ""
332 //                      if(disableRollback != null){
333 //                              if ( disableRollback == true) {
334 //                                      backoutOnFailure = "false"
335 //                              } else if ( disableRollback == false) {
336 //                                      backoutOnFailure = "true"
337 //                              }
338 //                      }
339                         //failIfExists - optional
340
341                         String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest")
342                         
343                         JSONArray networkList = execution.getVariable("networkList")
344                         utils.log("DEBUG", "array networkList: "+ networkList, isDebugEnabled)
345                         
346                         if (networkList == null || networkList.length() < 1){
347                                 networkList = new JSONArray(execution.getVariable("networkListString"))
348                                 utils.log("DEBUG", "array from string networkList: "+ networkList, isDebugEnabled)
349                         }
350                         
351                         Integer networksCreatedCount = execution.getVariable("CREVAS_NetworksCreatedCount")
352                         String networkModelInfoString = ""
353                         
354                         if (networkList != null) {
355                                 utils.log("DEBUG", " getting model info for network # :" + networksCreatedCount, isDebugEnabled)
356                                 JSONObject networkModelInfo = networkList.getJSONObject(networksCreatedCount.intValue()).getJSONObject("modelInfo")
357                                 networkModelInfoString = networkModelInfo.toString()
358                         } else {
359                                 String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected number of networks to create - " + ex.getMessage()
360                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
361                         }
362                         
363                         execution.setVariable("networkModelInfo", networkModelInfoString)
364                         utils.log("DEBUG", " networkModelInfoString :" + networkModelInfoString, isDebugEnabled)
365                         
366 //                      String networkModelInfo = execution.getVariable("networkModelInfo")
367                         // extract cloud configuration
368                         String lcpCloudRegionId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.lcpCloudRegionId")
369                         execution.setVariable("lcpCloudRegionId", lcpCloudRegionId)
370                         utils.log("DEBUG","lcpCloudRegionId: "+ lcpCloudRegionId, isDebugEnabled)
371                         String tenantId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.tenantId")
372                         execution.setVariable("tenantId", tenantId)
373                         utils.log("DEBUG","tenantId: "+ tenantId, isDebugEnabled)
374                         
375                         String sdncVersion = execution.getVariable("sdncVersion")
376                         utils.log("DEBUG","sdncVersion: "+ sdncVersion, isDebugEnabled)
377                         
378                         JSONArray vnfList = execution.getVariable("vnfList")
379                         utils.log("DEBUG", "vnfList: "+ vnfList, isDebugEnabled)
380                         
381                         String vnfModelInfo = execution.getVariable("vnfModelInfo")
382                         utils.log("DEBUG", "vnfModelInfo: "+ vnfModelInfo, isDebugEnabled)
383                         
384                         networkList = execution.getVariable("networkList")
385                         utils.log("DEBUG", "networkList: "+ networkList, isDebugEnabled)
386                         
387                         utils.log("DEBUG", " ***** Completed preparenNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
388                 } catch (Exception ex) {
389                         // try error in method block
390                         String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareNetworkCreate() - " + ex.getMessage()
391                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
392                 }
393          }
394         
395         // *******************************
396         //     Validate Network request Section -> increment count
397         // *******************************
398         public void validateNetworkCreate (Execution execution) {
399                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
400
401                 try {
402                         utils.log("DEBUG", " ***** Inside validateNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
403
404                         Integer networksCreatedCount = execution.getVariable("CREVAS_NetworksCreatedCount")
405                         networksCreatedCount++
406                         
407                         execution.setVariable("CREVAS_NetworksCreatedCount", networksCreatedCount)
408                         
409                         execution.setVariable("DCRENI_rollbackData"+networksCreatedCount, execution.getVariable("DCRENI_rollbackData"))
410
411                         utils.log("DEBUG", "networksCreatedCount: "+ networksCreatedCount, isDebugEnabled)
412                         utils.log("DEBUG", "DCRENI_rollbackData N : "+ execution.getVariable("DCRENI_rollbackData"+networksCreatedCount), isDebugEnabled)
413                         
414                         JSONArray vnfList = execution.getVariable("vnfList")
415                         utils.log("DEBUG", "vnfList: "+ vnfList, isDebugEnabled)
416                         
417                         String vnfModelInfo = execution.getVariable("vnfModelInfo")
418                         utils.log("DEBUG", "vnfModelInfo: "+ vnfModelInfo, isDebugEnabled)
419                         
420                         JSONArray networkList = execution.getVariable("networkList")
421                         utils.log("DEBUG", "networkList: "+ networkList, isDebugEnabled)
422                         
423                         utils.log("DEBUG", " ***** Completed validateNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** "+" network # "+networksCreatedCount, isDebugEnabled)
424                 } catch (Exception ex) {
425                         // try error in method block
426                         String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method validateNetworkCreate() - " + ex.getMessage()
427                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
428                 }
429          }
430         
431         // *******************************
432         //     Generate Network request Section
433         // *******************************
434         public void prepareVnfAndModulesCreate (Execution execution) {
435                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
436
437                 try {
438                         utils.log("DEBUG", " ***** Inside prepareVnfAndModulesCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
439
440                         //                      String disableRollback = execution.getVariable("disableRollback")
441                         //                      def backoutOnFailure = ""
442                         //                      if(disableRollback != null){
443                         //                              if ( disableRollback == true) {
444                         //                                      backoutOnFailure = "false"
445                         //                              } else if ( disableRollback == false) {
446                         //                                      backoutOnFailure = "true"
447                         //                              }
448                         //                      }
449                                                 //failIfExists - optional
450
451                         String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest")
452                         String productFamilyId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.productFamilyId")
453                         execution.setVariable("productFamilyId", productFamilyId)
454                         utils.log("DEBUG","productFamilyId: "+ productFamilyId, isDebugEnabled)
455
456                         JSONArray vnfList = execution.getVariable("vnfList")
457
458                         Integer vnfsCreatedCount = execution.getVariable("CREVAS_VnfsCreatedCount")
459                         String vnfModelInfoString = null;
460                         
461                         if (vnfList != null && vnfList.length() > 0 ) {
462                                 utils.log("DEBUG", "getting model info for vnf # " + vnfsCreatedCount, isDebugEnabled)
463                                 JSONObject vnfModelInfo1 = vnfList.getJSONObject(0).getJSONObject("modelInfo")
464                                 utils.log("DEBUG", "got 0 ", isDebugEnabled)
465                                 JSONObject vnfModelInfo = vnfList.getJSONObject(vnfsCreatedCount.intValue()).getJSONObject("modelInfo")
466                                 vnfModelInfoString = vnfModelInfo.toString()
467                         } else {
468                                 //TODO: vnfList does not contain data. Need to investigate why ... . Fro VIPR use model stored
469                                 vnfModelInfoString = execution.getVariable("vnfModelInfo")
470                         }
471                                                         
472                         utils.log("DEBUG", " vnfModelInfoString :" + vnfModelInfoString, isDebugEnabled)
473                         
474                         // extract cloud configuration
475                         String lcpCloudRegionId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.lcpCloudRegionId")
476                         execution.setVariable("lcpCloudRegionId", lcpCloudRegionId)
477                         utils.log("DEBUG","lcpCloudRegionId: "+ lcpCloudRegionId, isDebugEnabled)
478                         String tenantId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.tenantId")
479                         execution.setVariable("tenantId", tenantId)
480                         utils.log("DEBUG","tenantId: "+ tenantId, isDebugEnabled)
481                                                 
482                         String sdncVersion = execution.getVariable("sdncVersion")
483                         utils.log("DEBUG","sdncVersion: "+ sdncVersion, isDebugEnabled)
484
485                         utils.log("DEBUG", " ***** Completed prepareVnfAndModulesCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
486                 } catch (Exception ex) {
487                         // try error in method block
488                         String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareVnfAndModulesCreate() - " + ex.getMessage()
489                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
490                 }
491          }
492
493         // *******************************
494         //     Validate Vnf request Section -> increment count
495         // *******************************
496         public void validateVnfCreate (Execution execution) {
497                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
498
499                 try {
500                         utils.log("DEBUG", " ***** Inside validateVnfCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
501
502                         Integer vnfsCreatedCount = execution.getVariable("CREVAS_VnfsCreatedCount")
503                         vnfsCreatedCount++
504                         
505                         execution.setVariable("CREVAS_VnfsCreatedCount", vnfsCreatedCount)
506                         
507                         utils.log("DEBUG", " ***** Completed validateVnfCreate of CreateGenericMacroServiceNetworkVnf ***** "+" vnf # "+vnfsCreatedCount, isDebugEnabled)
508                 } catch (Exception ex) {
509                         // try error in method block
510                         String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method validateVnfCreate() - " + ex.getMessage()
511                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
512                 }
513          }
514         
515         // *******************************
516         //     Validate Network request Section -> decrement count
517         // *******************************
518         public void validateNetworkRollback (Execution execution) {
519                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
520
521                 try {
522                         utils.log("DEBUG", " ***** Inside validateNetworkRollback of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
523
524                         Integer networksCreatedCount = execution.getVariable("CREVAS_NetworksCreatedCount")
525                         networksCreatedCount--
526                         
527                         execution.setVariable("CREVAS_NetworksCreatedCount", networksCreatedCount)
528                         
529                         execution.setVariable("DCRENI_rollbackData", execution.getVariable("DCRENI_rollbackData"+networksCreatedCount))
530                         
531                         utils.log("DEBUG", " ***** Completed validateNetworkRollback of CreateGenericMacroServiceNetworkVnf ***** "+" network # "+networksCreatedCount, isDebugEnabled)
532                 } catch (Exception ex) {
533                         // try error in method block
534                         String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method validateNetworkRollback() - " + ex.getMessage()
535                         //exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
536                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
537                         execution.setVariable("CREVAS_NetworksCreatedCount", 0)
538                         utils.log("ERROR", exceptionMessage, true)
539                 }
540          }
541         // *******************************
542         //     Build DB request Section
543         // *******************************
544 //      public void prepareDBRequest (Execution execution) {
545 //              def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
546 //
547 //              try {
548 //                      utils.log("DEBUG", " ***** Inside prepareDBRequest of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
549 //
550 //                      String requestId = execution.getVariable("CREVAS_requestId")
551 //                      String statusMessage = "vIPR ATM Service Instance successfully created."
552 //                      String serviceInstanceId = execution.getVariable("CREVAS_serviceInstanceId")
553 //
554 //                      //TODO - verify the format for Service Instance Create,
555 //                      String dbRequest =
556 //                                      """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
557 //                                              <soapenv:Header/>
558 //                                              <soapenv:Body>
559 //                                                      <ns:updateInfraRequest xmlns:ns="http://org.openecomp.mso/requestsdb">
560 //                                                              <requestId>${requestId}</requestId>
561 //                                                              <lastModifiedBy>BPMN</lastModifiedBy>
562 //                                                              <statusMessage>${statusMessage}</statusMessage>
563 //                                                              <responseBody></responseBody>
564 //                                                              <requestStatus>COMPLETED</requestStatus>
565 //                                                              <progress>100</progress>
566 //                                                              <vnfOutputs/>
567 //                                                              <serviceInstanceId>${serviceInstanceId}</serviceInstanceId>
568 //                                                      </ns:updateInfraRequest>
569 //                                                 </soapenv:Body>
570 //                                         </soapenv:Envelope>"""
571 //
572 //                 String buildDeleteDBRequestAsString = utils.formatXml(dbRequest)
573 //                 execution.setVariable("CREVAS_createDBRequest", buildDeleteDBRequestAsString)
574 //                 utils.logAudit(buildDeleteDBRequestAsString)
575 //
576 //                 utils.log("DEBUG", " ***** Completed prepareDBRequest of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
577 //              } catch (Exception ex) {
578 //                      // try error in method block
579 //                      String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage()
580 //                      exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
581 //
582 //              }
583 //
584 //       }
585
586
587         // *****************************************
588         //     Prepare Completion request Section
589         // *****************************************
590         public void postProcessResponse (Execution execution) {
591                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
592
593                 utils.log("DEBUG", " ***** Inside postProcessResponse of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
594
595                 try {
596                         String source = execution.getVariable("source")
597                         String requestId = execution.getVariable("mso-request-id")
598                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
599
600                         String msoCompletionRequest =
601                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
602                                                                         xmlns:ns="http://org.openecomp/mso/request/types/v1">
603                                                         <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
604                                                                 <request-id>${requestId}</request-id>
605                                                                 <action>CREATE</action>
606                                                                 <source>${source}</source>
607                                                         </request-info>
608                                                         <status-message>Service Instance has been created successfully via macro orchestration</status-message>
609                                                         <serviceInstanceId>${serviceInstanceId}</serviceInstanceId>
610                                                         <mso-bpel-name>BPMN macro create</mso-bpel-name>
611                                                 </aetgt:MsoCompletionRequest>"""
612
613                         // Format Response
614                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
615
616                         utils.logAudit(xmlMsoCompletionRequest)
617                         execution.setVariable("CREVAS_Success", true)
618                         execution.setVariable("CREVAS_CompleteMsoProcessRequest", xmlMsoCompletionRequest)
619                         utils.log("DEBUG", " SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
620                 } catch (BpmnError e) {
621                         throw e;
622                 } catch (Exception ex) {
623                         // try error in method block
624                         String exceptionMessage = "Bpmn error encountered in CreateServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage()
625                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
626                 }
627         }
628
629         public void preProcessRollback (Execution execution) {
630                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
631                 utils.log("DEBUG"," ***** preProcessRollback of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
632                 try {
633                         
634                         Object workflowException = execution.getVariable("WorkflowException");
635
636                         if (workflowException instanceof WorkflowException) {
637                                 utils.log("DEBUG", "Prev workflowException: " + workflowException.getErrorMessage(), isDebugEnabled)
638                                 execution.setVariable("prevWorkflowException", workflowException);
639                                 //execution.setVariable("WorkflowException", null);
640                         }
641                 } catch (BpmnError e) {
642                         utils.log("DEBUG", "BPMN Error during preProcessRollback", isDebugEnabled)
643                 } catch(Exception ex) {
644                         String msg = "Exception in preProcessRollback. " + ex.getMessage()
645                         utils.log("DEBUG", msg, isDebugEnabled)
646                 }
647                 utils.log("DEBUG"," *** Exit preProcessRollback of CreateGenericMacroServiceNetworkVnf *** ", isDebugEnabled)
648         }
649
650         public void postProcessRollback (Execution execution) {
651                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
652                 utils.log("DEBUG"," ***** postProcessRollback of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled)
653                 String msg = ""
654                 try {
655                         Object workflowException = execution.getVariable("prevWorkflowException");
656                         if (workflowException instanceof WorkflowException) {
657                                 utils.log("DEBUG", "Setting prevException to WorkflowException: ", isDebugEnabled)
658                                 execution.setVariable("WorkflowException", workflowException);
659                         }
660                 } catch (BpmnError b) {
661                         utils.log("DEBUG", "BPMN Error during postProcessRollback", isDebugEnabled)
662                         throw b;
663                 } catch(Exception ex) {
664                         msg = "Exception in postProcessRollback. " + ex.getMessage()
665                         utils.log("DEBUG", msg, isDebugEnabled)
666                 }
667                 utils.log("DEBUG"," *** Exit postProcessRollback of CreateGenericMacroServiceNetworkVnf *** ", isDebugEnabled)
668         }
669
670         public void prepareFalloutRequest(Execution execution){
671                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
672
673                 utils.log("DEBUG", " *** STARTED CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process *** ", isDebugEnabled)
674
675                 try {
676                         WorkflowException wfex = execution.getVariable("WorkflowException")
677                         utils.log("DEBUG", " Incoming Workflow Exception: " + wfex.toString(), isDebugEnabled)
678                         String requestInfo = execution.getVariable("CREVAS_requestInfo")
679                         utils.log("DEBUG", " Incoming Request Info: " + requestInfo, isDebugEnabled)
680                         
681                         //TODO. hmmm. there is no way to UPDATE error message.
682 //                      String errorMessage = wfex.getErrorMessage()
683 //                      boolean successIndicator = execution.getVariable("DCRESI_rollbackSuccessful")
684 //                      if (successIndicator){
685 //                              errorMessage = errorMessage + ". Rollback successful."
686 //                      } else {
687 //                              errorMessage = errorMessage + ". Rollback not completed."
688 //                      }
689                         
690                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
691
692                         execution.setVariable("CREVAS_falloutRequest", falloutRequest)
693
694                 } catch (Exception ex) {
695                         utils.log("DEBUG", "Error Occured in CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process " + ex.getMessage(), isDebugEnabled)
696                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process")
697                 }
698                 utils.log("DEBUG", "*** COMPLETED CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process ***", isDebugEnabled)
699         }
700
701
702         public void sendSyncError (Execution execution) {
703                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
704                 execution.setVariable("prefix", Prefix)
705
706                 utils.log("DEBUG", " ***** Inside sendSyncError() of CreateServiceInstanceInfra ***** ", isDebugEnabled)
707
708                 try {
709                         String errorMessage = ""
710                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
711                                 WorkflowException wfe = execution.getVariable("WorkflowException")
712                                 errorMessage = wfe.getErrorMessage()
713                         } else {
714                                 errorMessage = "Sending Sync Error."
715                         }
716
717                         String buildworkflowException =
718                                 """<aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
719                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
720                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
721                                    </aetgt:WorkflowException>"""
722
723                         utils.logAudit(buildworkflowException)
724                         sendWorkflowResponse(execution, 500, buildworkflowException)
725                 } catch (Exception ex) {
726                         utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled)
727                 }
728         }
729
730         public void processJavaException(Execution execution){
731                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
732                 execution.setVariable("prefix",Prefix)
733                 try{
734                         utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled)
735                         utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled)
736                         utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled)
737                         execution.setVariable("CRESI_unexpectedError", "Caught a Java Lang Exception")  // Adding this line temporarily until this flows error handling gets updated
738                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception")
739                 }catch(BpmnError b){
740                         utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugEnabled)
741                         throw b
742                 }catch(Exception e){
743                         utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled)
744                         execution.setVariable("CRESI_unexpectedError", "Exception in processJavaException method")  // Adding this line temporarily until this flows error handling gets updated
745                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method")
746                 }
747                 utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled)
748         }
749 }