Dynamic Cloud Owner Support
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoUpdateNetworkInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts;
22
23 import javax.ws.rs.core.UriBuilder
24
25 import org.apache.commons.lang3.*
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.delegate.DelegateExecution
28 import org.onap.so.bpmn.common.scripts.AaiUtil
29 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
30 import org.onap.so.bpmn.common.scripts.ExceptionUtil
31 import org.onap.so.bpmn.common.scripts.MsoUtils
32 import org.onap.so.bpmn.common.scripts.NetworkUtils
33 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
34 import org.onap.so.bpmn.common.scripts.VidUtils
35 import org.onap.so.bpmn.core.UrnPropertiesReader
36 import org.onap.so.bpmn.core.WorkflowException
37 import org.onap.so.bpmn.core.json.JsonUtils
38 import org.onap.so.client.aai.AAIObjectType
39 import org.onap.so.client.aai.AAIResourcesClient
40 import org.onap.so.client.aai.entities.uri.AAIResourceUri
41 import org.onap.so.client.aai.entities.uri.AAIUriFactory
42 import org.onap.so.client.aai.entities.AAIResultWrapper
43 import org.onap.so.client.graphinventory.entities.uri.Depth
44 import org.onap.so.constants.Defaults
45 import org.onap.so.logger.MsoLogger
46 import org.onap.so.rest.APIResponse
47 import org.springframework.web.util.UriUtils
48 import org.onap.aai.domain.yang.VpnBinding
49 import org.onap.aai.domain.yang.RouteTarget
50 import javax.ws.rs.NotFoundException
51
52 import groovy.json.*
53 import groovy.xml.XmlUtil
54
55 /**
56  * This groovy class supports the <class>DoUpdateNetworkInstance.bpmn</class> process.
57  *
58  */
59 public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor {
60         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoUpdateNetworkInstance.class);
61
62         String Prefix="UPDNETI_"
63         ExceptionUtil exceptionUtil = new ExceptionUtil()
64         JsonUtils jsonUtil = new JsonUtils()
65         VidUtils vidUtils = new VidUtils(this)
66         NetworkUtils networkUtils = new NetworkUtils()
67         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
68
69         /**
70          * This method is executed during the preProcessRequest task of the <class>DoUpdateNetworkInstance.bpmn</class> process.
71          * @param execution
72          */
73         public InitializeProcessVariables(DelegateExecution execution){
74                 /* Initialize all the process variables in this block */
75
76                 execution.setVariable(Prefix + "messageId", "")
77                 execution.setVariable("BasicAuthHeaderValuePO", "")
78                 execution.setVariable("BasicAuthHeaderValueSDNC", "")
79                 execution.setVariable(Prefix + "networkRequest", "")
80                 execution.setVariable(Prefix + "networkInputs", "")
81                 execution.setVariable(Prefix + "networkOutputs", "")
82                 execution.setVariable(Prefix + "requestId", "")
83                 execution.setVariable(Prefix + "source", "")
84                 execution.setVariable(Prefix + "networkId", "")
85
86                 execution.setVariable(Prefix + "isPONR", false)    // Point-of-no-return, means, rollback is not needed
87
88                 // AAI query Cloud Region
89                 execution.setVariable(Prefix + "queryCloudRegionRequest","")
90                 execution.setVariable(Prefix + "queryCloudRegionReturnCode","")
91                 execution.setVariable(Prefix + "queryCloudRegionResponse","")
92                 execution.setVariable(Prefix + "cloudRegionPo","")
93                 execution.setVariable(Prefix + "cloudRegionSdnc","")
94                 execution.setVariable(Prefix + "isCloudRegionGood", false)
95
96                 // AAI query Id
97                 execution.setVariable(Prefix + "queryIdAAIRequest","")
98                 execution.setVariable(Prefix + "queryIdAAIResponse", "")
99                 execution.setVariable(Prefix + "aaiIdReturnCode", "")
100
101                 // AAI query vpn binding
102                 execution.setVariable(Prefix + "queryVpnBindingAAIRequest","")
103                 execution.setVariable(Prefix + "queryVpnBindingAAIResponse", "")
104                 execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "")
105                 execution.setVariable(Prefix + "vpnBindings", null)
106                 execution.setVariable(Prefix + "vpnCount", 0)
107                 execution.setVariable(Prefix + "routeCollection", "")
108
109                 // AAI query network policy
110                 execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest","")
111                 execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", "")
112                 execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "")
113                 execution.setVariable(Prefix + "networkPolicyUriList", null)
114                 execution.setVariable(Prefix + "networkPolicyCount", 0)
115                 execution.setVariable(Prefix + "networkCollection", "")
116
117                 // AAI query route table reference
118                 execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest","")
119                 execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", "")
120                 execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "")
121                 execution.setVariable(Prefix + "networkTableRefUriList", null)
122                 execution.setVariable(Prefix + "networkTableRefCount", 0)
123                 execution.setVariable(Prefix + "tableRefCollection", "")
124
125                 // AAI requery Id
126                 execution.setVariable(Prefix + "requeryIdAAIRequest","")
127                 execution.setVariable(Prefix + "requeryIdAAIResponse", "")
128                 execution.setVariable(Prefix + "aaiRequeryIdReturnCode", "")
129
130                 // AAI update contrail
131                 execution.setVariable(Prefix + "updateContrailAAIUrlRequest","")
132                 execution.setVariable(Prefix + "updateContrailAAIPayloadRequest","")
133                 execution.setVariable(Prefix + "updateContrailAAIResponse", "")
134                 execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", "")
135
136                 execution.setVariable(Prefix + "updateNetworkRequest", "")
137                 execution.setVariable(Prefix + "updateNetworkResponse", "")
138                 execution.setVariable(Prefix + "rollbackNetworkRequest", "")
139                 execution.setVariable(Prefix + "networkReturnCode", "")
140                 execution.setVariable(Prefix + "isNetworkRollbackNeeded", false)
141
142                 execution.setVariable(Prefix + "changeAssignSDNCRequest", "")
143                 execution.setVariable(Prefix + "changeAssignSDNCResponse", "")
144                 execution.setVariable(Prefix + "rollbackSDNCRequest", "")
145                 execution.setVariable(Prefix + "sdncReturnCode", "")
146                 execution.setVariable(Prefix + "isSdncRollbackNeeded", false)
147                 execution.setVariable(Prefix + "sdncResponseSuccess", false)
148
149                 execution.setVariable(Prefix + "isVnfBindingPresent", false)
150                 execution.setVariable(Prefix + "Success", false)
151                 execution.setVariable(Prefix + "serviceInstanceId", "")
152
153                 execution.setVariable(Prefix + "isException", false)
154
155         }
156
157         // **************************************************
158         //     Pre or Prepare Request Section
159         // **************************************************
160         /**
161          * This method is executed during the preProcessRequest task of the <class>DoUpdateNetworkInstance.bpmn</class> process.
162          * @param execution
163          */
164         public void preProcessRequest (DelegateExecution execution) {
165
166                 execution.setVariable("prefix",Prefix)
167
168                 msoLogger.trace("Inside preProcessRequest DoUpdateNetworkInstance Request ")
169
170                 try {
171                         // initialize flow variables
172                         InitializeProcessVariables(execution)
173
174                         // GET Incoming request & validate 3 kinds of format.
175                         execution.setVariable("action", "UPDATE")
176                         String networkRequest = execution.getVariable("bpmnRequest")
177                         if (networkRequest != null) {
178                                 if (networkRequest.contains("requestDetails")) {
179                                         // JSON format request is sent, create xml
180                                         try {
181                                                 def prettyJson = JsonOutput.prettyPrint(networkRequest.toString())
182                                                 msoLogger.debug(" Incoming message formatted . . . : " + '\n' + prettyJson)
183                                                 networkRequest =  vidUtils.createXmlNetworkRequestInfra(execution, networkRequest)
184
185                                         } catch (Exception ex) {
186                                                 String dataErrorMessage = " Invalid json format Request - " + ex.getMessage()
187                                                 msoLogger.debug(dataErrorMessage)
188                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
189                                         }
190                                 } else {
191                                          // XML format request is sent
192
193                                 }
194                         } else {
195                                 // vIPR format request is sent, create xml from individual variables
196                                 networkRequest = vidUtils.createXmlNetworkRequestInstance(execution)
197                         }
198
199                         networkRequest = utils.formatXml(networkRequest)
200                         msoLogger.debug(networkRequest)
201                         execution.setVariable(Prefix + "networkRequest", networkRequest)
202                         msoLogger.debug(" network-request - " + '\n' + networkRequest)
203
204                         // validate 'disableRollback'  (aka, 'suppressRollback')
205                         boolean rollbackEnabled = networkUtils.isRollbackEnabled(execution, networkRequest)
206                         execution.setVariable(Prefix + "rollbackEnabled", rollbackEnabled)
207                         msoLogger.debug(Prefix + "rollbackEnabled - " + rollbackEnabled)
208
209                         String networkInputs = utils.getNodeXml(networkRequest, "network-inputs", false).replace("tag0:","").replace(":tag0","")
210                         execution.setVariable(Prefix + "networkInputs", networkInputs)
211                         msoLogger.debug(Prefix + "networkInputs - " + '\n' + networkInputs)
212
213                         // prepare messageId
214                         String messageId = execution.getVariable(Prefix + "messageId")  // for testing
215                         if (messageId == null || messageId == "") {
216                                 messageId = UUID.randomUUID()
217                                 msoLogger.debug(" UPDNETI_messageId, random generated: " + messageId)
218                         } else {
219                                 msoLogger.debug(" UPDNETI_messageId, pre-assigned: " + messageId)
220                         }
221                         execution.setVariable(Prefix + "messageId", messageId)
222
223                         String source = utils.getNodeText(networkRequest, "source")
224                         execution.setVariable(Prefix + "source", source)
225                         msoLogger.debug(Prefix + "source - " + source)
226
227                         String networkId = ""
228                         if (utils.nodeExists(networkRequest, "network-id")) {
229                                 networkId = utils.getNodeText(networkRequest, "network-id")
230                                 if (networkId == 'null' || networkId == "") {
231                                         sendSyncError(execution)
232                                         // missing value of networkId
233                                         String dataErrorMessage = "Variable 'network-id' value/element is missing."
234                                         msoLogger.debug(" Invalid Request - " + dataErrorMessage)
235                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
236
237                                 }
238                         }
239
240                         String lcpCloudRegion = ""
241                         if (utils.nodeExists(networkRequest, "aic-cloud-region")) {
242                                 lcpCloudRegion = utils.getNodeText(networkRequest, "aic-cloud-region")
243                                 if ((lcpCloudRegion == 'null') || (lcpCloudRegion == "")) {
244                                         sendSyncError(execution)
245                                         String dataErrorMessage = "requestDetails has missing 'aic-cloud-region' value/element."
246                                         msoLogger.debug(" Invalid Request - " + dataErrorMessage)
247                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
248                                 }
249                         }
250
251                         String serviceInstanceId = ""
252                         if (utils.nodeExists(networkRequest, "service-instance-id")) {
253                                 serviceInstanceId = utils.getNodeText(networkRequest, "service-instance-id")
254                                 if ((serviceInstanceId == 'null') || (lcpCloudRegion == "")) {
255                                         sendSyncError(execution)
256                                         String dataErrorMessage = "Variable 'serviceInstanceId' value/element is missing."
257                                         msoLogger.debug(" Invalid Request - " + dataErrorMessage)
258                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
259                                 }
260                         }
261
262                         // PO Authorization Info / headers Authorization=
263                         String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution)
264
265
266                         try {
267                                 def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution))
268                                 execution.setVariable("BasicAuthHeaderValuePO",encodedString)
269                                 execution.setVariable("BasicAuthHeaderValueSDNC", encodedString)
270
271                         } catch (IOException ex) {
272                                 String exceptionMessage = "Exception Encountered in DoUpdateNetworkInstance, PreProcessRequest() - "
273                                 String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage()
274                                 msoLogger.debug(dataErrorMessage)
275                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
276                         }
277
278                         // Set variables for Generic Get Sub Flow use
279                         execution.setVariable(Prefix + "serviceInstanceId", serviceInstanceId)
280                         msoLogger.debug(Prefix + "serviceInstanceId - " + serviceInstanceId)
281
282                         msoLogger.debug(" Url for SDNC adapter: " + UrnPropertiesReader.getVariable("mso.adapters.sdnc.endpoint",execution))
283
284                         String sdncVersion = execution.getVariable("sdncVersion")
285                         msoLogger.debug("sdncVersion? : " + sdncVersion)
286
287                         // build 'networkOutputs'
288                         networkId = utils.getNodeText(networkRequest, "network-id")
289                         if ((networkId == null) || (networkId == "null")) {
290                                 networkId = ""
291                         }
292                         String networkName = utils.getNodeText(networkRequest, "network-name")
293                         if ((networkName == null) || (networkName == "null")) {
294                                 networkName = ""
295                         }
296                         String networkOutputs =
297                            """<network-outputs>
298                            <network-id>${MsoUtils.xmlEscape(networkId)}</network-id>
299                            <network-name>${MsoUtils.xmlEscape(networkName)}</network-name>
300                          </network-outputs>"""
301                         execution.setVariable(Prefix + "networkOutputs", networkOutputs)
302                         msoLogger.debug(Prefix + "networkOutputs - " + '\n' + networkOutputs)
303                         execution.setVariable(Prefix + "networkId", networkId)
304                         execution.setVariable(Prefix + "networkName", networkName)
305
306
307                 } catch (BpmnError e) {
308                         throw e;
309
310                 } catch (Exception ex){
311                         sendSyncError(execution)
312                          // caught exception
313                         String exceptionMessage = "Exception Encountered in DoUpdateNetworkInstance, PreProcessRequest() - " + ex.getMessage()
314                         msoLogger.debug(exceptionMessage)
315                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
316
317                 }
318         }
319
320         /**
321          * Gets the service instance uri from aai
322          *
323          */
324         public void getServiceInstance(DelegateExecution execution) {
325                 msoLogger.trace("getServiceInstance ")
326                 try {
327                         String serviceInstanceId = execution.getVariable('serviceInstanceId')
328
329                         AAIResourcesClient resourceClient = new AAIResourcesClient()
330                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)
331
332                         if(!resourceClient.exists(uri)){
333                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Service Instance not found in aai")
334                         }else{
335                                 Map<String, String> keys = uri.getURIKeys()
336                                 execution.setVariable("serviceType", keys.get("service-type"))
337                                 execution.setVariable("subscriberName", keys.get("global-customer-id"))
338                         }
339
340                 }catch(BpmnError e) {
341                         throw e;
342                 }catch (Exception ex){
343                         String msg = "Exception in getServiceInstance. " + ex.getMessage()
344                         msoLogger.debug(msg)
345                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
346                 }
347         }
348
349         public void callRESTQueryAAICloudRegion (DelegateExecution execution) {
350
351                 execution.setVariable("prefix", Prefix)
352
353                 msoLogger.debug(" ***** Inside callRESTQueryAAICloudRegion of DoUpdateNetworkInstance ***** " )
354
355                 try {
356                         String networkInputs  = execution.getVariable(Prefix + "networkInputs")
357                         String cloudRegion = utils.getNodeText(networkInputs, "aic-cloud-region")
358
359                         // Prepare AA&I url
360                         String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
361                         AaiUtil aaiUtil = new AaiUtil(this)
362
363                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, Defaults.CLOUD_OWNER.toString(), cloudRegion)
364                         def queryCloudRegionRequest = aaiUtil.createAaiUri(uri)
365
366                         execution.setVariable(Prefix + "queryCloudRegionRequest", queryCloudRegionRequest)
367
368                         String cloudRegionPo = aaiUtil.getAAICloudReqion(execution,  queryCloudRegionRequest, "PO", cloudRegion)
369                         String cloudRegionSdnc = aaiUtil.getAAICloudReqion(execution,  queryCloudRegionRequest, "SDNC", cloudRegion)
370
371                         if ((cloudRegionPo != "ERROR") && (cloudRegionSdnc != "ERROR")) {
372                                 execution.setVariable(Prefix + "cloudRegionPo", cloudRegionPo)
373                                 execution.setVariable(Prefix + "cloudRegionSdnc", cloudRegionSdnc)
374                                 execution.setVariable(Prefix + "isCloudRegionGood", true)
375
376                         } else {
377                             String dataErrorMessage = "QueryAAICloudRegion Unsuccessful. Return Code: " + execution.getVariable(Prefix + "queryCloudRegionReturnCode")
378                             msoLogger.debug(dataErrorMessage)
379                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
380
381                         }
382
383                         msoLogger.debug(" is Cloud Region Good: " + execution.getVariable(Prefix + "isCloudRegionGood"))
384
385                 } catch (BpmnError e) {
386                         throw e;
387
388                 } catch (Exception ex) {
389                         // try error
390                         String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow - callRESTQueryAAICloudRegion() - " + ex.getMessage()
391                         msoLogger.debug(exceptionMessage)
392                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
393
394                 }
395
396         }
397
398         public void callRESTQueryAAINetworkId(DelegateExecution execution) {
399
400                 execution.setVariable("prefix", Prefix)
401
402                 msoLogger.debug(" ***** Inside callRESTQueryAAINetworkId of DoUpdateNetworkInstance ***** " )
403
404                 try {
405                         // get variables
406                         String networkRequest = execution.getVariable(Prefix + "networkRequest")
407                         String networkId   = utils.getNodeText(networkRequest, "network-id")
408                         networkId = UriUtils.encode(networkId,"UTF-8")
409                         execution.setVariable(Prefix + "networkId", networkId)
410
411                         // Prepare AA&I url
412                         AaiUtil aaiUriUtil = new AaiUtil(this)
413                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)
414                         uri.depth(Depth.ALL)
415                         String queryIdAAIRequest = aaiUriUtil.createAaiUri(uri)
416
417                         msoLogger.debug(queryIdAAIRequest)
418                         execution.setVariable(Prefix + "queryIdAAIRequest", queryIdAAIRequest)
419                         msoLogger.debug(Prefix + "queryIdAAIRequest - " + "\n" + queryIdAAIRequest)
420
421                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryIdAAIRequest)
422                         String returnCode = response.getStatusCode()
423                         execution.setVariable(Prefix + "aaiIdReturnCode", returnCode)
424                         msoLogger.debug(" ***** AAI Response Code  : " + returnCode)
425
426                         String aaiResponseAsString = response.getResponseBodyAsString()
427
428                         if (returnCode=='200') {
429                                 msoLogger.debug(aaiResponseAsString)
430                                 execution.setVariable(Prefix + "queryIdAAIResponse", aaiResponseAsString)
431                                 msoLogger.debug(" QueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString)
432
433                         } else {
434                                 if (returnCode=='404') {
435                                         String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)."
436                                         msoLogger.debug(" AAI Query Failed. " + dataErrorMessage)
437                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
438
439                                 } else {
440                                    if (aaiResponseAsString.contains("RESTFault")) {
441                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
442                                            execution.setVariable("WorkflowException", exceptionObject)
443                                            throw new BpmnError("MSOWorkflowException")
444
445                                    } else {
446                                                         // aai all errors
447                                                         String dataErrorMessage = "Unexpected Response from QueryAAINetworkId - " + returnCode
448                                                         msoLogger.debug("Unexpected Response from QueryAAINetworkId - " + dataErrorMessage)
449                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
450
451                                   }
452                                 }
453                         }
454
455                 } catch (BpmnError e) {
456                         throw e;
457
458                 } catch (Exception ex) {
459                         String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkId() - " + ex.getMessage()
460                         msoLogger.debug(exceptionMessage)
461                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
462
463                 }
464
465         }
466
467         public void callRESTReQueryAAINetworkId(DelegateExecution execution) {
468
469                 execution.setVariable("prefix", Prefix)
470
471                 msoLogger.debug(" ***** Inside callRESTReQueryAAINetworkId of DoUpdateNetworkInstance ***** " )
472
473                 try {
474                         // get variables
475                         String networkRequest = execution.getVariable(Prefix + "networkRequest")
476                         String networkId   = utils.getNodeText(networkRequest, "network-id")
477                         networkId = UriUtils.encode(networkId,"UTF-8")
478
479                         // Prepare AA&I url
480                         AaiUtil aaiUriUtil = new AaiUtil(this)
481                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)
482                         uri.depth(Depth.ALL)
483                         String requeryIdAAIRequest = aaiUriUtil.createAaiUri(uri)
484
485                         msoLogger.debug(requeryIdAAIRequest)
486                         execution.setVariable(Prefix + "requeryIdAAIRequest", requeryIdAAIRequest)
487                         msoLogger.debug(" UPDNETI_requeryIdAAIRequest - " + "\n" + requeryIdAAIRequest)
488
489                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, requeryIdAAIRequest)
490                         String returnCode = response.getStatusCode()
491                         execution.setVariable(Prefix + "aaiRequeryIdReturnCode", returnCode)
492                         msoLogger.debug(" ***** AAI ReQuery Response Code  : " + returnCode)
493
494                         String aaiResponseAsString = response.getResponseBodyAsString()
495
496                         if (returnCode=='200') {
497                                 msoLogger.debug(aaiResponseAsString)
498                                 execution.setVariable(Prefix + "requeryIdAAIResponse", aaiResponseAsString)
499                                 msoLogger.debug(" ReQueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString)
500
501                                 String netId = utils.getNodeText(aaiResponseAsString, "network-id")
502                                 String netName = utils.getNodeText(aaiResponseAsString, "network-name")
503                                 String networkOutputs =
504                                    """<network-outputs>
505                    <network-id>${MsoUtils.xmlEscape(netId)}</network-id>
506                    <network-name>${MsoUtils.xmlEscape(netName)}</network-name>
507                  </network-outputs>"""
508                                 execution.setVariable(Prefix + "networkOutputs", networkOutputs)
509                                 msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs)
510
511                         } else {
512                                 if (returnCode=='404') {
513                                         String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)."
514                                         msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage)
515                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
516
517                                 } else {
518                                    if (aaiResponseAsString.contains("RESTFault")) {
519                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
520                                            execution.setVariable("WorkflowException", exceptionObject)
521                                            throw new BpmnError("MSOWorkflowException")
522
523                                            } else {
524                                                         // aai all errors
525                                                         String dataErrorMessage = "Unexpected Response from ReQueryAAINetworkId - " + returnCode
526                                                         msoLogger.debug(dataErrorMessage)
527                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
528
529                                         }
530                                 }
531                         }
532
533                 } catch (BpmnError e) {
534                         throw e;
535
536                 } catch (Exception ex) {
537                         String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTReQueryAAINetworkId() - " + ex.getMessage()
538                         msoLogger.debug(exceptionMessage)
539                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
540
541                 }
542
543         }
544
545         public void callRESTQueryAAINetworkVpnBinding(DelegateExecution execution) {
546
547                 execution.setVariable("prefix", Prefix)
548
549                 msoLogger.debug(" ***** Inside callRESTQueryAAINetworkVpnBinding of DoUpdateNetworkInstance ***** " )
550
551                 try {
552
553                         // get variables
554                         String queryIdAAIResponse   = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "")
555                         String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","")
556                         msoLogger.debug(" relationship - " + relationship)
557
558                         // Check if Vnf Binding is present, then build a List of vnfBinding
559                         List vpnBindingUri = networkUtils.getVnfBindingObject(relationship)
560                         int vpnCount = vpnBindingUri.size()
561                         execution.setVariable(Prefix + "vpnCount", vpnCount)
562                         msoLogger.debug(" UPDNETI_vpnCount - " + vpnCount)
563
564                         if (vpnCount > 0) {
565                                 execution.setVariable(Prefix + "vpnBindings", vpnBindingUri)
566                                 msoLogger.debug(" vpnBindingUri List - " + vpnBindingUri)
567
568                                 String routeTargets = ""
569                                 // AII loop call using list vpnBindings
570                                 for(i in 0..vpnBindingUri.size()-1) {
571                                         int counting = i+1
572
573                                         String vpnBindingId = vpnBindingUri[i].substring(vpnBindingUri[i].indexOf("/vpn-binding/")+13, vpnBindingUri[i].length())
574                                         if (vpnBindingId.charAt(vpnBindingId.length()-1) == '/') {
575                                                 vpnBindingId = vpnBindingId.substring(0, vpnBindingId.length()-1)
576                                         }
577
578                                         AAIResourcesClient resourceClient = new AAIResourcesClient()
579                                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnBindingId)
580                                         AAIResultWrapper wrapper = resourceClient.get(uri.depth(Depth.TWO), NotFoundException.class)
581
582                                         Optional<VpnBinding> binding = wrapper.asBean(VpnBinding.class)
583
584                                         String routeTarget = ""
585                                         String routeRole = ""
586                                         if(binding.get().getRouteTargets() != null) {
587                                                 List<RouteTarget> targets = binding.get().getRouteTargets().getRouteTarget()
588                                                 for(RouteTarget target : targets) {
589                                                         routeTarget  = target.getGlobalRouteTarget()
590                                                         routeRole  = target.getRouteTargetRole()
591                                                         routeTargets += "<routeTargets>" + '\n' +
592                                                                         " <routeTarget>" + routeTarget + "</routeTarget>" + '\n' +
593                                                                         " <routeTargetRole>" + routeRole + "</routeTargetRole>" + '\n' +
594                                                                         "</routeTargets>" + '\n'
595                                                 }
596                                         }
597
598                                 } // end loop
599
600                                 execution.setVariable(Prefix + "routeCollection", routeTargets)
601                                 msoLogger.debug(" UPDNETI_routeCollection - " + '\n' + routeTargets)
602
603                         } else {
604                                 // reset return code to success
605                                 execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200")
606                                 AaiUtil aaiUriUtil = new AaiUtil(this)
607                                 String schemaVersion = aaiUriUtil.getNamespace()
608                             String aaiStubResponse =
609                                         """     <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd">
610                                                         <vpn-binding xmlns="${schemaVersion}">
611                                                       <global-route-target/>
612                                                         </vpn-binding>
613                                                 </rest:payload>"""
614                                 String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse)
615                                 execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml)
616                                 execution.setVariable(Prefix + "routeCollection", "<routeTargets/>")
617                                 msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml)
618
619                         }
620
621                 } catch (NotFoundException e) {
622                         msoLogger.debug("Response Error from AAINetworkVpnBinding is 404 (Not Found).")
623                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Response Error from AAINetworkVpnBinding is 404 (Not Found).")
624                 } catch (Exception ex) {
625                         String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkVpnBinding() - " + ex.getMessage()
626                         msoLogger.debug(exceptionMessage)
627                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
628
629                 }
630
631         }
632
633         public void callRESTQueryAAINetworkPolicy(DelegateExecution execution) {
634
635                 execution.setVariable("prefix", Prefix)
636
637                 msoLogger.debug(" ***** Inside callRESTQueryAAINetworkPolicy of DoUpdateNetworkInstance ***** " )
638
639                 try {
640                         // get variables
641                         String queryIdAAIResponse   = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "")
642                         String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","")
643                         msoLogger.debug(" relationship - " + relationship)
644
645                         // Check if Network Policy is present, then build a List of network policy
646                         List networkPolicyUriList = networkUtils.getNetworkPolicyObject(relationship)
647                         int networkPolicyCount = networkPolicyUriList.size()
648                         execution.setVariable(Prefix + "networkPolicyCount", networkPolicyCount)
649                         msoLogger.debug(" UPDNETI_networkPolicyCount - " + networkPolicyCount)
650
651                         AaiUtil aaiUriUtil = new AaiUtil(this)
652
653                         if (networkPolicyCount > 0) {
654                                 execution.setVariable(Prefix + "networkPolicyUriList", networkPolicyUriList)
655                                 msoLogger.debug(" networkPolicyUri List - " + networkPolicyUriList)
656
657                                 String networkPolicies = ""
658                                 // AII loop call using list vpnBindings
659                                 for (i in 0..networkPolicyUriList.size()-1) {
660
661                                         int counting = i+1
662
663                                         URI uri = UriBuilder.fromUri(networkPolicyUriList[i]).build()
664
665                                         AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.NETWORK_POLICY, uri)
666                                         aaiUri.depth(Depth.ALL)
667                                         String queryNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(aaiUri)
668
669                                         msoLogger.debug(queryNetworkPolicyAAIRequest)
670                                         execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest", queryNetworkPolicyAAIRequest)
671                                         msoLogger.debug(" UPDNETI_queryNetworkPolicyAAIRequest, , NetworkPolicy #" + counting + " : " + "\n" + queryNetworkPolicyAAIRequest)
672
673                                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyAAIRequest)
674                                         String returnCode = response.getStatusCode()
675                                         execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", returnCode)
676                                         msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode)
677
678                                         String aaiResponseAsString = response.getResponseBodyAsString()
679
680                                         if (returnCode=='200') {
681                                                 msoLogger.debug(aaiResponseAsString)
682                                                 execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiResponseAsString)
683                                                 msoLogger.debug(" QueryAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString)
684
685                                                 String networkPolicy = ""
686                                                 if (utils.nodeExists(aaiResponseAsString, "network-policy-fqdn")) {
687                                                         networkPolicy  = utils.getNodeText(aaiResponseAsString, "network-policy-fqdn")
688                                                         networkPolicies += "<policyFqdns>" + networkPolicy + "</policyFqdns>" + '\n'
689                                                 }
690
691                                         } else {
692                                                 if (returnCode=='404') {
693                                                         String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)."
694                                                         msoLogger.debug(dataErrorMessage)
695                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
696
697                                                 } else {
698                                                    if (aaiResponseAsString.contains("RESTFault")) {
699                                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
700                                                            execution.setVariable("WorkflowException", exceptionObject)
701                                                            throw new BpmnError("MSOWorkflowException")
702
703                                                            } else {
704                                                                         // aai all errors
705                                                                         String dataErrorMessage = "Unexpected Response from QueryAAINetworkPolicy - " + returnCode
706                                                                         msoLogger.debug(dataErrorMessage)
707                                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
708
709                                                           }
710                                                 }
711                                         }
712
713                                 } // end loop
714
715                                 execution.setVariable(Prefix + "networkCollection", networkPolicies)
716                                 msoLogger.debug(" UPDNETI_networkCollection - " + '\n' + networkPolicies)
717
718                         } else {
719                                 // reset return code to success
720                                 execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200")
721                                 String schemaVersion = aaiUriUtil.getNamespace()
722                                 String aaiStubResponse =
723                                         """     <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd">
724                                                         <network-policy xmlns="${schemaVersion}">
725                                                           <network-policy-fqdn/>
726                             </network-policy>
727                                                 </rest:payload>"""
728                                 String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse)
729                                 execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml)
730                                 execution.setVariable(Prefix + "networkCollection", "<policyFqdns/>")
731                                 msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml)
732
733                         }
734
735                 } catch (BpmnError e) {
736                         throw e;
737
738                 } catch (Exception ex) {
739                         String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage()
740                         msoLogger.debug(exceptionMessage)
741                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
742
743                 }
744
745         }
746
747         public void callRESTQueryAAINetworkTableRef(DelegateExecution execution) {
748
749                 execution.setVariable("prefix", Prefix)
750
751                 msoLogger.debug(" ***** Inside callRESTQueryAAINetworkTableRef of DoUpdateNetworkInstance ***** " )
752
753                 try {
754                         // get variables
755                         String queryIdAAIResponse   = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "")
756                         String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","")
757                         msoLogger.debug(" relationship - " + relationship)
758
759                         // Check if Network TableREf is present, then build a List of network policy
760                         List networkTableRefUriList = networkUtils.getNetworkTableRefObject(relationship)
761                         int networkTableRefCount = networkTableRefUriList.size()
762                         execution.setVariable(Prefix + "networkTableRefCount", networkTableRefCount)
763                         msoLogger.debug(" UPDNETI_networkTableRefCount - " + networkTableRefCount)
764
765                         String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
766                         AaiUtil aaiUriUtil = new AaiUtil(this)
767
768                         if (networkTableRefCount > 0) {
769                                 execution.setVariable(Prefix + "networkTableRefUriList", networkTableRefUriList)
770                                 msoLogger.debug(" networkTableRefUri List - " + networkTableRefUriList)
771
772                                 // AII loop call using list vpnBindings
773                                 String networkTableRefs = ""
774                                 for (i in 0..networkTableRefUriList.size()-1) {
775
776                                         int counting = i+1
777
778                                         // prepare url using tableRef
779                                         URI uri = UriBuilder.fromUri(networkTableRefUriList[i]).build()
780
781                                         AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ROUTE_TABLE_REFERENCE, uri)
782                                         aaiUri.depth(Depth.ALL)
783                                         String queryNetworkTableRefAAIRequest = aaiUriUtil.createAaiUri(aaiUri)
784
785                                         msoLogger.debug(queryNetworkTableRefAAIRequest)
786                                         execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest", queryNetworkTableRefAAIRequest)
787                                         msoLogger.debug(" UPDNETI_queryNetworkTableRefAAIRequest, , NetworkTableRef #" + counting + " : " + "\n" + queryNetworkTableRefAAIRequest)
788
789                                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkTableRefAAIRequest)
790                                         String returnCode = response.getStatusCode()
791                                         execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", returnCode)
792                                         msoLogger.debug(" ***** AAI query network Table Reference Response Code, NetworkTableRef #" + counting + " : " + returnCode)
793
794                                         String aaiResponseAsString = response.getResponseBodyAsString()
795
796                                         if (returnCode=='200') {
797                                                 msoLogger.debug(aaiResponseAsString)
798                                                 execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiResponseAsString)
799                                                 msoLogger.debug(" QueryAAINetworkTableRef Success REST Response, , NetworkTableRef #" + counting + " : " + "\n" + aaiResponseAsString)
800
801                                                 String networkTableRef = ""
802                                                 if (utils.nodeExists(aaiResponseAsString, "route-table-reference-fqdn")) {
803                                                         networkTableRef  = utils.getNodeText(aaiResponseAsString, "route-table-reference-fqdn")
804                                                         networkTableRefs += "<routeTableFqdns>" + networkTableRef + "</routeTableFqdns>" + '\n'
805                                                 }
806
807                                         } else {
808                                                 if (returnCode=='404') {
809                                                         String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)."
810                                                         msoLogger.debug(dataErrorMessage)
811                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
812
813                                                 } else {
814                                                    if (aaiResponseAsString.contains("RESTFault")) {
815                                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
816                                                            execution.setVariable("WorkflowException", exceptionObject)
817                                                            throw new BpmnError("MSOWorkflowException")
818
819                                                            } else {
820                                                                         // aai all errors
821                                                                         String dataErrorMessage = "Unexpected Response from QueryAAINetworkTableRef - " + returnCode
822                                                                         msoLogger.debug(dataErrorMessage)
823                                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
824
825                                                           }
826                                                 }
827                                         }
828
829                                 } // end loop
830
831                                 execution.setVariable(Prefix + "tableRefCollection", networkTableRefs)
832                                 msoLogger.debug(" UPDNETI_tableRefCollection - " + '\n' + networkTableRefs)
833
834                         } else {
835                                 // reset return code to success
836                                 execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200")
837                                 String schemaVersion = aaiUriUtil.getNamespace()
838                                 String aaiStubResponse =
839                                         """     <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd">
840                                                         <route-table-references xmlns="${schemaVersion}">
841                                                           <route-table-reference-fqdn/>
842                             </route-table-references>
843                                                 </rest:payload>"""
844                                 String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse)
845                                 execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml)
846                                 execution.setVariable(Prefix + "tableRefCollection", "<routeTableFqdns/>")
847                                 msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml)
848
849                         }
850
851                 } catch (BpmnError e) {
852                         throw e;
853
854                 } catch (Exception ex) {
855                         String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkTableRef() - " + ex.getMessage()
856                         msoLogger.debug(exceptionMessage)
857                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
858
859                 }
860
861         }
862
863         public void callRESTUpdateContrailAAINetwork(DelegateExecution execution) {
864
865                 execution.setVariable("prefix", Prefix)
866
867                 msoLogger.debug(" ***** Inside callRESTUpdateContrailAAINetwork of DoUpdateNetworkInstance ***** " )
868
869                 try {
870                         // get variables
871                         String networkRequest = execution.getVariable(Prefix + "networkRequest")
872                         String networkId   = utils.getNodeText(networkRequest, "network-id")
873                         networkId = UriUtils.encode(networkId,"UTF-8")
874                         String requeryIdAAIResponse   = execution.getVariable(Prefix + "requeryIdAAIResponse")
875                         String updateNetworkResponse   = execution.getVariable(Prefix + "updateNetworkResponse")
876
877                         // Prepare url
878                         AaiUtil aaiUriUtil = new AaiUtil(this)
879                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)
880                         uri.depth(Depth.ALL)
881                         String updateContrailAAIUrlRequest = aaiUriUtil.createAaiUri(uri)
882
883                         msoLogger.debug(updateContrailAAIUrlRequest)
884                         execution.setVariable(Prefix + "updateContrailAAIUrlRequest", updateContrailAAIUrlRequest)
885                         msoLogger.debug(" UPDNETI_updateContrailAAIUrlRequest - " + "\n" + updateContrailAAIUrlRequest)
886
887                         //Prepare payload (PUT)
888                         String schemaVersion = aaiUriUtil.getNamespaceFromUri(updateContrailAAIUrlRequest)
889                         String payload = networkUtils.ContrailNetworkCreatedUpdate(requeryIdAAIResponse, updateNetworkResponse, schemaVersion)
890                         String payloadXml = utils.formatXml(payload)
891                         msoLogger.debug(payloadXml)
892                         execution.setVariable(Prefix + "updateContrailAAIPayloadRequest", payloadXml)
893                         msoLogger.debug(" 'payload' to Update Contrail - " + "\n" + payloadXml)
894
895                         APIResponse response = aaiUriUtil.executeAAIPutCall(execution, updateContrailAAIUrlRequest, payload)
896                         String returnCode = response.getStatusCode()
897                         String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString()
898
899                         execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", returnCode)
900                         msoLogger.debug(" ***** AAI Update Contrail Response Code  : " + returnCode)
901
902
903                         if (returnCode=='200') {
904                                 msoLogger.debug(aaiUpdateContrailResponseAsString)
905                                 execution.setVariable(Prefix + "updateContrailAAIResponse", aaiUpdateContrailResponseAsString)
906                                 msoLogger.debug(" AAI Update Contrail Success REST Response - " + "\n" + aaiUpdateContrailResponseAsString)
907                                 // Point-of-no-return is set to false, rollback not needed.
908                                 execution.setVariable(Prefix + "isPONR", true)
909
910                         } else {
911                                 if (returnCode=='404') {
912                                         String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)."
913                                         msoLogger.debug(dataErrorMessage)
914                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
915
916                                 } else {
917                                    if (aaiUpdateContrailResponseAsString.contains("RESTFault")) {
918                                            WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiUpdateContrailResponseAsString, execution)
919                                            execution.setVariable("WorkflowException", exceptionObject)
920                                            throw new BpmnError("MSOWorkflowException")
921
922                                            } else {
923                                                         // aai all errors
924                                                         String errorMessage = "Unexpected Response from UpdateContrailAAINetwork - " + returnCode
925                                                         msoLogger.debug(errorMessage)
926                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
927                                           }
928                                 }
929                         }
930
931                 } catch (BpmnError e) {
932                         throw e;
933
934                 } catch (Exception ex) {
935                         String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTUpdateContrailAAINetwork() - " + ex.getMessage()
936                         msoLogger.debug(exceptionMessage)
937                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
938
939                 }
940
941         }
942
943         public void prepareUpdateNetworkRequest (DelegateExecution execution) {
944
945                 execution.setVariable("prefix", Prefix)
946
947                 msoLogger.trace("Inside prepareUpdateNetworkRequest of DoUpdateNetworkInstance ")
948
949                 try {
950
951                         // get variables
952                         String requestId = execution.getVariable(Prefix + "requestId")
953                         String messageId = execution.getVariable(Prefix + "messageId")
954                         String source    = execution.getVariable(Prefix + "source")
955
956                         String requestInput = execution.getVariable(Prefix + "networkRequest")
957                         String queryIdResponse = execution.getVariable(Prefix + "requeryIdAAIResponse")
958                         String cloudRegionId = execution.getVariable(Prefix + "cloudRegionPo")
959                         String backoutOnFailure = execution.getVariable(Prefix + "rollbackEnabled")
960
961                         // Prepare Network request
962                         String routeCollection = execution.getVariable(Prefix + "routeCollection")
963                         String policyCollection = execution.getVariable(Prefix + "networkCollection")
964                         String tableCollection = execution.getVariable(Prefix + "tableRefCollection")
965                         String updateNetworkRequest = networkUtils.UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyCollection, tableCollection, cloudRegionId, backoutOnFailure, source )
966                         // Format Response
967                         String buildUpdateNetworkRequestAsString = utils.formatXml(updateNetworkRequest)
968                         buildUpdateNetworkRequestAsString = buildUpdateNetworkRequestAsString.replace(":w1aac13n0", "").replace("w1aac13n0:", "")
969                         msoLogger.debug(buildUpdateNetworkRequestAsString)
970
971                         execution.setVariable(Prefix + "updateNetworkRequest", buildUpdateNetworkRequestAsString)
972                         msoLogger.debug(" UPDNETI_updateNetworkRequest - " + "\n" +  buildUpdateNetworkRequestAsString)
973
974                 } catch (Exception ex) {
975                         String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareUpdateNetworkRequest() - " + ex.getMessage()
976                         msoLogger.debug(exceptionMessage)
977                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
978
979                 }
980
981         }
982
983         public void prepareSDNCRequest (DelegateExecution execution) {
984
985                 execution.setVariable("prefix", Prefix)
986
987                 msoLogger.trace("Inside prepareSDNCRequest of DoUpdateNetworkInstance ")
988
989                 try {
990                         // get variables
991                         String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution)
992                         String updateNetworkInput = execution.getVariable(Prefix + "networkRequest")
993                         String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc")
994
995                         String networkId = ""
996                         if (utils.nodeExists(updateNetworkInput, "network-id")) {
997                            networkId = utils.getNodeText(updateNetworkInput, "network-id")
998                         }
999                         if (networkId == null) {networkId = ""}
1000
1001                         String serviceInstanceId = utils.getNodeText(updateNetworkInput, "service-instance-id")
1002
1003                         String queryAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse")
1004
1005                         // 1. prepare assign topology via SDNC Adapter SUBFLOW call
1006                         String sndcTopologyCreateRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, updateNetworkInput, serviceInstanceId, sdncCallback, "changeassign", "NetworkActivateRequest", cloudRegionId, networkId, queryAAIResponse, null)
1007
1008                         String sndcTopologyUpdateRequesAsString = utils.formatXml(sndcTopologyCreateRequest)
1009                         msoLogger.debug(sndcTopologyUpdateRequesAsString)
1010                         execution.setVariable(Prefix + "changeAssignSDNCRequest", sndcTopologyUpdateRequesAsString)
1011                         msoLogger.debug(" UPDNETI_changeAssignSDNCRequest - " + "\n" +  sndcTopologyUpdateRequesAsString)
1012
1013
1014                 } catch (Exception ex) {
1015                         String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareSDNCRequest() - " + ex.getMessage()
1016                         msoLogger.debug(exceptionMessage)
1017                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1018
1019                 }
1020
1021         }
1022
1023
1024
1025
1026         // **************************************************
1027         //     Post or Validate Response Section
1028         // **************************************************
1029
1030         public void validateUpdateNetworkResponse (DelegateExecution execution) {
1031
1032                 execution.setVariable("prefix", Prefix)
1033
1034                 msoLogger.trace("Inside validateUpdateNetworkResponse of DoUpdateNetworkInstance ")
1035
1036                 try {
1037                         String returnCode = execution.getVariable(Prefix + "networkReturnCode")
1038                         String networkResponse = execution.getVariable(Prefix + "updateNetworkResponse")
1039                         if (networkResponse==null)      {
1040                                 networkResponse="" // reset
1041                         }
1042
1043                         msoLogger.debug(" Network Adapter update responseCode: " + returnCode)
1044
1045                         String errorMessage = ""
1046                         if (returnCode == "200") {
1047                                 execution.setVariable(Prefix + "isNetworkRollbackNeeded", true)
1048                                 msoLogger.debug(networkResponse)
1049                                 execution.setVariable(Prefix + "updateNetworkResponse", networkResponse)
1050                                 msoLogger.debug(" Network Adapter update Success Response - " + "\n" + networkResponse)
1051
1052                                 // prepare rollback data
1053                                 String rollbackData = utils.getNodeXml(networkResponse, "rollback", false).replace("tag0:","").replace(":tag0","")
1054                                 rollbackData = rollbackData.replace("rollback>", "networkRollback>")
1055                                 String rollbackNetwork =
1056                                         """<rollbackNetworkRequest>
1057                                                         ${rollbackData}
1058                                                 </rollbackNetworkRequest>"""
1059                                 String rollbackNetworkXml = utils.formatXml(rollbackNetwork)
1060                                 execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkXml)
1061                                 msoLogger.debug(" Network Adapter rollback data - " + "\n" + rollbackNetworkXml)
1062
1063                         } else { // network error
1064                            if (returnCode.toInteger() > 399 && returnCode.toInteger() < 600) {   //4xx, 5xx
1065                                    if (networkResponse.contains("updateNetworkError")) {
1066                                            networkResponse = networkResponse.replace('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', '')
1067                                            errorMessage = utils.getNodeText(networkResponse, "message")
1068                                            errorMessage  = "Received error from Network Adapter: " + errorMessage
1069                                            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1070
1071                                    } else { // CatchAll exception
1072                                            if (returnCode == "500") {
1073                                                    errorMessage = "JBWEB000065: HTTP Status 500."
1074                                        } else {
1075                                                errorMessage = "Return code is " + returnCode
1076                                        }
1077                                            errorMessage  = "Received error from Network Adapter: " + errorMessage
1078                                            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1079
1080                                    }
1081
1082                            } else { // CatchAll exception
1083                                    String dataErrorMessage  = "Received error from Network Adapter. Return code is: " + returnCode
1084                                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
1085
1086                            }
1087
1088                         }
1089
1090                 } catch (BpmnError e) {
1091                         throw e;
1092
1093                 } catch (Exception ex) {
1094                         String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. validateUpdateNetworkResponse() - " + ex.getMessage()
1095                         msoLogger.debug(exceptionMessage)
1096                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1097
1098                 }
1099
1100
1101         }
1102
1103         public void validateSDNCResponse (DelegateExecution execution) {
1104
1105                 execution.setVariable("prefix", Prefix)
1106
1107                 msoLogger.trace("Inside validateSDNCResponse of DoUpdateNetworkInstance ")
1108
1109                 String response = execution.getVariable(Prefix + "changeAssignSDNCResponse")
1110                 WorkflowException workflowException = null
1111                 try {
1112                         workflowException = execution.getVariable(Prefix + "WorkflowException")
1113                         //execution.setVariable("WorkflowException", workflowException)
1114                 } catch (Exception ex) {
1115                         msoLogger.debug(" Sdnc 'WorkflowException' object is empty or null. ")
1116                 }
1117
1118                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
1119
1120                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
1121                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
1122                 // reset variable
1123                 String changeAssignSDNCResponseDecodeXml = execution.getVariable(Prefix + "changeAssignSDNCResponse")
1124                 changeAssignSDNCResponseDecodeXml = changeAssignSDNCResponseDecodeXml.replace('<?xml version="1.0" encoding="UTF-8"?>', "")
1125                 execution.setVariable(Prefix + "changeAssignSDNCResponse", changeAssignSDNCResponseDecodeXml)
1126
1127                 if (execution.getVariable(Prefix + "sdncResponseSuccess") == true) {  // from sdnc util, prefix+'sdncResponseSuccess'
1128                         execution.setVariable(Prefix + "isSdncRollbackNeeded", true)
1129                         msoLogger.debug("Successfully Validated SDNC Response")
1130
1131                 } else {
1132                         msoLogger.debug("Did NOT Successfully Validated SDNC Response")
1133                         throw new BpmnError("MSOWorkflowException")
1134                 }
1135
1136         }
1137
1138
1139         public void postProcessResponse (DelegateExecution execution) {
1140
1141                 execution.setVariable("prefix", Prefix)
1142
1143                 msoLogger.trace("Inside postProcessResponse of DoUpdateNetworkInstance ")
1144
1145                 try {
1146                         msoLogger.debug(" ***** Is Exception Encountered (isException)? : " + execution.getVariable(Prefix + "isException"))
1147                         if (execution.getVariable(Prefix + "isException") == false) {
1148                                 // set rollback data
1149                                 execution.setVariable("orchestrationStatus", "")
1150                                 execution.setVariable("networkId", execution.getVariable(Prefix + "networkId"))
1151                                 execution.setVariable("networkName", execution.getVariable(Prefix + "networkName"))
1152                                 prepareSuccessRollbackData(execution) // populate rollbackData
1153                                 execution.setVariable("WorkflowException", null)
1154                                 execution.setVariable(Prefix + "Success", true)
1155                                 msoLogger.debug(" ***** postProcessResponse(), GOOD !!!")
1156                         } else {
1157                                 execution.setVariable(Prefix + "Success", false)
1158                                 execution.setVariable("rollbackData", null)
1159                                 String exceptionMessage = " Exception encountered in MSO Bpmn. "
1160                                 if (execution.getVariable("workflowException") != null) {  // Output of Rollback flow.
1161                                    msoLogger.debug(" ***** workflowException: " + execution.getVariable("workflowException"))
1162                                    WorkflowException wfex = execution.getVariable("workflowException")
1163                                    exceptionMessage = wfex.getErrorMessage()
1164                                 } else {
1165                                if (execution.getVariable(Prefix + "WorkflowException") != null) {
1166                                       WorkflowException pwfex = execution.getVariable(Prefix + "WorkflowException")
1167                                       exceptionMessage = pwfex.getErrorMessage()
1168                                }
1169                                 }
1170                             // going to the Main flow: a-la-carte or macro
1171                             msoLogger.debug(" ***** postProcessResponse(), BAD !!!")
1172                             exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
1173                                 throw new BpmnError("MSOWorkflowException")
1174                         }
1175
1176                 } catch(BpmnError b){
1177                      msoLogger.debug("Rethrowing MSOWorkflowException")
1178                      throw b
1179
1180
1181                 } catch (Exception ex) {
1182                         String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. postProcessResponse() - " + ex.getMessage()
1183                         msoLogger.debug(exceptionMessage)
1184                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1185
1186         }
1187
1188
1189         }
1190
1191         public void prepareSDNCRollbackRequest (DelegateExecution execution) {
1192
1193                 execution.setVariable("prefix", Prefix)
1194
1195                 msoLogger.trace("Inside prepareSDNCRollbackRequest of DoUpdateNetworkInstance ")
1196
1197                 try {
1198                         // for some reason the WorkflowException object is null after the sdnc rollback call task, need to save WorkflowException.
1199                         execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException"))
1200                         // get variables
1201                         String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution)
1202                         String updateNetworkInput = execution.getVariable(Prefix + "networkRequest")
1203                         String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc")
1204                         String changeAssignSDNCResponse = execution.getVariable(Prefix + "changeAssignSDNCResponse")
1205                         String networkId = utils.getNodeText(changeAssignSDNCResponse, "network-id")
1206
1207                         String serviceInstanceId = utils.getNodeText(updateNetworkInput, "service-instance-id")
1208
1209                         // 2. prepare rollback topology via SDNC Adapter SUBFLOW call
1210                         String sndcTopologyRollbackRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, updateNetworkInput, serviceInstanceId, sdncCallback, "rollback", "NetworkActivateRequest", cloudRegionId, networkId, null, null)
1211                         String sndcTopologyRollbackRequestAsString = utils.formatXml(sndcTopologyRollbackRequest)
1212                         execution.setVariable(Prefix + "rollbackSDNCRequest", sndcTopologyRollbackRequestAsString)
1213                         msoLogger.debug(" Preparing request for SDNC Topology assign's rollback/compensation . . . - " + "\n" +  sndcTopologyRollbackRequestAsString)
1214
1215                 } catch (Exception ex) {
1216                         String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareSDNCRollbackRequest() - " + ex.getMessage()
1217                         msoLogger.debug(exceptionMessage)
1218                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
1219
1220                 }
1221
1222         }
1223
1224         public void prepareRollbackData(DelegateExecution execution) {
1225
1226                 execution.setVariable("prefix",Prefix)
1227
1228                 msoLogger.trace("Inside prepareRollbackData() of DoUpdateNetworkInstance ")
1229
1230                 try {
1231
1232                         Map<String, String> rollbackData = new HashMap<String, String>();
1233                         String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest")
1234                         if (rollbackSDNCRequest != null) {
1235                                 if (rollbackSDNCRequest != "") {
1236                                         rollbackData.put("rollbackSDNCRequest", execution.getVariable(Prefix + "rollbackSDNCRequest"))
1237                                 }
1238                         }
1239                         String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest")
1240                         if (rollbackNetworkRequest != null) {
1241                                 if (rollbackNetworkRequest != "") {
1242                                         rollbackData.put("rollbackNetworkRequest", execution.getVariable(Prefix + "rollbackNetworkRequest"))
1243                                 }
1244                         }
1245                         execution.setVariable("rollbackData", rollbackData)
1246                         msoLogger.debug("** rollbackData : " + rollbackData)
1247
1248                         execution.setVariable("WorkflowException", execution.getVariable(Prefix + "WorkflowException"))
1249                         msoLogger.debug("** WorkflowException : " + execution.getVariable("WorkflowException"))
1250
1251                 } catch (Exception ex) {
1252                         String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareRollbackData() - " + ex.getMessage()
1253                         msoLogger.debug(exceptionMessage)
1254                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
1255
1256                 }
1257
1258         }
1259
1260         public void prepareSuccessRollbackData(DelegateExecution execution) {
1261
1262                 execution.setVariable("prefix",Prefix)
1263
1264                 msoLogger.trace("Inside prepareSuccessRollbackData() of DoUpdateNetworkInstance ")
1265
1266                 try {
1267
1268                         if (execution.getVariable("sdncVersion") != '1610') {
1269                                 // skip: 1702 for 'changeassign' or equivalent not yet defined in SNDC, so no rollback.
1270                         } else {
1271                                 prepareSDNCRollbackRequest(execution)
1272                         }
1273
1274                         Map<String, String> rollbackData = new HashMap<String, String>();
1275                         String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest")
1276                         if (rollbackSDNCRequest != null) {
1277                                 if (rollbackSDNCRequest != "") {
1278                                         rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest)
1279                                 }
1280                         }
1281                         String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest")
1282                         if (rollbackNetworkRequest != null) {
1283                                 if (rollbackNetworkRequest != "") {
1284                                         rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest)
1285                                 }
1286                         }
1287                         execution.setVariable("rollbackData", rollbackData)
1288
1289                         msoLogger.debug("** 'rollbackData' for Full Rollback : " + rollbackData)
1290                         execution.setVariable("WorkflowException", null)
1291
1292
1293                 } catch (Exception ex) {
1294                         String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareSuccessRollbackData() - " + ex.getMessage()
1295                         msoLogger.debug(exceptionMessage)
1296                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
1297
1298                 }
1299
1300         }
1301
1302         public void setExceptionFlag(DelegateExecution execution){
1303
1304                 execution.setVariable("prefix",Prefix)
1305
1306                 msoLogger.trace("Inside setExceptionFlag() of DoUpdateNetworkInstance ")
1307
1308                 try {
1309
1310                         execution.setVariable(Prefix + "isException", true)
1311
1312                         if (execution.getVariable("SavedWorkflowException1") != null) {
1313                                 execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1"))
1314                         } else {
1315                                 execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException"))
1316                         }
1317                         msoLogger.debug(Prefix + "WorkflowException - " +execution.getVariable(Prefix + "WorkflowException"))
1318
1319                 } catch(Exception ex){
1320                           String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. setExceptionFlag(): " + ex.getMessage()
1321                         msoLogger.debug(exceptionMessage)
1322                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
1323                 }
1324
1325         }
1326
1327
1328         // *******************************
1329         //     Build Error Section
1330         // *******************************
1331
1332         public void processJavaException(DelegateExecution execution){
1333
1334                 execution.setVariable("prefix",Prefix)
1335                 try{
1336                         msoLogger.debug("Caught a Java Exception")
1337                         msoLogger.debug("Started processJavaException Method")
1338                         msoLogger.debug("Variables List: " + execution.getVariables())
1339                         execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - "  + Prefix)  // Adding this line temporarily until this flows error handling gets updated
1340                         exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception")
1341
1342                 }catch(Exception e){
1343                         msoLogger.debug("Caught Exception during processJavaException Method: " + e)
1344                         execution.setVariable("UnexpectedError", "Exception in processJavaException method")  // Adding this line temporarily until this flows error handling gets updated
1345                         exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method")
1346                 }
1347                 msoLogger.debug("Completed processJavaException Method")
1348         }
1349
1350 }