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