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