Initial OpenECOMP MSO commit
[so.git] / bpmn / MSOGammaBPMN / src / main / groovy / com / att / bpm / scripts / CreateNetworkInstanceInfra.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 com.att.bpm.scripts;
22
23 import groovy.xml.XmlUtil
24 import groovy.json.*
25
26 import org.openecomp.mso.bpmn.core.WorkflowException
27 import org.openecomp.mso.bpmn.core.json.JsonUtils;
28 import org.openecomp.mso.rest.APIResponse
29 import org.openecomp.mso.rest.RESTClient
30 import org.openecomp.mso.rest.RESTConfig
31
32 import java.util.UUID;
33
34 import org.camunda.bpm.engine.delegate.BpmnError
35 import org.camunda.bpm.engine.runtime.Execution
36 import org.apache.commons.lang3.*
37 import org.apache.commons.codec.binary.Base64;
38 import org.springframework.web.util.UriUtils
39
40 /**
41  * This groovy class supports the <class>CreateNetworkInstanceInfra.bpmn</class> process.
42  *
43  */
44 public class CreateNetworkInstanceInfra extends AbstractServiceTaskProcessor {
45         String Prefix="CRENWKI_"
46         ExceptionUtil exceptionUtil = new ExceptionUtil()
47         JsonUtils jsonUtil = new JsonUtils()
48         VidUtils vidUtils = new VidUtils(this)
49         NetworkUtils networkUtils = new NetworkUtils()
50         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
51
52         /**
53          * This method is executed during the preProcessRequest task of the <class>CreateNetworkInstanceInfra.bpmn</class> process.
54          * @param execution
55          */
56         public InitializeProcessVariables(Execution execution){
57                 /* Initialize all the process variables in this block */
58
59                 execution.setVariable("CRENWKI_messageId", "")
60                 execution.setVariable("BasicAuthHeaderValuePO", "")
61                 execution.setVariable("BasicAuthHeaderValueSDNC", "")
62                 execution.setVariable("CRENWKI_CreateNetworkInstanceInfraJsonRequest", "")
63                 execution.setVariable("CRENWKI_networkRequest", "")
64                 execution.setVariable("CRENWKI_networkInputs", "")
65                 execution.setVariable("CRENWKI_networkOutputs", "")
66                 execution.setVariable("CRENWKI_requestId", "")
67                 execution.setVariable("CRENWKI_source", "")
68
69                 execution.setVariable("CRENWKI_CompleteMsoProcessRequest", "")
70                 execution.setVariable("CRENWKI_FalloutHandlerRequest", "")
71                 execution.setVariable("CRENWKI_isSilentSuccess", false)
72                 execution.setVariable("CRENWKI_isPONR", false)    // Point-of-no-return, means, rollback is not needed
73
74                 // query Service Instance
75                 execution.setVariable("CRENWKI_serviceInstanceId","")
76                 
77                 // AAI query Name
78                 execution.setVariable("CRENWKI_queryNameAAIRequest","")
79                 execution.setVariable("CRENWKI_queryNameAAIResponse", "")
80                 execution.setVariable("CRENWKI_aaiNameReturnCode", "")
81                 execution.setVariable("CRENWKI_isAAIqueryNameGood", false)
82
83                 // AAI query Cloud Region
84                 execution.setVariable("CRENWKI_queryCloudRegionRequest","")
85                 execution.setVariable("CRENWKI_queryCloudRegionReturnCode","")
86                 execution.setVariable("CRENWKI_queryCloudRegionResponse","")
87                 execution.setVariable("CRENWKI_cloudRegionPo","")
88                 execution.setVariable("CRENWKI_cloudRegionSdnc","")
89                 execution.setVariable("CRENWKI_isCloudRegionGood", false)
90
91                 // AAI query Id
92                 execution.setVariable("CRENWKI_queryIdAAIRequest","")
93                 execution.setVariable("CRENWKI_queryIdAAIResponse", "")
94                 execution.setVariable("CRENWKI_aaiIdReturnCode", "")
95
96                 // AAI query vpn binding
97                 execution.setVariable("CRENWKI_queryVpnBindingAAIRequest","")
98                 execution.setVariable("CRENWKI_queryVpnBindingAAIResponse", "")
99                 execution.setVariable("CRENWKI_aaiQqueryVpnBindingReturnCode", "")
100                 execution.setVariable("CRENWKI_vpnBindings", null)
101                 execution.setVariable("CRENWKI_vpnCount", 0)
102                 execution.setVariable("CRENWKI_routeCollection", "")
103
104                 // AAI query network policy
105                 execution.setVariable("CRENWKI_queryNetworkPolicyAAIRequest","")
106                 execution.setVariable("CRENWKI_queryNetworkPolicyAAIResponse", "")
107                 execution.setVariable("CRENWKI_aaiQqueryNetworkPolicyReturnCode", "")
108                 execution.setVariable("CRENWKI_networkPolicyUriList", null)
109                 execution.setVariable("CRENWKI_networkPolicyCount", 0)
110                 execution.setVariable("CRENWKI_networkCollection", "")
111
112                 // AAI query route table reference
113                 execution.setVariable("CRENWKI_queryNetworkTableRefAAIRequest","")
114                 execution.setVariable("CRENWKI_queryNetworkTableRefAAIResponse", "")
115                 execution.setVariable("CRENWKI_aaiQqueryNetworkTableRefReturnCode", "")
116                 execution.setVariable("CRENWKI_networkTableRefUriList", null)
117                 execution.setVariable("CRENWKI_networkTableRefCount", 0)
118                 execution.setVariable("CRENWKI_tableRefCollection", "")
119
120                 // AAI requery Id
121                 execution.setVariable("CRENWKI_requeryIdAAIRequest","")
122                 execution.setVariable("CRENWKI_requeryIdAAIResponse", "")
123                 execution.setVariable("CRENWKI_aaiRequeryIdReturnCode", "")
124
125                 // AAI update contrail
126                 execution.setVariable("CRENWKI_updateContrailAAIUrlRequest","")
127                 execution.setVariable("CRENWKI_updateContrailAAIPayloadRequest","")
128                 execution.setVariable("CRENWKI_updateContrailAAIResponse", "")
129                 execution.setVariable("CRENWKI_aaiUpdateContrailReturnCode", "")
130
131                 execution.setVariable("CRENWKI_createNetworkRequest", "")
132                 execution.setVariable("CRENWKI_createNetworkResponse", "")
133                 execution.setVariable("CRENWKI_rollbackNetworkRequest", "")
134                 execution.setVariable("CRENWKI_rollbackNetworkResponse", "")
135                 execution.setVariable("CRENWKI_networkReturnCode", "")
136                 execution.setVariable("CRENWKI_rollbackNetworkReturnCode", "")
137                 execution.setVariable("CRENWKI_isNetworkRollbackNeeded", false)
138
139                 execution.setVariable("CRENWKI_assignSDNCRequest", "")
140                 execution.setVariable("CRENWKI_assignSDNCResponse", "")
141                 execution.setVariable("CRENWKI_rollbackSDNCRequest", "")
142                 execution.setVariable("CRENWKI_rollbackSDNCResponse", "")
143                 execution.setVariable("CRENWKI_sdncReturnCode", "")
144                 execution.setVariable("CRENWKI_rollbackSDNCReturnCode", "")
145                 execution.setVariable("CRENWKI_isSdncRollbackNeeded", false)
146                 execution.setVariable("CRENWKI_sdncResponseSuccess", false)
147
148                 execution.setVariable("CRENWKI_createDBRequest", "")
149                 execution.setVariable("CRENWKI_createDBResponse", "")
150                 execution.setVariable("CRENWKI_dbReturnCode", "")
151
152                 execution.setVariable("CRENWKI_orchestrationStatus", "")
153                 execution.setVariable("CRENWKI_isVnfBindingPresent", false)
154                 execution.setVariable("CRENWKI_Success", false)
155                 execution.setVariable("GENGS_type", "service-instance") // Setting for Generic Sub Flow use
156
157
158         }
159
160         // **************************************************
161         //     Pre or Prepare Request Section
162         // **************************************************
163         /**
164          * This method is executed during the preProcessRequest task of the <class>CreateNetworkInstanceInfra.bpmn</class> process.
165          * @param execution
166          */
167         public void preProcessRequest (Execution execution) {
168                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
169                 execution.setVariable("prefix",Prefix)
170
171                 utils.log("DEBUG", " ***** Inside preProcessRequest CreateNetworkInstanceInfra Request ***** ", isDebugEnabled)
172
173                 // initialize flow variables
174                 InitializeProcessVariables(execution)
175
176                 // get Incoming request & validate json format
177                 String createNetworkJsonIncoming = execution.getVariable("bpmnRequest")
178                 utils.logAudit(createNetworkJsonIncoming)
179                 try {
180                         def prettyJson = JsonOutput.prettyPrint(createNetworkJsonIncoming.toString())
181                         utils.log("DEBUG", " Incoming message formatted . . . : " + '\n' + prettyJson, isDebugEnabled)
182
183                 } catch (Exception ex) {
184                         String dataErrorMessage = " Invalid json format Request - " + ex.getMessage()
185                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
186                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
187                 }
188
189                 // PO Authorization Info / headers Authorization=
190                 String basicAuthValuePO = execution.getVariable("URN_mso_adapters_po_auth")
191                 utils.log("DEBUG", " Obtained BasicAuth userid password for PO/SDNC adapter: " + basicAuthValuePO, isDebugEnabled)
192                 try {
193                         def encodedString = utils.getBasicAuth(basicAuthValuePO, execution.getVariable("URN_mso_msoKey"))
194                         execution.setVariable("BasicAuthHeaderValuePO",encodedString)
195                         execution.setVariable("BasicAuthHeaderValueSDNC", encodedString)
196
197                 } catch (IOException ex) {
198                         String dataErrorMessage = " Unable to encode PO/SDNC user/password string - " + ex.getMessage()
199                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
200                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
201                 }
202
203                 try {
204
205                         execution.setVariable("CRENWKI_CreateNetworkInstanceInfraJsonRequest", createNetworkJsonIncoming)
206
207                         // input should be empty, use generated 'network-id' from SDNC/AAI
208                         execution.setVariable("networkId", "")
209
210                         // recreate the xml network-request
211                         String networkRequest =  vidUtils.createXmlNetworkRequestInfra(execution, createNetworkJsonIncoming)
212                         execution.setVariable("CRENWKI_networkRequest", networkRequest)
213                         utils.log("DEBUG", " network-request - " + '\n' + networkRequest, isDebugEnabled)
214
215                         String networkInputs = utils.getNodeXml(networkRequest, "network-inputs", false).replace("tag0:","").replace(":tag0","")
216                         execution.setVariable("CRENWKI_networkInputs", networkInputs)
217                         utils.log("DEBUG", " networkInputs - " + '\n' + networkInputs, isDebugEnabled)
218
219                         String netId = utils.getNodeText1(networkRequest, "network-id")
220                         String netName = utils.getNodeText1(networkRequest, "network-name")
221                         String networkOutputs =
222                            """<network-outputs>
223                    <network-id>${netId}</network-id>
224                    <network-name>${netName}</network-name>
225                  </network-outputs>"""
226                         execution.setVariable("CRENWKI_networkOutputs", networkOutputs)
227                         utils.log("DEBUG", " networkOutputs - " + '\n' + networkOutputs, isDebugEnabled)
228
229                         String requestId = execution.getVariable("att-mso-request-id")
230                         if (requestId == null || requestId == "") {
231                                 requestId = execution.getVariable("requestId")
232                         }
233                         execution.setVariable("CRENWKI_requestId", requestId)
234                         execution.setVariable("CRENWKI_source", utils.getNodeText1(networkRequest, "source"))
235
236                         // prepare messageId
237                         String messageId = execution.getVariable("CRENWKI_messageId")  // for testing
238                         if (messageId == null || messageId == "") {
239                                 messageId = UUID.randomUUID()
240                                 utils.log("DEBUG", " CRENWKI_messageId, random generated: " + messageId, isDebugEnabled)
241                         } else {
242                                 utils.log("DEBUG", " CRENWKI_messageId, pre-assigned: " + messageId, isDebugEnabled)
243                         }
244                         execution.setVariable("CRENWKI_messageId", messageId)
245
246                         // validate 'backout-on-failure' to override 'URN_mso_rollback'
247                         boolean rollbackEnabled = networkUtils.isRollbackEnabled(execution, networkRequest)
248                         execution.setVariable("CRENWKI_rollbackEnabled", rollbackEnabled)
249
250                         String instanceName = ""
251                         if (utils.nodeExists(networkRequest, "network-name")) {
252                                 instanceName = utils.getNodeText1(networkRequest, "network-name")
253                                 if (instanceName == 'null' || instanceName == "") {
254                                         sendSyncError(execution)
255                                         // missing value of network-name
256                                         String dataErrorMessage = "requestDetails has missing 'network-name' value/element."
257                                         utils.log("DEBUG", " Invalid Request - " + dataErrorMessage, isDebugEnabled)
258                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
259
260                                 }
261                         }
262
263                         String lcpCloudRegion = ""
264                         if (utils.nodeExists(networkRequest, "aic-cloud-region")) {
265                                 lcpCloudRegion = utils.getNodeText1(networkRequest, "aic-cloud-region")
266                             if ((lcpCloudRegion == 'null') || (lcpCloudRegion == "")) {
267                                         sendSyncError(execution)
268                                         String dataErrorMessage = "requestDetails has missing 'aic-cloud-region' value/element."
269                                         utils.log("DEBUG", " Invalid Request - " + dataErrorMessage, isDebugEnabled)
270                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
271                                 }
272                         }
273
274                         String serviceInstanceId = ""
275                         if (utils.nodeExists(networkRequest, "service-instance-id")) {
276                                 serviceInstanceId = utils.getNodeText1(networkRequest, "service-instance-id")
277                                 if ((serviceInstanceId == 'null') || (lcpCloudRegion == "")) {
278                                         sendSyncError(execution)
279                                         String dataErrorMessage = "Variable 'serviceInstanceId' value/element is missing."
280                                         utils.log("DEBUG", " Invalid Request - " + dataErrorMessage, isDebugEnabled)
281                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
282                                 }
283                         }
284
285                         execution.setVariable("CRENWKI_serviceInstanceId", serviceInstanceId)
286
287                 } catch (BpmnError e) {
288                         throw e;
289
290                 } catch (Exception ex){
291                         sendSyncError(execution)
292                          // caught exception
293                         String exceptionMessage = "Exception Encountered in CreateNetworkInstanceInfra, PreProcessRequest() - " + ex.getMessage()
294                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
295                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
296
297                 }
298         }
299
300         public void sendSyncResponse (Execution execution) {
301                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
302                 execution.setVariable("prefix",Prefix)
303
304                 utils.log("DEBUG", " ***** Inside sendSyncResponse of CreateNetworkInstanceInfra ***** ", isDebugEnabled)
305
306                 try {
307                         String requestId = execution.getVariable("att-mso-request-id")
308
309                         // RESTResponse (for API Handler (APIH) Reply Task)
310                         String createNetworkRestRequest = """{"requestReferences":{"instanceId":"","requestId":"${requestId}"}}""".trim()
311
312                         utils.log("DEBUG", " sendSyncResponse to APIH - " + "\n" + createNetworkRestRequest, isDebugEnabled)
313                         sendWorkflowResponse(execution, 202, createNetworkRestRequest)
314
315                 } catch (Exception ex) {
316                         String exceptionMessage = "Bpmn error encountered in CreateNetworkInstanceInfra flow. sendSyncResponse() - " + ex.getMessage()
317                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
318                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
319                 }
320
321         }
322
323
324         public void callRESTQueryAAINetworkName (Execution execution) {
325                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
326                 execution.setVariable("prefix",Prefix)
327
328                 utils.log("DEBUG", " ***** Inside callRESTQueryAAINetworkName of CreateNetworkInstanceInfra ***** " , isDebugEnabled)
329
330                 // get variables
331                 String networkInputs  = execution.getVariable("CRENWKI_networkInputs")
332                 String networkName   = utils.getNodeText1(networkInputs, "network-name")
333                 networkName = UriUtils.encode(networkName,"UTF-8")
334                 String messageId = execution.getVariable("CRENWKI_messageId")
335
336                 // Prepare AA&I url with network-name
337                 String aai_endpoint = execution.getVariable("URN_aai_endpoint")
338                 AaiUtil aaiUriUtil = new AaiUtil(this)
339                 String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution)
340                 String queryAAINameRequest = "${aai_endpoint}${aai_uri}" + "?network-name=" + networkName
341                 utils.logAudit(queryAAINameRequest)
342                 execution.setVariable("CRENWKI_queryNameAAIRequest", queryAAINameRequest)
343                 utils.log("DEBUG", " CRENWKI_queryNameAAIRequest - " + "\n" + queryAAINameRequest, isDebugEnabled)
344
345                 String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
346                 RESTConfig config = new RESTConfig(queryAAINameRequest);
347
348                 try {
349                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
350                                                                                                           .addHeader("X-FromAppId", "MSO")
351                                                                                                           .addHeader("Content-Type", "application/xml")
352                                                                                                           .addHeader("Accept","application/xml");
353                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
354                                 client.addAuthorizationHeader(basicAuthCred)
355                         }
356                         APIResponse response = client.get()
357                         String returnCode = response.getStatusCode()
358                         execution.setVariable("CRENWKI_aaiNameReturnCode", returnCode)
359                         utils.log("DEBUG", " ***** AAI Query Name Response Code  : " + returnCode, isDebugEnabled)
360
361                         String aaiResponseAsString = response.getResponseBodyAsString()
362                         utils.log("DEBUG", " ***** AAI Query Name Response : " +'\n'+ aaiResponseAsString, isDebugEnabled)
363
364                         if (returnCode=='200') {
365                                 utils.logAudit(aaiResponseAsString)
366                                 execution.setVariable("CRENWKI_queryNameAAIResponse", aaiResponseAsString)
367                                 execution.setVariable("CRENWKI_isAAIqueryNameGood", true)
368                                 String orchestrationStatus = ""
369                                 try {
370                                         // response is NOT empty
371                                         orchestrationStatus = utils.getNodeText1(aaiResponseAsString, "orchestration-status")
372                                         execution.setVariable("CRENWKI_orchestrationStatus", orchestrationStatus.toUpperCase())
373                                         utils.log("DEBUG", " CRENWKI_orchestrationStatus - " + orchestrationStatus.toUpperCase(), isDebugEnabled)
374                                 } catch (Exception ex) {
375                                     // response is empty
376                                         execution.setVariable("CRENWKI_orchestrationStatus", orchestrationStatus)
377                                         utils.log("DEBUG", " CRENWKI_orchestrationStatus - " + orchestrationStatus, isDebugEnabled)
378                                 }
379
380                         } else {
381                             if (returnCode=='404') {
382                                         utils.log("DEBUG", " QueryAAINetworkName return code = '404' (Not Found).  Proceed with the Create !!! ", isDebugEnabled)
383
384                             } else {
385                                 // aai all errors
386                                         String dataErrorMessage = "Unexpected Error Response from QueryAAINetworkName - " + returnCode
387                                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
388                                         exceptionUtil.buildWorkflowException(execution, 2500, dataErrorMessage)
389
390                       }
391
392                         }
393
394                         utils.log("DEBUG", " AAI call, CRENWKI_isAAIqueryNameGood? : " + execution.getVariable("CRENWKI_isAAIqueryNameGood"), isDebugEnabled)
395
396
397                 } catch (Exception ex) {
398                         // try error
399                         String exceptionMessage = "Bpmn error encountered in CreateNetworkInstanceInfra flow - callRESTQueryAAINetworkName() -  " + ex.getMessage()
400                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
401                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
402
403                 }
404
405         }
406
407         public void callRESTQueryAAICloudRegion (Execution execution) {
408                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
409                 execution.setVariable("prefix", Prefix)
410
411                 utils.log("DEBUG", " ***** Inside callRESTQueryAAICloudRegion of CreateNetworkInstanceInfra ***** " , isDebugEnabled)
412
413                 try {
414                         String networkInputs  = execution.getVariable("CRENWKI_networkInputs")
415                         String cloudRegion = utils.getNodeText1(networkInputs, "aic-cloud-region")
416                         cloudRegion = UriUtils.encode(cloudRegion,"UTF-8")
417
418                         // Prepare AA&I url
419                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
420                         AaiUtil aaiUtil = new AaiUtil(this)
421                         String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution)
422                         String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion
423                         utils.logAudit(queryCloudRegionRequest)
424                         execution.setVariable("CRENWKI_queryCloudRegionRequest", queryCloudRegionRequest)
425                         utils.log("DEBUG", " CRENWKI_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest, isDebugEnabled)
426
427                         String cloudRegionPo = aaiUtil.getAAICloudReqion(execution,  queryCloudRegionRequest, "PO", cloudRegion)
428                         String cloudRegionSdnc = aaiUtil.getAAICloudReqion(execution,  queryCloudRegionRequest, "SDNC", cloudRegion)
429
430                         if ((cloudRegionPo != "ERROR") && (cloudRegionSdnc != "ERROR")) {
431                                 execution.setVariable("CRENWKI_cloudRegionPo", cloudRegionPo)
432                                 execution.setVariable("CRENWKI_cloudRegionSdnc", cloudRegionSdnc)
433                                 execution.setVariable("CRENWKI_isCloudRegionGood", true)
434
435                         } else {
436                             String dataErrorMessage = "QueryAAICloudRegion Unsuccessful. Return Code: " + execution.getVariable("CRENWKI_queryCloudRegionReturnCode")
437                             utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
438                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
439
440                         }
441
442                         utils.log("DEBUG", " is Cloud Region Good: " + execution.getVariable("CRENWKI_isCloudRegionGood"), isDebugEnabled)
443
444                 } catch (BpmnError e) {
445                         throw e;
446
447                 } catch (Exception ex) {
448                         // try error
449                         String exceptionMessage = "Bpmn error encountered in CreateNetworkInstanceInfra flow - callRESTQueryAAICloudRegion() - " + ex.getMessage()
450                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
451                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
452
453                 }
454
455         }
456
457         public void callRESTQueryAAINetworkId(Execution execution) {
458                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
459                 execution.setVariable("prefix", Prefix)
460
461                 utils.log("DEBUG", " ***** Inside callRESTQueryAAINetworkId of CreateNetworkInstanceInfra ***** " , isDebugEnabled)
462
463                 try {
464                         // get variables
465                         String assignSDNCResponse = execution.getVariable("CRENWKI_assignSDNCResponse")
466                         String networkId   = utils.getNodeText1(assignSDNCResponse, "network-id")
467                         networkId = UriUtils.encode(networkId,"UTF-8")
468                         String messageId = execution.getVariable("CRENWKI_messageId")
469
470                         // Prepare AA&I url
471                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
472                         AaiUtil aaiUriUtil = new AaiUtil(this)
473                         String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution)
474                         String queryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId
475                         utils.logAudit(queryIdAAIRequest)
476                         execution.setVariable("CRENWKI_queryIdAAIRequest", queryIdAAIRequest)
477                         utils.log("DEBUG", " CRENWKI_queryIdAAIRequest - " + "\n" + queryIdAAIRequest, isDebugEnabled)
478
479                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
480
481                         RESTConfig config = new RESTConfig(queryIdAAIRequest);
482                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
483                                                                                                           .addHeader("X-FromAppId", "MSO")
484                                                                                                           .addHeader("Content-Type", "application/xml")
485                                                                                                           .addHeader("Accept","application/xml");
486                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
487                                 client.addAuthorizationHeader(basicAuthCred)
488                         }
489                         APIResponse response = client.get()
490                         String returnCode = response.getStatusCode()
491                         execution.setVariable("CRENWKI_aaiIdReturnCode", returnCode)
492
493                         utils.log("DEBUG", " ***** AAI Response Code  : " + returnCode, isDebugEnabled)
494
495                         String aaiResponseAsString = response.getResponseBodyAsString()
496
497                         if (returnCode=='200') {
498                                 utils.logAudit(aaiResponseAsString)
499                                 execution.setVariable("CRENWKI_queryIdAAIResponse", aaiResponseAsString)
500                                 utils.log("DEBUG", " QueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString, isDebugEnabled)
501
502                         } else {
503                                 if (returnCode=='404') {
504                                         String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)."
505                                         utils.log("DEBUG", " AAI Query Failed. " + dataErrorMessage, isDebugEnabled)
506                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
507
508                                 } else {
509                                    if (aaiResponseAsString.contains("RESTFault")) {
510                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
511                                            execution.setVariable("WorkflowException", exceptionObject)
512                                            throw new BpmnError("MSOWorkflowException")
513
514                                    } else {
515                                                         // aai all errors
516                                                         String dataErrorMessage = "Unexpected Response from QueryAAINetworkId - " + returnCode
517                                                         utils.log("DEBUG", "Unexpected Response from QueryAAINetworkId - " + dataErrorMessage, isDebugEnabled)
518                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
519
520                                   }
521                                 }
522                         }
523
524                 } catch (BpmnError e) {
525                         throw e;
526
527                 } catch (Exception ex) {
528                         String exceptionMessage = "Bpmn error encountered in CreateNetworkInstanceInfra flow. callRESTQueryAAINetworkId() - " + ex.getMessage()
529                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
530                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
531
532                 }
533
534         }
535
536         public void callRESTReQueryAAINetworkId(Execution execution) {
537                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
538                 execution.setVariable("prefix", Prefix)
539
540                 utils.log("DEBUG", " ***** Inside callRESTReQueryAAINetworkId of CreateNetworkInstanceInfra ***** " , isDebugEnabled)
541
542                 try {
543                         // get variables
544                         String networkId   = utils.getNodeText1(execution.getVariable("CRENWKI_assignSDNCResponse"), "network-id")
545                         networkId = UriUtils.encode(networkId,"UTF-8")
546                         String messageId = execution.getVariable("CRENWKI_messageId")
547
548                         // Prepare AA&I url
549                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
550                         AaiUtil aaiUriUtil = new AaiUtil(this)
551                         String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution)
552                         String requeryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId
553                         utils.logAudit(requeryIdAAIRequest)
554                         execution.setVariable("CRENWKI_requeryIdAAIRequest", requeryIdAAIRequest)
555                         utils.log("DEBUG", " CRENWKI_requeryIdAAIRequest - " + "\n" + requeryIdAAIRequest, isDebugEnabled)
556
557                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
558
559                         RESTConfig config = new RESTConfig(requeryIdAAIRequest);
560                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
561                                                                                                           .addHeader("X-FromAppId", "MSO")
562                                                                                                           .addHeader("Content-Type", "application/xml")
563                                                                                                           .addHeader("Accept","application/xml");
564                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
565                                 client.addAuthorizationHeader(basicAuthCred)
566                         }
567                         APIResponse response = client.get()
568                         String returnCode = response.getStatusCode()
569                         execution.setVariable("CRENWKI_aaiRequeryIdReturnCode", returnCode)
570                         utils.log("DEBUG", " ***** AAI ReQuery Response Code  : " + returnCode, isDebugEnabled)
571
572                         String aaiResponseAsString = response.getResponseBodyAsString()
573
574                         if (returnCode=='200') {
575                                 utils.logAudit(aaiResponseAsString)
576                                 execution.setVariable("CRENWKI_requeryIdAAIResponse", aaiResponseAsString)
577                                 utils.log("DEBUG", " ReQueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString, isDebugEnabled)
578
579                                 String netId = utils.getNodeText1(aaiResponseAsString, "network-id")
580                                 String netName = utils.getNodeText1(aaiResponseAsString, "network-name")
581                                 String networkOutputs =
582                                    """<network-outputs>
583                    <network-id>${netId}</network-id>
584                    <network-name>${netName}</network-name>
585                  </network-outputs>"""
586                                 execution.setVariable("CRENWKI_networkOutputs", networkOutputs)
587                                 utils.log("DEBUG", " networkOutputs - " + '\n' + networkOutputs, isDebugEnabled)
588
589                         } else {
590                                 if (returnCode=='404') {
591                                         String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)."
592                                         utils.log("DEBUG", " AAI ReQuery Failed. - " + dataErrorMessage, isDebugEnabled)
593                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
594
595                                 } else {
596                                    if (aaiResponseAsString.contains("RESTFault")) {
597                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
598                                            execution.setVariable("WorkflowException", exceptionObject)
599                                            throw new BpmnError("MSOWorkflowException")
600
601                                            } else {
602                                                         // aai all errors
603                                                         String dataErrorMessage = "Unexpected Response from ReQueryAAINetworkId - " + returnCode
604                                                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
605                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
606
607                                         }
608                                 }
609                         }
610
611                 } catch (BpmnError e) {
612                         throw e;
613
614                 } catch (Exception ex) {
615                         String exceptionMessage = "Bpmn error encountered in CreateNetworkInstanceInfra flow. callRESTReQueryAAINetworkId() - " + ex.getMessage()
616                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
617                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
618
619                 }
620
621         }
622
623         public void callRESTQueryAAINetworkVpnBinding(Execution execution) {
624                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
625                 execution.setVariable("prefix", Prefix)
626
627                 utils.log("DEBUG", " ***** Inside callRESTQueryAAINetworkVpnBinding of CreateNetworkInstanceInfra ***** " , isDebugEnabled)
628
629                 try {
630
631                         // get variables
632                         String messageId = execution.getVariable("CRENWKI_messageId")
633                         String queryIdAAIResponse   = execution.getVariable("CRENWKI_queryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "")
634                         String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","")
635                         utils.log("DEBUG", " relationship - " + relationship, isDebugEnabled)
636
637                         // Check if Vnf Binding is present, then build a List of vnfBinding
638                         List vpnBindingUri = networkUtils.getVnfBindingObject(relationship)
639                         int vpnCount = vpnBindingUri.size()
640                         execution.setVariable("CRENWKI_vpnCount", vpnCount)
641                         utils.log("DEBUG", " CRENWKI_vpnCount - " + vpnCount, isDebugEnabled)
642
643                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
644                         AaiUtil aaiUriUtil = new AaiUtil(this)
645
646                         if (vpnCount > 0) {
647                                 execution.setVariable("CRENWKI_vpnBindings", vpnBindingUri)
648                                 utils.log("DEBUG", " vpnBindingUri List - " + vpnBindingUri, isDebugEnabled)
649
650                                 String routeTargets = ""
651                                 // AII loop call using list vpnBindings
652                                 for (i in 0..vpnBindingUri.size()-1) {
653
654                                         int counting = i+1
655
656                                         // prepare url using vpnBinding
657                                         String queryVpnBindingAAIRequest = ""
658                                         String aai_uri = aaiUriUtil.getNetworkVpnBindingUri(execution)
659
660                                         // Note: By default, the vpnBinding url is found in 'related-link' of the response,
661                                         //       so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping.
662                                         if (aai_uri == null || aai_uri == "") {
663                                                 // using value of 'related-link' from response
664                                                 if (vpnBindingUri[i].charAt(vpnBindingUri[i].length()-1) == '/') {
665                                                     queryVpnBindingAAIRequest = "${aai_endpoint}" + vpnBindingUri[i].substring(0, vpnBindingUri[i].length()-1)
666                                                 } else {
667                                                     queryVpnBindingAAIRequest = "${aai_endpoint}" + vpnBindingUri[i]
668                                                 }
669
670                                         } else {
671                                             // using uri value in URN mapping
672                                                 String vpnBindingId = vpnBindingUri[i].substring(vpnBindingUri[i].indexOf("/vpn-binding/")+13, vpnBindingUri[i].length())
673                                                 if (vpnBindingId.charAt(vpnBindingId.length()-1) == '/') {
674                                                         vpnBindingId = vpnBindingId.substring(0, vpnBindingId.length()-1)
675                                                 }
676                                             queryVpnBindingAAIRequest = "${aai_endpoint}${aai_uri}/" + vpnBindingId
677                                         }
678
679                                         utils.logAudit(queryVpnBindingAAIRequest)
680                                         execution.setVariable("CRENWKI_queryVpnBindingAAIRequest", queryVpnBindingAAIRequest)
681                                         utils.log("DEBUG", " CRENWKI_queryVpnBindingAAIRequest, , vpnBinding #" + counting + " : " + "\n" + queryVpnBindingAAIRequest, isDebugEnabled)
682
683                                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
684
685                                         RESTConfig config = new RESTConfig(queryVpnBindingAAIRequest);
686                                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
687                                                                                                                           .addHeader("X-FromAppId", "MSO")
688                                                                                                                           .addHeader("Content-Type", "application/xml")
689                                                                                                                           .addHeader("Accept","application/xml");
690                                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
691                                                 client.addAuthorizationHeader(basicAuthCred)
692                                         }
693                                         APIResponse response = client.get()
694                                         String returnCode = response.getStatusCode()
695                                         execution.setVariable("CRENWKI_aaiQqueryVpnBindingReturnCode", returnCode)
696                                         utils.log("DEBUG", " ***** AAI query vpn binding Response Code, vpnBinding #" + counting + " : " + returnCode, isDebugEnabled)
697
698                                         String aaiResponseAsString = response.getResponseBodyAsString()
699
700                                         if (returnCode=='200') {
701                                                 utils.logAudit(aaiResponseAsString)
702                                                 execution.setVariable("CRENWKI_queryVpnBindingAAIResponse", aaiResponseAsString)
703                                                 utils.log("DEBUG", " AAI Query Vpn Binding Success REST Response, , vpnBinding #" + counting + " : " + "\n" + aaiResponseAsString, isDebugEnabled)
704
705                                                 String routeTarget = ""
706                                                 if (utils.nodeExists(aaiResponseAsString, "global-route-target")) {
707                                                         routeTarget  = utils.getNodeText1(aaiResponseAsString, "global-route-target")
708                                                         routeTargets += "<routeTargets>" + routeTarget + "</routeTargets>" + '\n'
709                                                 }
710
711                                         } else {
712                                                 if (returnCode=='404') {
713                                                         String dataErrorMessage = "Response Error from AAINetworkVpnBinding is 404 (Not Found)."
714                                                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
715                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
716
717                                                 } else {
718                                                    if (aaiResponseAsString.contains("RESTFault")) {
719                                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
720                                                            execution.setVariable("WorkflowException", exceptionObject)
721                                                            throw new BpmnError("MSOWorkflowException")
722
723                                                            } else {
724                                                                         // aai all errors
725                                                                         String dataErrorMessage = " Unexpected Response from AAINetworkVpnBinding - " + returnCode
726                                                                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
727                                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
728
729                                                           }
730                                                 }
731                                         }
732
733                                 } // end loop
734
735                                 execution.setVariable("CRENWKI_routeCollection", routeTargets)
736                                 utils.log("DEBUG", " CRENWKI_routeCollection - " + '\n' + routeTargets, isDebugEnabled)
737
738                         } else {
739                                 // reset return code to success
740                                 execution.setVariable("CRENWKI_aaiQqueryVpnBindingReturnCode", "200")
741                             String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution)
742                                 String schemaVersion = aaiUriUtil.getNamespaceFromUri(aai_uri)
743                             String aaiStubResponse =
744                                         """     <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd">
745                                                         <vpn-binding xmlns="${schemaVersion}">
746                                                       <global-route-target/>
747                                                         </vpn-binding>
748                                                 </rest:payload>"""
749                                 String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse)
750                                 execution.setVariable("CRENWKI_queryVpnBindingAAIResponse", aaiStubResponseAsXml)
751                                 execution.setVariable("CRENWKI_routeCollection", "<routeTargets/>")
752                                 utils.log("DEBUG", " No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml, isDebugEnabled)
753
754                         }
755
756                 } catch (BpmnError e) {
757                         throw e;
758
759                 } catch (Exception ex) {
760                         String exceptionMessage = "Bpmn error encountered in CreateNetworkInstanceInfra flow. callRESTQueryAAINetworkVpnBinding() - " + ex.getMessage()
761                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
762                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
763
764                 }
765
766         }
767
768         public void callRESTQueryAAINetworkPolicy(Execution execution) {
769                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
770                 execution.setVariable("prefix", Prefix)
771
772                 utils.log("DEBUG", " ***** Inside callRESTQueryAAINetworkPolicy of CreateNetworkInstanceInfra ***** " , isDebugEnabled)
773
774                 try {
775                         // get variables
776                         String messageId = execution.getVariable("CRENWKI_messageId")
777                         String queryIdAAIResponse   = execution.getVariable("CRENWKI_queryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "")
778                         String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","")
779                         utils.log("DEBUG", " relationship - " + relationship, isDebugEnabled)
780
781                         // Check if Network Policy is present, then build a List of network policy
782                         List networkPolicyUriList = networkUtils.getNetworkPolicyObject(relationship)
783                         int networkPolicyCount = networkPolicyUriList.size()
784                         execution.setVariable("CRENWKI_networkPolicyCount", networkPolicyCount)
785                         utils.log("DEBUG", " CRENWKI_networkPolicyCount - " + networkPolicyCount, isDebugEnabled)
786
787                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
788                         AaiUtil aaiUriUtil = new AaiUtil(this)
789
790                         if (networkPolicyCount > 0) {
791                                 execution.setVariable("CRENWKI_networkPolicyUriList", networkPolicyUriList)
792                                 utils.log("DEBUG", " networkPolicyUri List - " + networkPolicyUriList, isDebugEnabled)
793
794                                 String networkPolicies = ""
795                                 // AII loop call using list vpnBindings
796                                 for (i in 0..networkPolicyUriList.size()-1) {
797
798                                         int counting = i+1
799
800                                         // prepare url using vpnBinding
801                                         String queryNetworkPolicyAAIRequest = ""
802
803                                         String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution)
804
805                                         // Note: By default, the network policy url is found in 'related-link' of the response,
806                                         //       so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping.
807                                         if (aai_uri == null || aai_uri == "") {
808                                                 // using value of 'related-link' from response
809                                                 if (networkPolicyUriList[i].charAt(networkPolicyUriList[i].length()-1) == '/') {
810                                                         queryNetworkPolicyAAIRequest = "${aai_endpoint}" + networkPolicyUriList[i].substring(0, networkPolicyUriList[i].length()-1)
811                                                 } else {
812                                                         queryNetworkPolicyAAIRequest = "${aai_endpoint}" + networkPolicyUriList[i]
813                                                 }
814                                         } else {
815                                                 // using uri value in URN mapping
816                                                 String networkPolicyId = networkPolicyUriList[i].substring(networkPolicyUriList[i].indexOf("/network-policy/")+16, networkPolicyUriList[i].length())
817                                                 println " networkPolicyId - " + networkPolicyId
818                                                 if (networkPolicyId.charAt(networkPolicyId.length()-1) == '/') {
819                                                         networkPolicyId = networkPolicyId.substring(0, networkPolicyId.length()-1)
820                                                 }
821                                                 queryNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + networkPolicyId
822
823                                         }
824
825
826                                         utils.logAudit(queryNetworkPolicyAAIRequest)
827                                         execution.setVariable("CRENWKI_queryNetworkPolicyAAIRequest", queryNetworkPolicyAAIRequest)
828                                         utils.log("DEBUG", " CRENWKI_queryNetworkPolicyAAIRequest, , NetworkPolicy #" + counting + " : " + "\n" + queryNetworkPolicyAAIRequest, isDebugEnabled)
829
830                                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
831
832                                         RESTConfig config = new RESTConfig(queryNetworkPolicyAAIRequest);
833                                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
834                                                                                                                           .addHeader("X-FromAppId", "MSO")
835                                                                                                                           .addHeader("Content-Type", "application/xml")
836                                                                                                                           .addHeader("Accept","application/xml");
837                                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
838                                                 client.addAuthorizationHeader(basicAuthCred)
839                                         }
840                                         APIResponse response = client.get()
841                                         String returnCode = response.getStatusCode()
842                                         execution.setVariable("CRENWKI_aaiQqueryNetworkPolicyReturnCode", returnCode)
843                                         utils.log("DEBUG", " ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode, isDebugEnabled)
844
845                                         String aaiResponseAsString = response.getResponseBodyAsString()
846
847                                         if (returnCode=='200') {
848                                                 utils.logAudit(aaiResponseAsString)
849                                                 execution.setVariable("CRENWKI_queryNetworkPolicyAAIResponse", aaiResponseAsString)
850                                                 utils.log("DEBUG", " QueryAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString, isDebugEnabled)
851
852                                                 String networkPolicy = ""
853                                                 if (utils.nodeExists(aaiResponseAsString, "network-policy-fqdn")) {
854                                                         networkPolicy  = utils.getNodeText1(aaiResponseAsString, "network-policy-fqdn")
855                                                         networkPolicies += "<policyFqdns>" + networkPolicy + "</policyFqdns>" + '\n'
856                                                 }
857
858                                         } else {
859                                                 if (returnCode=='404') {
860                                                         String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)."
861                                                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
862                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
863
864                                                 } else {
865                                                    if (aaiResponseAsString.contains("RESTFault")) {
866                                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
867                                                            execution.setVariable("WorkflowException", exceptionObject)
868                                                            throw new BpmnError("MSOWorkflowException")
869
870                                                            } else {
871                                                                         // aai all errors
872                                                                         String dataErrorMessage = "Unexpected Response from QueryAAINetworkPolicy - " + returnCode
873                                                                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
874                                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
875
876                                                           }
877                                                 }
878                                         }
879
880                                 } // end loop
881
882                                 execution.setVariable("CRENWKI_networkCollection", networkPolicies)
883                                 utils.log("DEBUG", " CRENWKI_networkCollection - " + '\n' + networkPolicies, isDebugEnabled)
884
885                         } else {
886                                 // reset return code to success
887                                 execution.setVariable("CRENWKI_aaiQqueryNetworkPolicyReturnCode", "200")
888                                 String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution)
889                                 String schemaVersion = aaiUriUtil.getNamespaceFromUri(aai_uri)
890                                 String aaiStubResponse =
891                                         """     <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd">
892                                                         <network-policy xmlns="${schemaVersion}">
893                                                           <network-policy-fqdn/>
894                             </network-policy>
895                                                 </rest:payload>"""
896                                 String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse)
897                                 execution.setVariable("CRENWKI_queryNetworkPolicyAAIResponse", aaiStubResponseAsXml)
898                                 execution.setVariable("CRENWKI_networkCollection", "<policyFqdns/>")
899                                 utils.log("DEBUG", " No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml, isDebugEnabled)
900
901                         }
902
903                 } catch (BpmnError e) {
904                         throw e;
905
906                 } catch (Exception ex) {
907                         String exceptionMessage = "Bpmn error encountered in CreateNetworkInstanceInfra flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage()
908                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
909                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
910
911                 }
912
913         }
914
915         public void callRESTQueryAAINetworkTableRef(Execution execution) {
916                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
917                 execution.setVariable("prefix", Prefix)
918
919                 utils.log("DEBUG", " ***** Inside callRESTQueryAAINetworkTableRef of CreateNetworkInstanceInfra ***** " , isDebugEnabled)
920
921                 try {
922                         // get variables
923                         String messageId = execution.getVariable("CRENWKI_messageId")
924                         String queryIdAAIResponse   = execution.getVariable("CRENWKI_queryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "")
925                         String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","")
926                         utils.log("DEBUG", " relationship - " + relationship, isDebugEnabled)
927
928                         // Check if Network TableREf is present, then build a List of network policy
929                         List networkTableRefUriList = networkUtils.getNetworkTableRefObject(relationship)
930                         int networkTableRefCount = networkTableRefUriList.size()
931                         execution.setVariable("CRENWKI_networkTableRefCount", networkTableRefCount)
932                         utils.log("DEBUG", " CRENWKI_networkTableRefCount - " + networkTableRefCount, isDebugEnabled)
933
934                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
935                         AaiUtil aaiUriUtil = new AaiUtil(this)
936
937                         if (networkTableRefCount > 0) {
938                                 execution.setVariable("CRENWKI_networkTableRefUriList", networkTableRefUriList)
939                                 utils.log("DEBUG", " networkTableRefUri List - " + networkTableRefUriList, isDebugEnabled)
940
941                                 // AII loop call using list vpnBindings
942                                 String networkTableRefs = ""
943                                 for (i in 0..networkTableRefUriList.size()-1) {
944
945                                         int counting = i+1
946
947                                         // prepare url using tableRef
948                                         String queryNetworkTableRefAAIRequest = ""
949
950                                         String aai_uri = aaiUriUtil.getNetworkTableReferencesUri(execution)
951
952                                         // Note: By default, the network policy url is found in 'related-link' of the response,
953                                         //       so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping.
954                                         if (aai_uri == null || aai_uri == "") {
955                                                 // using value of 'related-link' from response
956                                                 if (networkTableRefUriList[i].charAt(networkTableRefUriList[i].length()-1) == '/') {
957                                                         queryNetworkTableRefAAIRequest = "${aai_endpoint}" + networkTableRefUriList[i].substring(0, networkTableRefUriList[i].length()-1)
958                                                 } else {
959                                                         queryNetworkTableRefAAIRequest = "${aai_endpoint}" + networkTableRefUriList[i]
960                                                 }
961                                         } else {
962                                                 // using uri value in URN mapping
963                                                 String networkTableRefId = networkTableRefUriList[i].substring(networkTableRefUriList[i].indexOf("/route-table-reference/")+23, networkTableRefUriList[i].length())
964
965                                                 if (networkTableRefId.charAt(networkTableRefId.length()-1) == '/') {
966                                                         networkTableRefId = networkTableRefId.substring(0, networkTableRefId.length()-1)
967                                                 }
968                                                 queryNetworkTableRefAAIRequest = "${aai_endpoint}${aai_uri}/" + networkTableRefId
969
970                                         }
971
972
973                                         utils.logAudit(queryNetworkTableRefAAIRequest)
974                                         execution.setVariable("CRENWKI_queryNetworkTableRefAAIRequest", queryNetworkTableRefAAIRequest)
975                                         utils.log("DEBUG", " CRENWKI_queryNetworkTableRefAAIRequest, , NetworkTableRef #" + counting + " : " + "\n" + queryNetworkTableRefAAIRequest, isDebugEnabled)
976
977                                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
978
979                                         RESTConfig config = new RESTConfig(queryNetworkTableRefAAIRequest);
980                                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
981                                                                                                                           .addHeader("X-FromAppId", "MSO")
982                                                                                                                           .addHeader("Content-Type", "application/xml")
983                                                                                                                           .addHeader("Accept","application/xml");
984                                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
985                                                 client.addAuthorizationHeader(basicAuthCred)
986                                         }
987                                         APIResponse response = client.get()
988                                         String returnCode = response.getStatusCode()
989                                         execution.setVariable("CRENWKI_aaiQqueryNetworkTableRefReturnCode", returnCode)
990                                         utils.log("DEBUG", " ***** AAI query network Table Reference Response Code, NetworkTableRef #" + counting + " : " + returnCode, isDebugEnabled)
991
992                                         String aaiResponseAsString = response.getResponseBodyAsString()
993
994                                         if (returnCode=='200') {
995                                                 utils.logAudit(aaiResponseAsString)
996                                                 execution.setVariable("CRENWKI_queryNetworkTableRefAAIResponse", aaiResponseAsString)
997                                                 utils.log("DEBUG", " QueryAAINetworkTableRef Success REST Response, , NetworkTableRef #" + counting + " : " + "\n" + aaiResponseAsString, isDebugEnabled)
998
999                                                 String networkTableRef = ""
1000                                                 if (utils.nodeExists(aaiResponseAsString, "route-table-reference-fqdn")) {
1001                                                         networkTableRef  = utils.getNodeText1(aaiResponseAsString, "route-table-reference-fqdn")
1002                                                         networkTableRefs += "<routeTableFqdns>" + networkTableRef + "</routeTableFqdns>" + '\n'
1003                                                 }
1004
1005                                         } else {
1006                                                 if (returnCode=='404') {
1007                                                         String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)."
1008                                                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
1009                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
1010
1011                                                 } else {
1012                                                    if (aaiResponseAsString.contains("RESTFault")) {
1013                                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
1014                                                            execution.setVariable("WorkflowException", exceptionObject)
1015                                                            throw new BpmnError("MSOWorkflowException")
1016
1017                                                            } else {
1018                                                                         // aai all errors
1019                                                                         String dataErrorMessage = "Unexpected Response from QueryAAINetworkTableRef - " + returnCode
1020                                                                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
1021                                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
1022
1023                                                           }
1024                                                 }
1025                                         }
1026
1027                                 } // end loop
1028
1029                                 execution.setVariable("CRENWKI_tableRefCollection", networkTableRefs)
1030                                 utils.log("DEBUG", " CRENWKI_tableRefCollection - " + '\n' + networkTableRefs, isDebugEnabled)
1031
1032                         } else {
1033                                 // reset return code to success
1034                                 execution.setVariable("CRENWKI_aaiQqueryNetworkTableRefReturnCode", "200")
1035                                 String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution)
1036                                 String schemaVersion = aaiUriUtil.getNamespaceFromUri(aai_uri)
1037                                 String aaiStubResponse =
1038                                         """     <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd">
1039                                                         <route-table-references xmlns="${schemaVersion}">
1040                                                           <route-table-reference-fqdn/>
1041                             </route-table-references>
1042                                                 </rest:payload>"""
1043                                 String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse)
1044                                 execution.setVariable("CRENWKI_queryNetworkTableRefAAIResponse", aaiStubResponseAsXml)
1045                                 execution.setVariable("CRENWKI_tableRefCollection", "<routeTableFqdns/>")
1046                                 utils.log("DEBUG", " No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml, isDebugEnabled)
1047
1048                         }
1049
1050                 } catch (BpmnError e) {
1051                         throw e;
1052
1053                 } catch (Exception ex) {
1054                         String exceptionMessage = "Bpmn error encountered in CreateNetworkInstanceInfra flow. callRESTQueryAAINetworkTableRef() - " + ex.getMessage()
1055                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1056                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1057
1058                 }
1059
1060         }
1061
1062
1063         public void callRESTUpdateContrailAAINetwork(Execution execution) {
1064                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1065                 execution.setVariable("prefix", Prefix)
1066
1067                 utils.log("DEBUG", " ***** Inside callRESTUpdateContrailAAINetwork of CreateNetworkInstanceInfra ***** " , isDebugEnabled)
1068
1069                 try {
1070                         // get variables
1071                         String networkId   = utils.getNodeText1(execution.getVariable("CRENWKI_assignSDNCResponse"), "network-id")
1072                         networkId = UriUtils.encode(networkId,"UTF-8")
1073                         String requeryIdAAIResponse   = execution.getVariable("CRENWKI_requeryIdAAIResponse")
1074                         String createNetworkResponse   = execution.getVariable("CRENWKI_createNetworkResponse")
1075                         String messageId = execution.getVariable("CRENWKI_messageId")
1076
1077                         // Prepare url
1078                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
1079                         AaiUtil aaiUriUtil = new AaiUtil(this)
1080                         String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution)
1081                         String updateContrailAAIUrlRequest = "${aai_endpoint}${aai_uri}/" + networkId
1082
1083                         utils.logAudit(updateContrailAAIUrlRequest)
1084                         execution.setVariable("CRENWKI_updateContrailAAIUrlRequest", updateContrailAAIUrlRequest)
1085                         utils.log("DEBUG", " CRENWKI_updateContrailAAIUrlRequest - " + "\n" + updateContrailAAIUrlRequest, isDebugEnabled)
1086
1087                         //Prepare payload (PUT)
1088                         String schemaVersion = aaiUriUtil.getNamespaceFromUri(aai_uri)
1089                         String payload = networkUtils.ContrailNetworkCreatedUpdate(requeryIdAAIResponse, createNetworkResponse, schemaVersion)
1090                         String payloadXml = utils.formatXml(payload)
1091                         utils.logAudit(payloadXml)
1092                         execution.setVariable("CRENWKI_updateContrailAAIPayloadRequest", payloadXml)
1093                         utils.log("DEBUG", " 'payload' to Update Contrail - " + "\n" + payloadXml, isDebugEnabled)
1094
1095                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
1096
1097                         RESTConfig config = new RESTConfig(updateContrailAAIUrlRequest);
1098                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
1099                                                                                                           .addHeader("X-FromAppId", "MSO")
1100                                                                                                           .addHeader("Content-Type", "application/xml")
1101                                                                                                           .addHeader("Accept","application/xml");
1102                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
1103                                 client.addAuthorizationHeader(basicAuthCred)
1104                         }
1105                         APIResponse response = client.httpPut(payload)
1106                         String returnCode = response.getStatusCode()
1107                         execution.setVariable("CRENWKI_aaiUpdateContrailReturnCode", returnCode)
1108
1109                         utils.log("DEBUG", " ***** AAI Update Contrail Response Code  : " + returnCode, isDebugEnabled)
1110
1111                         String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString()
1112
1113                         if (returnCode=='200') {
1114                                 utils.logAudit(aaiUpdateContrailResponseAsString)
1115                                 execution.setVariable("CRENWKI_updateContrailAAIResponse", aaiUpdateContrailResponseAsString)
1116                                 utils.log("DEBUG", " AAI Update Contrail Success REST Response - " + "\n" + aaiUpdateContrailResponseAsString, isDebugEnabled)
1117                                 // Point-of-no-return is set to false, rollback not needed.
1118                                 execution.setVariable("CRENWKI_isPONR", true)
1119
1120                         } else {
1121                                 if (returnCode=='404') {
1122                                         String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)."
1123                                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
1124                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
1125
1126                                 } else {
1127                                    if (aaiUpdateContrailResponseAsString.contains("RESTFault")) {
1128                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiUpdateContrailResponseAsString, execution)
1129                                            execution.setVariable("WorkflowException", exceptionObject)
1130                                            throw new BpmnError("MSOWorkflowException")
1131
1132                                            } else {
1133                                                         // aai all errors
1134                                                         String errorMessage = "Unexpected Response from UpdateContrailAAINetwork - " + returnCode
1135                                                         utils.log("DEBUG", errorMessage, isDebugEnabled)
1136                                                         exceptionUtil.buildAndThrowWorkflowException(execution, "2500", errorMessage)
1137                                           }
1138                                 }
1139                         }
1140
1141                 } catch (BpmnError e) {
1142                         throw e;
1143
1144                 } catch (Exception ex) {
1145                         String exceptionMessage = "Bpmn error encountered in CreateNetworkInstanceInfra flow. callRESTUpdateContrailAAINetwork() - " + ex.getMessage()
1146                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1147                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1148
1149                 }
1150
1151         }
1152
1153         public void prepareCreateNetworkRequest (Execution execution) {
1154                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1155                 execution.setVariable("prefix", Prefix)
1156
1157                 utils.log("DEBUG", " ***** Inside prepareCreateNetworkRequest of CreateNetworkInstanceInfra ***** ", isDebugEnabled)
1158
1159                 try {
1160
1161                         // get variables
1162                         String requestId = execution.getVariable("CRENWKI_requestId")
1163                         String messageId = execution.getVariable("CRENWKI_messageId")
1164                         String source    = execution.getVariable("CRENWKI_source")
1165
1166                         String requestInput = execution.getVariable("CRENWKI_networkRequest")
1167                         String queryIdResponse = execution.getVariable("CRENWKI_queryIdAAIResponse")
1168                         String cloudRegionId = execution.getVariable("CRENWKI_cloudRegionPo")
1169                         String backoutOnFailure = execution.getVariable("CRENWKI_rollbackEnabled")
1170
1171                         // Prepare Network request
1172                         String routeCollection = execution.getVariable("CRENWKI_routeCollection")
1173                         String policyCollection = execution.getVariable("CRENWKI_networkCollection")
1174                         String tableCollection = execution.getVariable("CRENWKI_tableRefCollection")
1175                         String createNetworkRequest = networkUtils.CreateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyCollection, tableCollection, cloudRegionId, backoutOnFailure, source )
1176                         // Format Response
1177                         String buildDeleteNetworkRequestAsString = utils.formatXml(createNetworkRequest)
1178                         buildDeleteNetworkRequestAsString = buildDeleteNetworkRequestAsString.replace(":w1aac13n0", "").replace("w1aac13n0:", "")
1179                         utils.logAudit(buildDeleteNetworkRequestAsString)
1180
1181                         execution.setVariable("CRENWKI_createNetworkRequest", buildDeleteNetworkRequestAsString)
1182                         utils.log("DEBUG", " CRENWKI_createNetworkRequest - " + "\n" +  buildDeleteNetworkRequestAsString, isDebugEnabled)
1183
1184                 } catch (Exception ex) {
1185                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstanceInfra flow. prepareCreateNetworkRequest() - " + ex.getMessage()
1186                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1187                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1188
1189                 }
1190
1191         }
1192
1193         public void prepareSDNCRequest (Execution execution) {
1194                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1195                 execution.setVariable("prefix", Prefix)
1196
1197                 utils.log("DEBUG", " ***** Inside prepareSDNCRequest of CreateNetworkInstanceInfra ***** ", isDebugEnabled)
1198
1199                 try {
1200                         // get variables
1201                         String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback")
1202                         String createNetworkInput = execution.getVariable("CRENWKI_networkRequest")
1203                         String cloudRegionId = execution.getVariable("CRENWKI_cloudRegionSdnc")
1204
1205                         String networkId = ""
1206                         if (utils.nodeExists(createNetworkInput, "network-id")) {
1207                            networkId = utils.getNodeText1(createNetworkInput, "network-id")
1208                         }
1209                         if (networkId == null) {networkId = ""}
1210
1211                         String serviceInstanceId = utils.getNodeText1(createNetworkInput, "service-instance-id")
1212
1213                         // 1. prepare assign topology via SDNC Adapter SUBFLOW call
1214                         String sndcTopologyCreateRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, createNetworkInput, serviceInstanceId, sdncCallback, "assign", "NetworkActivateRequest", cloudRegionId, networkId, null)
1215
1216                         String sndcTopologyCreateRequesAsString = utils.formatXml(sndcTopologyCreateRequest)
1217                         utils.logAudit(sndcTopologyCreateRequesAsString)
1218                         execution.setVariable("CRENWKI_assignSDNCRequest", sndcTopologyCreateRequesAsString)
1219                         utils.log("DEBUG", " CRENWKI_assignSDNCRequest - " + "\n" +  sndcTopologyCreateRequesAsString, isDebugEnabled)
1220
1221
1222                 } catch (Exception ex) {
1223                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstanceInfra flow. prepareSDNCRequest() - " + ex.getMessage()
1224                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1225                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1226
1227                 }
1228
1229         }
1230
1231         public void prepareDBRequest (Execution execution) {
1232                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1233                 execution.setVariable("prefix", Prefix)
1234
1235                 try {
1236                         utils.log("DEBUG", " ***** Inside prepareDBRequest of CreateNetworkInstanceInfra ***** ", isDebugEnabled)
1237
1238                         String networkOutputs = execution.getVariable("CRENWKI_networkOutputs")
1239                         String networkName = ""
1240                         try {
1241                                  networkName = utils.getNodeText1(networkOutputs, "network-name")
1242                                  if (networkName == null) {networkName = ""}
1243                         } catch (Exception ex) {
1244                                 networkName = ""
1245                                 utils.log("DEBUG", " No 'network-name' found in '<network-outputs>' ! ", isDebugEnabled)
1246                         }
1247                         String networkId = ""
1248                         try {
1249                                 networkId = utils.getNodeText1(networkOutputs, "network-id")
1250                                 if (networkId == null) {networkId = ""}
1251                         } catch (Exception) {
1252                                 networkId = ""
1253                                 utils.log("DEBUG", " No 'network-id' found in '<network-outputs>' ! ", isDebugEnabled)
1254                         }
1255                         String requestId = execution.getVariable("CRENWKI_requestId")
1256
1257                         String statusMessage = ""
1258                         if (execution.getVariable("CRENWKI_orchestrationStatus") == "ACTIVE") {
1259                                 // SILENT SUCCESS
1260                                 statusMessage = "Network " + networkName + " already exists. Silent success."
1261                         } else {
1262                                 statusMessage = "Network successfully created."
1263                         }
1264
1265                         String dbRequest =
1266                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
1267                                                 <soapenv:Header/>
1268                                                 <soapenv:Body>
1269                                                         <ns:updateInfraRequest xmlns:ns="http://com.att.mso/requestsdb">
1270                                                                 <requestId>${requestId}</requestId>
1271                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
1272                                                                 <statusMessage>${statusMessage}</statusMessage>
1273                                                                 <responseBody></responseBody>
1274                                                                 <requestStatus>COMPLETED</requestStatus>
1275                                                                 <progress>100</progress>
1276                                                                 <vnfOutputs>&lt;network-id&gt;${networkId}&lt;/network-id&gt;&lt;network-name&gt;${networkName}&lt;/network-names&gt;</vnfOutputs>
1277                                 <networkId>${networkId}</networkId>
1278                                                         </ns:updateInfraRequest>
1279                                                 </soapenv:Body>
1280                                            </soapenv:Envelope>"""
1281
1282                    String buildDeleteDBRequestAsString = utils.formatXml(dbRequest)
1283                    execution.setVariable("CRENWKI_createDBRequest", buildDeleteDBRequestAsString)
1284                    utils.log("DEBUG", " DB Adapter Request - " + "\n" + buildDeleteDBRequestAsString, isDebugEnabled)
1285                    utils.logAudit(buildDeleteDBRequestAsString)
1286
1287                 } catch (Exception ex) {
1288                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstanceInfra flow. prepareDBRequest() - " + ex.getMessage()
1289                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1290                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1291
1292                 }
1293
1294          }
1295
1296         public void prepareDBRequestError (Execution execution) {
1297                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1298                 execution.setVariable("prefix", Prefix)
1299
1300                 try {
1301                         utils.log("DEBUG", " ***** Inside prepareDBRequestError of CreateNetworkInstanceInfra ***** ", isDebugEnabled)
1302
1303                         String statusMessage = ""
1304                         WorkflowException wfe = null
1305                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
1306                                 wfe = execution.getVariable("WorkflowException")
1307                                 statusMessage = wfe.getErrorMessage()
1308                         } else {
1309                            String workflowException = execution.getVariable("WorkflowException")
1310                            try {
1311                                   statusMessage = utils.getNodeText1(workflowException, "ErrorMessage")
1312                            } catch (Exception ex) {
1313                                   statusMessage = "Encountered Error during DB Update. " + ex.getMessage()
1314                            }
1315                         }
1316                         String networkOutputs = execution.getVariable("CRENWKI_networkOutputs")
1317                         String requestId = execution.getVariable("CRENWKI_requestId")
1318                         String networkId = ""
1319                         try {
1320                                 networkId = utils.getNodeText1(networkOutputs, "network-id")
1321                                 if (networkId == null) {networkId = ""}
1322                         } catch (Exception) {
1323                                 networkId = ""
1324                                 utils.log("DEBUG", " No 'network-id' found in '<network-outputs>' ! ", isDebugEnabled)
1325                         }
1326                         String networkName = ""
1327                         try {
1328                                  networkName = utils.getNodeText1(networkOutputs, "network-name")
1329                                  if (networkName == null) {networkName = ""}
1330                         } catch (Exception ex) {
1331                                 networkName = ""
1332                                 utils.log("DEBUG", " No 'network-name' found in '<network-outputs>' ! ", isDebugEnabled)
1333                         }
1334                         String dbRequest =
1335                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
1336                                                 <soapenv:Header/>
1337                                                 <soapenv:Body>
1338                                                         <ns:updateInfraRequest xmlns:ns="http://com.att.mso/requestsdb">
1339                                                                 <requestId>${requestId}</requestId>
1340                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
1341                                                                 <statusMessage>${statusMessage}</statusMessage>
1342                                                                 <responseBody></responseBody>
1343                                                                 <requestStatus>FAILED</requestStatus>
1344                                                                 <vnfOutputs>&lt;network-id&gt;${networkId}&lt;/network-id&gt;&lt;network-name&gt;${networkName}&lt;/network-names&gt;</vnfOutputs>
1345                                                         </ns:updateInfraRequest>
1346                                                 </soapenv:Body>
1347                                            </soapenv:Envelope>"""
1348
1349                    execution.setVariable("CRENWKI_createDBRequest", dbRequest)
1350                    utils.log("DEBUG", " DB Adapter Request - " + "\n" + dbRequest, isDebugEnabled)
1351                    utils.logAudit(dbRequest)
1352
1353                 } catch (Exception ex) {
1354                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstanceInfra flow. prepareDBRequestError() - " + ex.getMessage()
1355                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1356                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1357
1358                 }
1359
1360          }
1361
1362
1363         // **************************************************
1364         //     Post or Validate Response Section
1365         // **************************************************
1366
1367         public void validateCreateNetworkResponse (Execution execution) {
1368                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1369                 execution.setVariable("prefix", Prefix)
1370
1371                 utils.log("DEBUG", " ***** Inside validateNetworkResponse of CreateNetworkInstanceInfra *****", isDebugEnabled)
1372
1373                 try {
1374                         String returnCode = execution.getVariable("CRENWKI_networkReturnCode")
1375                         String networkResponse = execution.getVariable("CRENWKI_createNetworkResponse")
1376                         if (networkResponse==null)      {
1377                                 networkResponse="" // reset
1378                         }
1379
1380                         utils.log("DEBUG", " Network Adapter create responseCode: " + returnCode, isDebugEnabled)
1381
1382                         String errorMessage = ""
1383                         if (returnCode == "200") {
1384                                 execution.setVariable("CRENWKI_isNetworkRollbackNeeded", true)
1385                                 utils.logAudit(networkResponse)
1386                                 execution.setVariable("CRENWKI_createNetworkResponse", networkResponse)
1387                                 utils.log("DEBUG", " Network Adapter create Success Response - " + "\n" + networkResponse, isDebugEnabled)
1388
1389                                 // prepare rollback data
1390                                 String rollbackData = utils.getNodeXml(networkResponse, "rollback", false).replace("tag0:","").replace(":tag0","")
1391                                 String rollbackNetwork =
1392                                         """<NetworkAdapter:rollbackNetwork xmlns:NetworkAdapter="http://com.att.mso/network">
1393                                                         ${rollbackData}
1394                                                 </NetworkAdapter:rollbackNetwork>"""
1395                                 String rollbackNetworkXml = utils.formatXml(rollbackNetwork)
1396                                 execution.setVariable("CRENWKI_rollbackNetworkRequest", rollbackNetworkXml)
1397                                 utils.log("DEBUG", " Network Adapter rollback data - " + "\n" + rollbackNetworkXml, isDebugEnabled)
1398
1399                         } else { // network error
1400                            if (returnCode.toInteger() > 399 && returnCode.toInteger() < 600) {   //4xx, 5xx
1401                                    if (networkResponse.contains("createNetworkError")) {
1402                                            networkResponse = networkResponse.replace('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', '')
1403                                            errorMessage = utils.getNodeText1(networkResponse, "message")
1404                                            errorMessage  = "Received error from Network Adapter: " + errorMessage
1405                                            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1406
1407                                    } else { // CatchAll exception
1408                                            if (returnCode == "500") {
1409                                                    errorMessage = "JBWEB000065: HTTP Status 500."
1410                                        } else {
1411                                                errorMessage = "Return code is " + returnCode
1412                                        }
1413                                            errorMessage  = "Received error from Network Adapter: " + errorMessage
1414                                            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1415
1416                                    }
1417
1418                            } else { // CatchAll exception
1419                                    String dataErrorMessage  = "Received error from Network Adapter. Return code is: " + returnCode
1420                                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
1421
1422                            }
1423
1424                         }
1425
1426                 } catch (BpmnError e) {
1427                         throw e;
1428
1429                 } catch (Exception ex) {
1430                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstanceInfra flow. validateCreateNetworkResponse() - " + ex.getMessage()
1431                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1432                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1433
1434                 }
1435
1436
1437         }
1438
1439         public void validateSDNCResponse (Execution execution) {
1440                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1441                 execution.setVariable("prefix", Prefix)
1442
1443                 utils.log("DEBUG", " ***** Inside validateSDNCResponse of CreateNetworkInstanceInfra ***** ", isDebugEnabled)
1444
1445                 String response = execution.getVariable("CRENWKI_assignSDNCResponse")
1446                 WorkflowException workflowException = null
1447                 try {
1448                         workflowException = execution.getVariable("CRENWKI_WorkflowException")
1449                         //execution.setVariable("WorkflowException", workflowException)
1450                 } catch (Exception ex) {
1451                         utils.log("DEBUG", " Sdnc 'WorkflowException' object is empty or null. ", isDebugEnabled)
1452                 }
1453
1454                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
1455
1456                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
1457                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
1458                 // reset variable
1459                 String assignSDNCResponseDecodeXml = sdncAdapterUtils.decodeXML(execution.getVariable("CRENWKI_assignSDNCResponse"))
1460                 assignSDNCResponseDecodeXml = assignSDNCResponseDecodeXml.replace("&", "&amp;").replace('<?xml version="1.0" encoding="UTF-8"?>', "")
1461                 execution.setVariable("CRENWKI_assignSDNCResponse", assignSDNCResponseDecodeXml)
1462
1463                 if (execution.getVariable("CRENWKI_sdncResponseSuccess") == true) {  // from sdnc util, prefix+'sdncResponseSuccess'
1464                         execution.setVariable("CRENWKI_isSdncRollbackNeeded", true)
1465                         utils.log("DEBUG", "Successfully Validated SDNC Response", isDebugEnabled)
1466
1467                 } else {
1468                         utils.log("DEBUG", "Did NOT Successfully Validated SDNC Response", isDebugEnabled)
1469                         throw new BpmnError("MSOWorkflowException")
1470                 }
1471
1472         }
1473
1474
1475         public void postProcessResponse (Execution execution) {
1476                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1477                 execution.setVariable("prefix", Prefix)
1478
1479                 utils.log("DEBUG", " ***** Inside postProcessResponse of CreateNetworkInstanceInfra ***** ", isDebugEnabled)
1480
1481                 try {
1482                         // Display DB response: CRENWKI_createDBResponse / CRENWKI_dbReturnCode
1483                         String dbReturnCode = execution.getVariable("CRENWKI_dbReturnCode")
1484                         utils.log("DEBUG", " ***** DB Update Response Code  : " + dbReturnCode, isDebugEnabled)
1485                         String createDBResponse =  execution.getVariable("CRENWKI_createDBResponse")
1486                         utils.log("DEBUG", " ***** DB Update Response String: " + '\n' + createDBResponse, isDebugEnabled)
1487                         utils.logAudit(createDBResponse)
1488
1489                         String source = execution.getVariable("CRENWKI_source")
1490                         String requestId = execution.getVariable("CRENWKI_requestId")
1491
1492                         String msoCompletionRequest =
1493                                 """<aetgt:MsoCompletionRequest xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1"
1494                                                                 xmlns:ns="http://ecomp.att.com/mso/request/types/v1">
1495                                                 <request-info xmlns="http://ecomp.att.com/mso/infra/vnf-request/v1">
1496                                                         <request-id>${requestId}</request-id>
1497                                                         <action>CREATE</action>
1498                                                         <source>${source}</source>
1499                                                 </request-info>
1500                                                 <aetgt:status-message>Network has been created successfully.</aetgt:status-message>
1501                                                 <aetgt:mso-bpel-name>BPMN Network action: CREATE</aetgt:mso-bpel-name>
1502                                         </aetgt:MsoCompletionRequest>"""
1503
1504                                 // Format Response
1505                                 String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
1506
1507                         if (execution.getVariable("CRENWKI_orchestrationStatus") != "ACTIVE") {
1508                                 // normal path
1509                                 if (dbReturnCode == "200") {
1510                                         utils.logAudit(createDBResponse)
1511                                         utils.logAudit(xmlMsoCompletionRequest)
1512                                         execution.setVariable("CRENWKI_Success", true)
1513                                         execution.setVariable("CRENWKI_CompleteMsoProcessRequest", xmlMsoCompletionRequest)
1514                                         utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
1515                                 } else {
1516                                         String errorMessage = " DB Update failed, code: " + dbReturnCode
1517                                         utils.log("DEBUG", errorMessage, isDebugEnabled)
1518                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1519
1520                                 }
1521
1522                         } else {
1523                                 // silent Success path
1524                                 utils.logAudit(createDBResponse)
1525                                 utils.logAudit(xmlMsoCompletionRequest)
1526                                 execution.setVariable("CRENWKI_Success", true)
1527                                 execution.setVariable("CRENWKI_CompleteMsoProcessRequest", xmlMsoCompletionRequest)
1528                                 utils.log("DEBUG", " Silent SUCCESS going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
1529
1530                         }
1531
1532                 } catch (BpmnError e) {
1533                 throw e;
1534
1535                 } catch (Exception ex) {
1536                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstanceInfra flow. postProcessResponse() - " + ex.getMessage()
1537                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1538                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1539
1540         }
1541
1542
1543         }
1544
1545         public void prepareSDNCRollbackRequest (Execution execution) {
1546                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1547                 execution.setVariable("prefix", Prefix)
1548
1549                 utils.log("DEBUG", " ***** Inside prepareSDNCRollbackRequest of CreateNetworkInstanceInfra ***** ", isDebugEnabled)
1550
1551                 try {
1552                         // for some reason the WorkflowException object is null after the sdnc rollback call task, need to save WorkflowException.
1553                         execution.setVariable("CRENWKI_WorkflowException", execution.getVariable("WorkflowException"))
1554                         // get variables
1555                         String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback")
1556                         String createNetworkInput = execution.getVariable("CRENWKI_networkRequest")
1557                         String cloudRegionId = execution.getVariable("CRENWKI_cloudRegionSdnc")
1558                         String assignSDNCResponse = execution.getVariable("CRENWKI_assignSDNCResponse")
1559                         String networkId = utils.getNodeText1(assignSDNCResponse, "network-id")
1560
1561                         String serviceInstanceId = utils.getNodeText1(createNetworkInput, "service-instance-id")
1562
1563                         // 2. prepare rollback topology via SDNC Adapter SUBFLOW call
1564                         String sndcTopologyRollbackRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, createNetworkInput, serviceInstanceId, sdncCallback, "rollback", "NetworkActivateRequest", cloudRegionId, networkId, null)
1565                         String sndcTopologyRollbackRequestAsString = utils.formatXml(sndcTopologyRollbackRequest)
1566                         execution.setVariable("CRENWKI_rollbackSDNCRequest", sndcTopologyRollbackRequestAsString)
1567                         utils.log("DEBUG", " Preparing request for SDNC Topology assign's rollback/compensation . . . - " + "\n" +  sndcTopologyRollbackRequestAsString, isDebugEnabled)
1568
1569
1570                 } catch (Exception ex) {
1571                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstanceInfra flow. prepareSDNCRollbackRequest() - " + ex.getMessage()
1572                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1573                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1574
1575                 }
1576
1577         }
1578
1579         public void validateRollbackResponses (Execution execution) {
1580                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1581                 execution.setVariable("prefix", Prefix)
1582
1583                 try {
1584                         // validate PO network rollback response
1585                         String rollbackNetworkErrorMessages = ""
1586                         Boolean isNetworkRollbackNeeded = execution.getVariable("CRENWKI_isNetworkRollbackNeeded")
1587                         if (isNetworkRollbackNeeded == true) {
1588                                 utils.log("DEBUG", " NetworkRollback Code - " + execution.getVariable("CRENWKI_rollbackNetworkReturnCode"), isDebugEnabled)
1589                                 utils.log("DEBUG", " NetworkRollback Response - " + execution.getVariable("CRENWKI_rollbackNetworkResponse"), isDebugEnabled)
1590
1591                                 String rollbackNetworkReturnCode = execution.getVariable("CRENWKI_rollbackNetworkReturnCode")
1592                                 String rollbackNetworkResponse = execution.getVariable("CRENWKI_rollbackNetworkResponse")
1593                                 if (rollbackNetworkReturnCode != "200") {
1594                                         rollbackNetworkErrorMessages = " + PO Network rollback failed. "
1595                                 } else {
1596                                         rollbackNetworkErrorMessages = " + PO Network rollback completed."
1597                                 }
1598
1599                         }
1600
1601                         // validate SDNC rollback response
1602                         String rollbackSdncErrorMessages = ""
1603                         Boolean isSdncRollbackNeeded = execution.getVariable("CRENWKI_isSdncRollbackNeeded")
1604                         if (isSdncRollbackNeeded == true) {
1605                                 String rollbackSDNCReturnCode = execution.getVariable("CRENWKI_rollbackSDNCReturnCode")
1606                                 String rollbackSDNCReturnInnerCode = ""
1607                                 String rollbackSDNCResponse = execution.getVariable("CRENWKI_rollbackSDNCResponse")
1608                                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
1609                                 rollbackSDNCResponse = sdncAdapterUtils.decodeXML(rollbackSDNCResponse)
1610                                 rollbackSDNCResponse = rollbackSDNCResponse.replace("&", "&amp;").replace('$', '').replace('<?xml version="1.0" encoding="UTF-8"?>', "")
1611
1612                                 if (rollbackSDNCReturnCode == "200") {
1613                                         if (utils.nodeExists(rollbackSDNCResponse, "response-code")) {
1614                                                 rollbackSDNCReturnInnerCode = utils.getNodeText1(rollbackSDNCResponse, "response-code")
1615                                                 if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") {
1616                                                 rollbackSdncErrorMessages = " + SNDC rollback completed."
1617                                                 } else {
1618                                                         rollbackSdncErrorMessages = " + SDNC rollback failed. "
1619                                                 }
1620                                         } else {
1621                                           rollbackSdncErrorMessages = " + SNDC rollback completed."
1622                                         }
1623                                 } else {
1624                                           rollbackSdncErrorMessages = " + SDNC rollback failed. "
1625                                 }
1626
1627                                 utils.log("DEBUG", " SDNC rollback Code - " + rollbackSDNCReturnCode, isDebugEnabled)
1628                                 utils.log("DEBUG", " SDNC rollback  Response - " + rollbackSDNCResponse, isDebugEnabled)
1629
1630                         }
1631
1632                         //WorkflowException wfe = execution.getVariable("WorkflowException")
1633                         //String statusMessage = wfe.getErrorMessage()
1634                         //int errorCode = wfe.getErrorCode()
1635
1636                         String statusMessage = ""
1637                         int errorCode = 0
1638                         WorkflowException wfe = execution.getVariable("WorkflowException")
1639                         if (wfe instanceof WorkflowException) {
1640                           statusMessage = wfe.getErrorMessage()
1641                           errorCode = wfe.getErrorCode()
1642                         } else {
1643                            if (execution.getVariable("CRENWKI_WorkflowException") instanceof WorkflowException) {
1644                                   // get saved WorkflowException
1645                               WorkflowException swfe = execution.getVariable("CRENWKI_WorkflowException")
1646                               statusMessage = swfe.getErrorMessage()
1647                               errorCode =  swfe.getErrorCode()
1648                            } else {
1649                               statusMessage = "Encountered Error, please see previous tasks/activities/steps for error messages."
1650                               errorCode = 7000
1651                        }
1652                         }
1653
1654                         // recreate WorkflowException to include the rollback Message
1655                         statusMessage =  statusMessage + rollbackNetworkErrorMessages + rollbackSdncErrorMessages
1656                         exceptionUtil.buildWorkflowException(execution, errorCode, statusMessage)
1657
1658                 } catch (Exception ex) {
1659                         execution.setVariable("WorkflowException", null)
1660                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstanceInfra flow. validateRollbackResponses() - " + ex.getMessage()
1661                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
1662                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
1663
1664                 }
1665
1666
1667
1668         }
1669
1670         // *******************************
1671         //     Build Error Section
1672         // *******************************
1673
1674         // Prepare for FalloutHandler
1675         public void buildErrorResponse (Execution execution) {
1676                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1677                 execution.setVariable("prefix", Prefix)
1678
1679                 utils.log("DEBUG", " ***** Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler. *****", isDebugEnabled)
1680
1681                 String dbReturnCode = execution.getVariable("CRENWKI_dbReturnCode")
1682                 utils.log("DEBUG", " ***** DB Update Response Code  : " + dbReturnCode, isDebugEnabled)
1683                 String createDBResponse =  execution.getVariable("CRENWKI_createDBResponse")
1684                 utils.log("DEBUG", " ***** DB Update Response String: " + '\n' + createDBResponse, isDebugEnabled)
1685                 utils.logAudit(createDBResponse)
1686
1687                 String falloutHandlerRequest = ""
1688                 String requestId = execution.getVariable("CRENWKI_requestId")
1689                 String source = execution.getVariable("CRENWKI_source")
1690                 try {
1691                         execution.setVariable("CRENWKI_Success", false)
1692                         WorkflowException wfe = execution.getVariable("WorkflowException")
1693                         String errorCode = String.valueOf(wfe.getErrorCode())
1694                         String errorMessage = wfe.getErrorMessage()
1695                         falloutHandlerRequest =
1696                             """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1"
1697                                                                      xmlns:ns="http://ecomp.att.com/mso/request/types/v1"
1698                                                                      xmlns:wfsch="http://ecomp.att.com/mso/workflow/schema/v1">
1699                                            <request-info xmlns="http://ecomp.att.com/mso/infra/vnf-request/v1">
1700                                               <request-id>${requestId}</request-id>
1701                                               <action>CREATE</action>
1702                                               <source>${source}</source>
1703                                            </request-info>
1704                                                 <aetgt:WorkflowException xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1">
1705                                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
1706                                                         <aetgt:ErrorCode>${errorCode}</aetgt:ErrorCode>
1707                                                 </aetgt:WorkflowException>
1708                                         </aetgt:FalloutHandlerRequest>"""
1709
1710                         utils.logAudit(falloutHandlerRequest)
1711                         execution.setVariable("CRENWKI_FalloutHandlerRequest", falloutHandlerRequest)
1712                         utils.log("DEBUG", "  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled)
1713
1714                 } catch (Exception ex) {
1715                         String errorException = "  Bpmn error encountered in CreateNetworkInstanceInfra flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
1716                         utils.log("DEBUG", errorException, isDebugEnabled)
1717                         falloutHandlerRequest =
1718                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1"
1719                                                                      xmlns:ns="http://ecomp.att.com/mso/request/types/v1"
1720                                                                      xmlns:wfsch="http://ecomp.att.com/mso/workflow/schema/v1">
1721                                            <request-info xmlns="http://ecomp.att.com/mso/infra/vnf-request/v1">
1722                                               <request-id>${requestId}</request-id>
1723                                               <action>CREATE</action>
1724                                               <source>${source}</source>
1725                                            </request-info>
1726                                                 <aetgt:WorkflowException xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1">
1727                                                         <aetgt:ErrorMessage>${errorException}</aetgt:ErrorMessage>
1728                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
1729                                                 </aetgt:WorkflowException>
1730                                         </aetgt:FalloutHandlerRequest>"""
1731
1732                         execution.setVariable("CRENWKI_FalloutHandlerRequest", falloutHandlerRequest)
1733                         utils.log("DEBUG", "  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled)
1734
1735                 }
1736
1737         }
1738
1739
1740         public void sendSyncError (Execution execution) {
1741                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1742                 execution.setVariable("prefix", Prefix)
1743
1744                 try {
1745
1746                         String requestId = execution.getVariable("att-mso-request-id")
1747
1748                         // REST Error (for API Handler (APIH) Reply Task)
1749                         String syncError = """{"requestReferences":{"instanceId":"","requestId":"${requestId}"}}""".trim()
1750
1751                         sendWorkflowResponse(execution, 500, syncError)
1752
1753                 } catch (Exception ex) {
1754                         utils.log("DEBUG", " Bpmn error encountered in CreateNetworkInstanceInfra flow. sendSyncError() - " + ex.getMessage(), isDebugEnabled)
1755                 }
1756
1757         }
1758
1759
1760         public void processJavaException(Execution execution){
1761                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1762                 execution.setVariable("prefix",Prefix)
1763                 try{
1764                         utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled)
1765                         utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled)
1766                         utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled)
1767                         execution.setVariable("UnexpectedError", "Caught a Java Lang Exception")  // Adding this line temporarily until this flows error handling gets updated
1768                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception")
1769                 }catch(BpmnError b){
1770                         utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugEnabled)
1771                         throw b
1772                 }catch(Exception e){
1773                         utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled)
1774                         execution.setVariable("UnexpectedError", "Exception in processJavaException method")  // Adding this line temporarily until this flows error handling gets updated
1775                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method")
1776                 }
1777                 utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled)
1778         }
1779
1780 }