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