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