Merge "sonar try-with-resources"
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / AaiUtil.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.common.scripts
22 import org.camunda.bpm.engine.delegate.BpmnError
23 import org.camunda.bpm.engine.delegate.DelegateExecution
24 import org.onap.so.bpmn.core.UrnPropertiesReader;
25 import org.onap.so.rest.APIResponse;
26 import org.onap.so.rest.RESTClient
27 import org.onap.so.rest.RESTConfig
28 import org.onap.so.logger.MessageEnum
29 import org.onap.so.logger.MsoLogger
30
31 class AaiUtil {
32         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, AaiUtil.class);
33
34
35         public MsoUtils utils = new MsoUtils()
36         public static final String AAI_NAMESPACE_STRING_KEY = 'mso.workflow.global.default.aai.namespace'
37         public static final String DEFAULT_VERSION_KEY = 'mso.workflow.global.default.aai.version'
38
39         private String aaiNamespace = null;
40
41         private AbstractServiceTaskProcessor taskProcessor
42
43         public AaiUtil(AbstractServiceTaskProcessor taskProcessor) {
44                 this.taskProcessor = taskProcessor
45         }
46
47         public String getNetworkGenericVnfEndpoint(DelegateExecution execution) {
48                 String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
49                 def uri = getNetworkGenericVnfUri(execution)
50                 msoLogger.debug('AaiUtil.getNetworkGenericVnfEndpoint() - AAI endpoint: ' + endpoint + uri)
51                 return endpoint + uri
52         }
53
54         public String getNetworkGenericVnfUri(DelegateExecution execution) {
55                 def uri = getUri(execution, 'generic-vnf')
56                 msoLogger.debug('AaiUtil.getNetworkGenericVnfUri() - AAI URI: ' + uri)
57                 return uri
58         }
59
60         public String getNetworkVpnBindingUri(DelegateExecution execution) {
61                 def uri = getUri(execution, 'vpn-binding')
62                 msoLogger.debug('AaiUtil.getNetworkVpnBindingUri() - AAI URI: ' + uri)
63                 return uri
64         }
65
66         public String getNetworkPolicyUri(DelegateExecution execution) {
67                 def uri = getUri(execution, 'network-policy')
68                 msoLogger.debug('AaiUtil.getNetworkPolicyUri() - AAI URI: ' + uri)
69                 return uri
70         }
71
72         public String getNetworkTableReferencesUri(DelegateExecution execution) {
73                 def uri = getUri(execution, 'route-table-reference')
74                 msoLogger.debug('AaiUtil.getNetworkTableReferencesUri() - AAI URI: ' + uri)
75                 return uri
76         }
77
78         public String getNetworkVceUri(DelegateExecution execution) {
79                 def uri = getUri(execution, 'vce')
80                 msoLogger.debug('AaiUtil.getNetworkVceUri() - AAI URI: ' + uri)
81                 return uri
82         }
83
84         public String getNetworkL3NetworkUri(DelegateExecution execution) {
85                 def uri = getUri(execution, 'l3-network')
86                 msoLogger.debug('AaiUtil.getNetworkL3NetworkUri() - AAI URI: ' + uri)
87                 return uri
88         }
89
90         public String getBusinessCustomerUri(DelegateExecution execution) {
91                 def uri = getUri(execution, 'customer')
92                 msoLogger.debug('AaiUtil.getBusinessCustomerUri() - AAI URI: ' + uri)
93                 return uri
94         }
95         
96         public String getBusinessSPPartnerUri(DelegateExecution execution) {
97                 def uri = getUri(execution, 'sp-partner')
98                 msoLogger.debug('AaiUtil.getBusinessSPPartnerUri() - AAI URI: ' + uri)
99                 return uri
100         }
101
102         public String getAAIServiceInstanceUri(DelegateExecution execution) {
103                 String uri = getBusinessCustomerUri(execution)
104
105                 uri = uri +"/" + execution.getVariable("globalSubscriberId") + "/service-subscriptions/service-subscription/" + UriUtils.encode(execution.getVariable("serviceType"),"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(execution.getVariable("serviceInstanceId"),"UTF-8")
106
107                 msoLogger.debug('AaiUtil.getAAIRequestInputUri() - AAI URI: ' + uri)
108                 return uri
109         }
110
111         //public String getBusinessCustomerUriv7(DelegateExecution execution) {
112         //      //      //def uri = getUri(execution, BUSINESS_CUSTOMERV7)
113         //      def uri = getUri(execution, 'Customer')
114         //      msoLogger.debug('AaiUtil.getBusinessCustomerUriv7() - AAI URI: ' + uri)
115         //      return uri
116         //}
117
118         public String getCloudInfrastructureCloudRegionEndpoint(DelegateExecution execution) {
119                 String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
120                 def uri = getCloudInfrastructureCloudRegionUri(execution)
121                 msoLogger.debug('AaiUtil.getCloudInfrastructureCloudRegionEndpoint() - AAI endpoint: ' + endpoint + uri)
122                 return endpoint + uri
123         }
124
125         public String getCloudInfrastructureCloudRegionUri(DelegateExecution execution) {
126                 def uri = getUri(execution, 'cloud-region')
127                 msoLogger.debug('AaiUtil.getCloudInfrastructureCloudRegionUri() - AAI URI: ' + uri)
128                 return uri
129         }
130
131         public String getCloudInfrastructureTenantUri(DelegateExecution execution) {
132                 def uri = getUri(execution, 'tenant')
133                 msoLogger.debug('AaiUtil.getCloudInfrastructureTenantUri() - AAI URI: ' + uri)
134                 return uri
135         }
136
137         public String getSearchNodesQueryUri(DelegateExecution execution) {
138                 def uri = getUri(execution, 'nodes-query')
139                 msoLogger.debug('AaiUtil.getSearchNodesQueryUri() - AAI URI: ' + uri)
140                 return uri
141         }
142
143         public String getSearchNodesQueryEndpoint(DelegateExecution execution) {
144                 String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
145                 def uri = getSearchNodesQueryUri(execution)
146                 msoLogger.debug('AaiUtil.getSearchNodesQueryEndpoint() - AAI endpoint: ' + endpoint + uri)
147                 return endpoint + uri
148         }
149
150         public String getSearchGenericQueryUri(DelegateExecution execution) {
151                 def uri = getUri(execution, 'generic-query')
152                 msoLogger.debug('AaiUtil.getSearchGenericQueryUri() - AAI URI: ' + uri)
153                 return uri
154         }
155
156         public String getVersion(DelegateExecution execution, resourceName, processKey) {
157                 def versionWithResourceKey = "mso.workflow.default.aai.${resourceName}.version"
158                 def versionWithProcessKey = "mso.workflow.custom.${processKey}.aai.version"
159
160                 def version = UrnPropertiesReader.getVariable(versionWithProcessKey, execution)
161                 if (version) {
162                         msoLogger.debug("AaiUtil.getVersion() - using flow specific ${versionWithProcessKey}=${version}")
163                         return version
164                 }
165
166                 version = UrnPropertiesReader.getVariable(versionWithResourceKey, execution)
167                 if (version) {
168                         msoLogger.debug("AaiUtil.getVersion() - using resource specific ${versionWithResourceKey}=${version}")
169                         return version
170                 }
171
172                 version = UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY, execution)
173                 if (version) {
174                         msoLogger.debug("AaiUtil.getVersion() - using default version ${DEFAULT_VERSION_KEY}=${version}")
175                         return version
176                 }
177
178                 (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, "Internal Error: One of the following should be defined in MSO URN properties file: ${versionWithResourceKey}, ${versionWithProcessKey}, ${DEFAULT_VERSION_KEY}")
179         }
180
181         public String getUri(DelegateExecution execution, resourceName) {
182
183                 def processKey = taskProcessor.getMainProcessKey(execution)
184
185                 //set namespace
186                 setNamespace(execution)
187
188                 // Check for flow+resource specific first
189                 def key = "mso.workflow.${processKey}.aai.${resourceName}.uri"
190                 def uri = UrnPropertiesReader.getVariable(key, execution)
191                 if(uri) {
192                         msoLogger.debug("AaiUtil.getUri() - using flow+resource specific key: ${key}=${uri}")
193                         return uri
194                 }
195
196                 // Check for versioned key
197                 def version = getVersion(execution, resourceName, processKey)
198                 key = "mso.workflow.default.aai.v${version}.${resourceName}.uri"
199                 uri = UrnPropertiesReader.getVariable(key, execution)
200
201                 if(uri) {
202                         msoLogger.debug("AaiUtil.getUri() - using versioned URI key: ${key}=${uri}")
203                         return uri
204                 }
205
206                 (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file')
207         }
208
209         public String setNamespace(DelegateExecution execution) {
210                 def key = AAI_NAMESPACE_STRING_KEY
211                 aaiNamespace = UrnPropertiesReader.getVariable(key, execution)
212                 if (aaiNamespace == null ) {
213                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file')
214                 }
215         }
216
217         /**
218          * This method can be used for getting the building namespace out of uri.
219          *  NOTE: A getUri() method needs to be invoked first.
220          *        Alternative method is the getNamespaceFromUri(DelegateExecution execution, String uri)
221          * return namespace (plus version from uri)
222          *
223          * @param url
224          *
225          * @return namespace
226          */
227
228         public String getNamespaceFromUri(String uri) {
229                  if (aaiNamespace == null) {
230                         throw new Exception('Internal Error: AAI Namespace has not been set yet. A getUri() method needs to be invoked first.')
231                 }
232                 String namespace = aaiNamespace
233                 if(uri!=null){
234                         String version = getVersionFromUri(uri)
235                         return namespace + "v"+version
236                 }else{
237                         return namespace
238                 }
239         }
240
241         /**
242          * This method can be used for building namespace with aai version out of uri.
243          *   NOTE: 2 arguments: DelegateExecution execution & String uri
244          * @param execution
245          * @param url
246          *
247          * @return namespace
248          */
249         public String getNamespaceFromUri(DelegateExecution execution, String uri) {
250            String namespace = UrnPropertiesReader.getVariable(AAI_NAMESPACE_STRING_KEY, execution)
251            if (namespace == null ) {
252                    (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + AAI_NAMESPACE_STRING_KEY + ' not defined in the MSO URN properties file')
253            }
254            if(uri!=null){
255                    String version = getVersionFromUri(uri)
256                    return namespace + "v"+version
257            }else{
258                    return namespace
259            }
260    }
261
262         /**
263          * This is used to extract the version from uri.
264          *
265          * @param uri
266          *
267          * @return version
268          */
269         private String getVersionFromUri(String uri) {
270                 def version = ""
271                 def savedVersion = ""
272                 for (int x=2; x<6; x++) {
273                         version = uri.substring(uri.indexOf("v")+1,  uri.indexOf("v")+x)
274                         if (!Character.isDigit(version.charAt(version.size()-1))) {
275                                 break
276                         }
277                         savedVersion = version
278                 }
279                 return savedVersion
280         }
281
282
283         /**
284          * This reusable method can be used for making AAI Get Calls. The url should
285          * be passed as a parameter along with the execution.  The method will
286          * return an APIResponse.
287          *
288          * @param execution
289          * @param url
290          *
291          * @return APIResponse
292          *
293          */
294         public APIResponse executeAAIGetCall(DelegateExecution execution, String url){
295                 msoLogger.trace("STARTED Execute AAI Get Process ")
296                 APIResponse apiResponse = null
297                 try{
298                         String uuid = utils.getRequestID()
299                         msoLogger.debug("Generated uuid is: " + uuid)
300                         msoLogger.debug("URL to be used is: " + url)
301
302                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
303
304                         RESTConfig config = new RESTConfig(url);
305                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");
306
307                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
308                                 client.addAuthorizationHeader(basicAuthCred)
309                         }
310                         apiResponse = client.get()
311
312                         msoLogger.trace("COMPLETED Execute AAI Get Process ")
313                 }catch(Exception e){
314                         msoLogger.debug("Exception occured while executing AAI Get Call. Exception is: \n" + e)
315                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
316                 }
317                 return apiResponse
318         }
319
320
321         /**
322          * This reusable method can be used for making AAI httpPut Calls. The url should
323          * be passed as a parameter along with the execution and payload.  The method will
324          * return an APIResponse.
325          *
326          * @param execution
327          * @param url
328          * @param payload
329          *
330          * @return APIResponse
331          *
332          */
333         public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){
334                 msoLogger.trace("Started Execute AAI Put Process ")
335                 APIResponse apiResponse = null
336                 try{
337                         String uuid = utils.getRequestID()
338                         msoLogger.debug("Generated uuid is: " + uuid)
339                         msoLogger.debug("URL to be used is: " + url)
340
341                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
342
343                         RESTConfig config = new RESTConfig(url);
344                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");
345                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
346                                 client.addAuthorizationHeader(basicAuthCred)
347                         }
348                         apiResponse = client.httpPut(payload)
349
350                         msoLogger.trace("Completed Execute AAI Put Process ")
351                 }catch(Exception e){
352                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
353                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
354                 }
355                 return apiResponse
356         }
357
358         /**
359          * This reusable method can be used for making AAI httpPatch Calls. The url should
360          * be passed as a parameter along with the execution and payload.  The method will
361          * return an APIResponse.
362          *
363          * @param execution
364          * @param url
365          * @param payload
366          *
367          * @return APIResponse
368          *
369          */
370         public APIResponse executeAAIPatchCall(DelegateExecution execution, String url, String payload){
371                 msoLogger.trace("Started Execute AAI Patch Process ")
372                 APIResponse apiResponse = null
373                 try{
374                         String uuid = utils.getRequestID()
375                         msoLogger.debug("Generated uuid is: " + uuid)
376
377                         msoLogger.debug("URL to be used is: " + url)
378
379                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
380
381                         RESTConfig config = new RESTConfig(url);
382                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/merge-patch+json").addHeader("Accept","application/json");
383                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
384                                 client.addAuthorizationHeader(basicAuthCred)
385                         }
386                         apiResponse = client.httpPatch(payload)
387
388                         msoLogger.trace("Completed Execute AAI Patch Process ")
389                 }catch(Exception e){
390                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Patch Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
391                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
392                 }
393                 return apiResponse
394         }
395
396
397         /**
398          * This reusable method can be used for making AAI Delete Calls. The url should
399          * be passed as a parameter along with the execution.  The method will
400          * return an APIResponse.
401          *
402          * @param execution
403          * @param url
404          *
405          * @return APIResponse
406          *
407          */
408         public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url){
409                 msoLogger.trace("Started Execute AAI Delete Process ")
410                 APIResponse apiResponse = null
411                 try{
412                         String uuid = utils.getRequestID()
413                         msoLogger.debug("Generated uuid is: " + uuid)
414                         msoLogger.debug("URL to be used is: " + url)
415
416                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
417
418                         RESTConfig config = new RESTConfig(url);
419                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");
420                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
421                                 client.addAuthorizationHeader(basicAuthCred)
422                         }
423                         apiResponse = client.delete()
424
425                         msoLogger.trace("Completed Execute AAI Delete Process ")
426                 }catch(Exception e){
427                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
428                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
429                 }
430                 return apiResponse
431         }
432
433         /**
434          * This reusable method can be used for making AAI Delete Calls. The url should
435          * be passed as a parameter along with the execution.  The method will
436          * return an APIResponse.
437          *
438          * @param execution
439          * @param url
440          * @param payload
441          *
442          * @return APIResponse
443          *
444          */
445         public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url, String payload, String authHeader){
446                 msoLogger.trace("Started Execute AAI Delete Process ")
447                 APIResponse apiResponse = null
448                 try{
449                         String uuid = utils.getRequestID()
450                         msoLogger.debug("Generated uuid is: " + uuid)
451
452                         msoLogger.debug("URL to be used is: " + url)
453
454                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
455                         RESTConfig config = new RESTConfig(url);
456                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml").addAuthorizationHeader(authHeader);
457                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
458                                 client.addAuthorizationHeader(basicAuthCred)
459                         }
460                         apiResponse = client.httpDelete(payload)
461
462                         msoLogger.trace("Completed Execute AAI Delete Process ")
463                 }catch(Exception e){
464                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
465                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
466                 }
467                 return apiResponse
468         }
469
470         /**
471          * This reusable method can be used for making AAI Post Calls. The url
472          * and payload should be passed as a parameters along with the execution.
473          * The method will return an APIResponse.
474          *
475          * @param execution
476          * @param url
477          * @param payload
478          *
479          * @return APIResponse
480          *
481          */
482         public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload){
483                 msoLogger.trace("Started Execute AAI Post Process ")
484                 APIResponse apiResponse = null
485                 try{
486                         String uuid = utils.getRequestID()
487                         msoLogger.debug("Generated uuid is: " + uuid)
488                         msoLogger.debug("URL to be used is: " + url)
489
490                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
491                         RESTConfig config = new RESTConfig(url);
492                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");
493
494                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
495                                 client.addAuthorizationHeader(basicAuthCred)
496                         }
497                         apiResponse = client.httpPost(payload)
498
499                         msoLogger.trace("Completed Execute AAI Post Process ")
500                 }catch(Exception e){
501                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
502                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
503                 }
504                 return apiResponse
505         }
506
507         /**
508          * This reusable method can be used for making AAI Post Calls. The url
509          * and payload should be passed as a parameters along with the execution.
510          * The method will return an APIResponse.
511          *
512          * @param execution
513          * @param url
514          * @param payload
515          * @param authenticationHeader - addAuthenticationHeader value
516          * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue)
517          * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue)
518          *
519          * @return APIResponse
520          *
521          */
522         public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){
523                 msoLogger.trace("Started Execute AAI Post Process ")
524                 APIResponse apiResponse = null
525                 try{
526                         msoLogger.debug("URL to be used is: " + url)
527
528                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
529
530                         RESTConfig config = new RESTConfig(url);
531                         RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue)
532                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
533                                 client.addAuthorizationHeader(basicAuthCred)
534                         }
535                         apiResponse = client.httpPost(payload)
536
537                         msoLogger.trace("Completed Execute AAI Post Process ")
538                 }catch(Exception e){
539                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
540                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
541                 }
542                 return apiResponse
543         }
544
545
546         /* Utility to get the Cloud Region from AAI
547          * Returns String cloud region id, (ie, cloud-region-id)
548          * @param execution
549          * @param url  - url for AAI get cloud region
550          * @param backend - "PO" - real region, or "SDNC" - v2.5 (fake region).
551          */
552
553         public String getAAICloudReqion(DelegateExecution execution, String url, String backend, inputCloudRegion){
554                 String regionId = ""
555                 try{
556                         APIResponse apiResponse = executeAAIGetCall(execution, url)
557                         String returnCode = apiResponse.getStatusCode()
558                         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
559                         msoLogger.debug("Call AAI Cloud Region Return code: " + returnCode)
560                         execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode)
561
562                         if(returnCode == "200"){
563                                 msoLogger.debug("Call AAI Cloud Region is Successful.")
564
565                                 String regionVersion = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-version")
566                                 msoLogger.debug("Cloud Region Version from AAI for " + backend + " is: " + regionVersion)
567                                 if (backend == "PO") {
568                                         regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
569                                 } else { // backend not "PO"
570                                         if (regionVersion == "2.5" ) {
571                                                 regionId = "AAIAIC25"
572                                         } else {
573                                                 regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
574                                         }
575                                 }
576                                 if(regionId == null){
577                                         throw new BpmnError("MSOWorkflowException")
578                                 }
579                                 msoLogger.debug("Cloud Region Id from AAI " + backend + " is: " + regionId)
580                         }else if (returnCode == "404"){ // not 200
581                                 if (backend == "PO") {
582                                         regionId = inputCloudRegion
583                                 }else{  // backend not "PO"
584                                         regionId = "AAIAIC25"
585                                 }
586                                 msoLogger.debug("Cloud Region value for code='404' of " + backend + " is: " + regionId)
587                         }else{
588                                 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Call AAI Cloud Region is NOT Successful.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
589                                 throw new BpmnError("MSOWorkflowException")
590                         }
591                 }catch(Exception e) {
592                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while getting the Cloud Reqion.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage());
593                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
594                 }
595                 return regionId
596         }
597
598         /* returns xml Node with service-type of searchValue */
599         def searchServiceType(xmlInput, searchValue){
600                 def fxml= new XmlSlurper().parseText(xmlInput)
601                 def ret = fxml.'**'.find {it.'service-type' == searchValue}
602                 return ret
603         }
604
605         /* returns xml Node with service-instance-id of searchValue */
606         def searchServiceInstanceId(xmlInput, searchValue){
607                 def ret = xmlInput.'**'.find {it.'service-instance-id' == searchValue}
608                 return ret
609         }
610
611         /**
612          * Get the lowest unused VF Module index from AAI response for a given module type. The criteria for
613          * determining module type is specified by "key" parameter (for example, "persona-model-id"),
614          * the value for filtering is specified in "value" parameter
615          *
616          * @param execution
617          * @param aaiVnfResponse
618          * @param key
619          * @param value
620          *
621          * @return moduleIndex
622          *
623          */
624         public int getLowestUnusedVfModuleIndexFromAAIVnfResponse(DelegateExecution execution, String aaiVnfResponse, String key, String value) {
625                 if (aaiVnfResponse != null) {
626                         String vfModulesText = taskProcessor.utils.getNodeXml(aaiVnfResponse, "vf-modules")
627                         if (vfModulesText == null || vfModulesText.isEmpty()) {
628                                 msoLogger.debug("There are no VF modules in this VNF yet")
629                                 return 0
630                         }
631                         else {
632                                 def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
633                                 def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
634                                 int vfModulesSize = 0
635                                 if (vfModules != null) {
636                                         vfModulesSize = vfModules.size()
637                                 }
638                                 String matchingVfModules = "<vfModules>"
639                                 for (i in 0..vfModulesSize-1) {
640                                         def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
641                                         def keyFromAAI = taskProcessor.utils.getNodeText(vfModuleXml, key)
642                                         if (keyFromAAI != null && keyFromAAI.equals(value)) {
643                                                 matchingVfModules = matchingVfModules + taskProcessor.utils.removeXmlPreamble(vfModuleXml)
644                                         }
645                                 }
646                                 matchingVfModules = matchingVfModules + "</vfModules>"
647                                 msoLogger.debug("Matching VF Modules: " + matchingVfModules)
648                                 String lowestUnusedIndex = taskProcessor.utils.getLowestUnusedIndex(matchingVfModules)
649                                 return Integer.parseInt(lowestUnusedIndex)
650                         }
651                 }
652                 else {
653                         return 0
654                 }
655         }
656
657         private def getPInterface(DelegateExecution execution, String aai_uri) {
658
659                 String namespace = getNamespaceFromUri(aai_uri)
660                 String aai_endpoint = execution.getVariable("URN_aai_endpoint")
661                 String serviceAaiPath = ${aai_endpoint}${aai_uri}
662
663                 APIResponse response = executeAAIGetCall(execution, serviceAaiPath)
664                 return new XmlParser().parseText(response.getResponseBodyAsString())
665         }
666
667         // This method checks if interface is remote
668         private def isPInterfaceRemote(DelegateExecution execution, String uri) {
669                 if(uri.contains("ext-aai-network")) {
670                         return true
671                 } else {
672                         return false
673                 }
674         }
675
676         // This method returns Local and remote TPs information from AAI        
677         public Map getTPsfromAAI(DelegateExecution execution) {
678                 Map tpInfo = [:]
679
680                 String aai_uri = '/aai/v14/network/logical-links'
681
682                 String aai_endpoint = execution.getVariable("URN_aai_endpoint")
683                 String serviceAaiPath = ${aai_endpoint}${aai_uri}
684
685                 APIResponse response = executeAAIGetCall(execution, serviceAaiPath)
686
687                 def logicalLinks = new XmlParser().parseText(response.getResponseBodyAsString())
688
689                 logicalLinks."logical-links".find { link ->
690                         def pInterface = []
691                         def relationship = link."relationship-list"."relationship"
692                         relationship.each {
693                                 if ("p-interface".compareToIgnoreCase(it."related-to")) {
694                                         pInterface.add(it)
695                                 }
696                         }
697                         if (pInterface.size() == 2) {
698                                 def localTP = null
699                                 def remoteTP = null
700
701                                 if (pInterface[0]."related-link".contains("ext-aai-networks")) {
702                                         remoteTP = pInterface[0]
703                                         localTP = pInterface[1]
704                                 }
705
706                                 if (pInterface[1]."related-link".contains("ext-aai-networks")) {
707                                         localTP = pInterface[0]
708                                         remoteTP = pInterface[1]
709                                 }
710
711                                 if (localTP != null && remoteTP != null) {
712                                 
713                                         // give local tp
714                                         var intfLocal = getPInterface(execution, localTP."related-link")
715                                         tpInfotpInfo.put("local-access-node-id", localTP."related-link".split("/")[6])
716                                 
717                                         def networkRef = intfLocal."network-ref".split("/")
718                                         tpInfo.put("local-access-provider-id", networkRef[1])
719                                         tpInfo.put("local-access-client-id", networkRef[3])
720                                         tpInfo.put("local-access-topology-id", networkRef[5])
721                                         tpInfo.put("local-access-ltp-id", localTP."interface-name")
722                                         
723                                         // give local tp
724                                         var intfRemote = getPInterface(execution, remoteTP."related-link")
725                                         tpInfo.put("remote-access-node-id", remoteTP."related-link".split("/")[6])                                      
726                                         def networkRefRemote = intfRemote."network-ref".split("/")
727                                         tpInfo.put("remote-access-provider-id", networkRefRemote[1])
728                                         tpInfo.put("remote-access-client-id", networkRefRemote[3])
729                                         tpInfo.put("remote-access-topology-id", networkRefRemote[5])
730                                         tpInfo.put("remote-access-ltp-id", remoteTP."interface-name")
731                                 }
732                         }
733
734                 }
735                 return tpInfo
736         }
737 }