summaryrefslogtreecommitdiffstats
path: root/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy
blob: cae80e913753209454ae974e1d4852a1b554e51f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.so.bpmn.common.scripts
import org.camunda.bpm.engine.delegate.BpmnError
import org.camunda.bpm.engine.delegate.DelegateExecution
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.onap.so.rest.APIResponse;
import org.onap.so.rest.RESTClient
import org.onap.so.rest.RESTConfig
import org.onap.so.logger.MessageEnum
import org.onap.so.logger.MsoLogger

class AaiUtil {
	private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, AaiUtil.class);


	public MsoUtils utils = new MsoUtils()
	public static final String AAI_NAMESPACE_STRING_KEY = 'mso.workflow.global.default.aai.namespace'
	public static final String DEFAULT_VERSION_KEY = 'mso.workflow.global.default.aai.version'

	private String aaiNamespace = null;

	private AbstractServiceTaskProcessor taskProcessor

	public AaiUtil(AbstractServiceTaskProcessor taskProcessor) {
		this.taskProcessor = taskProcessor
	}

	public String getNetworkGenericVnfEndpoint(DelegateExecution execution) {
		String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
		def uri = getNetworkGenericVnfUri(execution)
		msoLogger.debug('AaiUtil.getNetworkGenericVnfEndpoint() - AAI endpoint: ' + endpoint + uri)
		return endpoint + uri
	}

	public String getNetworkGenericVnfUri(DelegateExecution execution) {
		def uri = getUri(execution, 'generic-vnf')
		msoLogger.debug('AaiUtil.getNetworkGenericVnfUri() - AAI URI: ' + uri)
		return uri
	}

	public String getNetworkVpnBindingUri(DelegateExecution execution) {
		def uri = getUri(execution, 'vpn-binding')
		msoLogger.debug('AaiUtil.getNetworkVpnBindingUri() - AAI URI: ' + uri)
		return uri
	}

	public String getNetworkPolicyUri(DelegateExecution execution) {
		def uri = getUri(execution, 'network-policy')
		msoLogger.debug('AaiUtil.getNetworkPolicyUri() - AAI URI: ' + uri)
		return uri
	}

	public String getNetworkTableReferencesUri(DelegateExecution execution) {
		def uri = getUri(execution, 'route-table-reference')
		msoLogger.debug('AaiUtil.getNetworkTableReferencesUri() - AAI URI: ' + uri)
		return uri
	}

	public String getNetworkVceUri(DelegateExecution execution) {
		def uri = getUri(execution, 'vce')
		msoLogger.debug('AaiUtil.getNetworkVceUri() - AAI URI: ' + uri)
		return uri
	}

	public String getNetworkL3NetworkUri(DelegateExecution execution) {
		def uri = getUri(execution, 'l3-network')
		msoLogger.debug('AaiUtil.getNetworkL3NetworkUri() - AAI URI: ' + uri)
		return uri
	}

	public String getBusinessCustomerUri(DelegateExecution execution) {
		def uri = getUri(execution, 'customer')
		msoLogger.debug('AaiUtil.getBusinessCustomerUri() - AAI URI: ' + uri)
		return uri
	}
	
	public String getBusinessSPPartnerUri(DelegateExecution execution) {
		def uri = getUri(execution, 'sp-partner')
		msoLogger.debug('AaiUtil.getBusinessSPPartnerUri() - AAI URI: ' + uri)
		return uri
	}

	public String getAAIServiceInstanceUri(DelegateExecution execution) {
		String uri = getBusinessCustomerUri(execution)

		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")

		msoLogger.debug('AaiUtil.getAAIRequestInputUri() - AAI URI: ' + uri)
		return uri
	}

	//public String getBusinessCustomerUriv7(DelegateExecution execution) {
	//	//	//def uri = getUri(execution, BUSINESS_CUSTOMERV7)
	//	def uri = getUri(execution, 'Customer')
	//	msoLogger.debug('AaiUtil.getBusinessCustomerUriv7() - AAI URI: ' + uri)
	//	return uri
	//}

	public String getCloudInfrastructureCloudRegionEndpoint(DelegateExecution execution) {
		String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
		def uri = getCloudInfrastructureCloudRegionUri(execution)
		msoLogger.debug('AaiUtil.getCloudInfrastructureCloudRegionEndpoint() - AAI endpoint: ' + endpoint + uri)
		return endpoint + uri
	}

	public String getCloudInfrastructureCloudRegionUri(DelegateExecution execution) {
		def uri = getUri(execution, 'cloud-region')
		msoLogger.debug('AaiUtil.getCloudInfrastructureCloudRegionUri() - AAI URI: ' + uri)
		return uri
	}

	public String getCloudInfrastructureTenantUri(DelegateExecution execution) {
		def uri = getUri(execution, 'tenant')
		msoLogger.debug('AaiUtil.getCloudInfrastructureTenantUri() - AAI URI: ' + uri)
		return uri
	}

	public String getSearchNodesQueryUri(DelegateExecution execution) {
		def uri = getUri(execution, 'nodes-query')
		msoLogger.debug('AaiUtil.getSearchNodesQueryUri() - AAI URI: ' + uri)
		return uri
	}

	public String getSearchNodesQueryEndpoint(DelegateExecution execution) {
		String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
		def uri = getSearchNodesQueryUri(execution)
		msoLogger.debug('AaiUtil.getSearchNodesQueryEndpoint() - AAI endpoint: ' + endpoint + uri)
		return endpoint + uri
	}

	public String getSearchGenericQueryUri(DelegateExecution execution) {
		def uri = getUri(execution, 'generic-query')
		msoLogger.debug('AaiUtil.getSearchGenericQueryUri() - AAI URI: ' + uri)
		return uri
	}

	public String getVersion(DelegateExecution execution, resourceName, processKey) {
		def versionWithResourceKey = "mso.workflow.default.aai.${resourceName}.version"
		def versionWithProcessKey = "mso.workflow.custom.${processKey}.aai.version"

		def version = UrnPropertiesReader.getVariable(versionWithProcessKey, execution)
		if (version) {
			msoLogger.debug("AaiUtil.getVersion() - using flow specific ${versionWithProcessKey}=${version}")
			return version
		}

		version = UrnPropertiesReader.getVariable(versionWithResourceKey, execution)
		if (version) {
			msoLogger.debug("AaiUtil.getVersion() - using resource specific ${versionWithResourceKey}=${version}")
			return version
		}

		version = UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY, execution)
		if (version) {
			msoLogger.debug("AaiUtil.getVersion() - using default version ${DEFAULT_VERSION_KEY}=${version}")
			return version
		}

		(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, "Internal Error: One of the following should be defined in MSO URN properties file: ${versionWithResourceKey}, ${versionWithProcessKey}, ${DEFAULT_VERSION_KEY}")
	}

	public String getUri(DelegateExecution execution, resourceName) {

		def processKey = taskProcessor.getMainProcessKey(execution)

		//set namespace
		setNamespace(execution)

		// Check for flow+resource specific first
		def key = "mso.workflow.${processKey}.aai.${resourceName}.uri"
		def uri = UrnPropertiesReader.getVariable(key, execution)
		if(uri) {
			msoLogger.debug("AaiUtil.getUri() - using flow+resource specific key: ${key}=${uri}")
			return uri
		}

		// Check for versioned key
		def version = getVersion(execution, resourceName, processKey)
		key = "mso.workflow.default.aai.v${version}.${resourceName}.uri"
		uri = UrnPropertiesReader.getVariable(key, execution)

		if(uri) {
			msoLogger.debug("AaiUtil.getUri() - using versioned URI key: ${key}=${uri}")
			return uri
		}

		(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file')
	}

	public String setNamespace(DelegateExecution execution) {
		def key = AAI_NAMESPACE_STRING_KEY
		aaiNamespace = UrnPropertiesReader.getVariable(key, execution)
		if (aaiNamespace == null ) {
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file')
		}
	}

	/**
	 * This method can be used for getting the building namespace out of uri.
	 *  NOTE: A getUri() method needs to be invoked first.
	 *        Alternative method is the getNamespaceFromUri(DelegateExecution execution, String uri)
	 * return namespace (plus version from uri)
	 *
	 * @param url
	 *
	 * @return namespace
	 */

	public String getNamespaceFromUri(String uri) {
		 if (aaiNamespace == null) {
			throw new Exception('Internal Error: AAI Namespace has not been set yet. A getUri() method needs to be invoked first.')
		}
		String namespace = aaiNamespace
		if(uri!=null){
			String version = getVersionFromUri(uri)
			return namespace + "v"+version
		}else{
			return namespace
		}
	}

	/**
	 * This method can be used for building namespace with aai version out of uri.
	 *   NOTE: 2 arguments: DelegateExecution execution & String uri
	 * @param execution
	 * @param url
	 *
	 * @return namespace
	 */
	public String getNamespaceFromUri(DelegateExecution execution, String uri) {
	   String namespace = UrnPropertiesReader.getVariable(AAI_NAMESPACE_STRING_KEY, execution)
	   if (namespace == null ) {
		   (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + AAI_NAMESPACE_STRING_KEY + ' not defined in the MSO URN properties file')
	   }
	   if(uri!=null){
		   String version = getVersionFromUri(uri)
		   return namespace + "v"+version
	   }else{
		   return namespace
	   }
   }

	/**
	 * This is used to extract the version from uri.
	 *
	 * @param uri
	 *
	 * @return version
	 */
	private String getVersionFromUri(String uri) {
		def version = ""
		def savedVersion = ""
		for (int x=2; x<6; x++) {
			version = uri.substring(uri.indexOf("v")+1,  uri.indexOf("v")+x)
			if (!Character.isDigit(version.charAt(version.size()-1))) {
				break
			}
			savedVersion = version
		}
		return savedVersion
	}


	/**
	 * This reusable method can be used for making AAI Get Calls. The url should
	 * be passed as a parameter along with the execution.  The method will
	 * return an APIResponse.
	 *
	 * @param execution
	 * @param url
	 *
	 * @return APIResponse
	 *
	 */
	public APIResponse executeAAIGetCall(DelegateExecution execution, String url){
		msoLogger.trace("STARTED Execute AAI Get Process ")
		APIResponse apiResponse = null
		try{
			String uuid = utils.getRequestID()
			msoLogger.debug("Generated uuid is: " + uuid)
			msoLogger.debug("URL to be used is: " + url)

			String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))

			RESTConfig config = new RESTConfig(url);
			RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");

			if (basicAuthCred != null && !"".equals(basicAuthCred)) {
				client.addAuthorizationHeader(basicAuthCred)
			}
			apiResponse = client.get()

			msoLogger.trace("COMPLETED Execute AAI Get Process ")
		}catch(Exception e){
			msoLogger.debug("Exception occured while executing AAI Get Call. Exception is: \n" + e)
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
		}
		return apiResponse
	}


	/**
	 * This reusable method can be used for making AAI httpPut Calls. The url should
	 * be passed as a parameter along with the execution and payload.  The method will
	 * return an APIResponse.
	 *
	 * @param execution
	 * @param url
	 * @param payload
	 *
	 * @return APIResponse
	 *
	 */
	public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){
		msoLogger.trace("Started Execute AAI Put Process ")
		APIResponse apiResponse = null
		try{
			String uuid = utils.getRequestID()
			msoLogger.debug("Generated uuid is: " + uuid)
			msoLogger.debug("URL to be used is: " + url)

			String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))

			RESTConfig config = new RESTConfig(url);
			RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");
			if (basicAuthCred != null && !"".equals(basicAuthCred)) {
				client.addAuthorizationHeader(basicAuthCred)
			}
			apiResponse = client.httpPut(payload)

			msoLogger.trace("Completed Execute AAI Put Process ")
		}catch(Exception e){
			msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
		}
		return apiResponse
	}

	/**
	 * This reusable method can be used for making AAI httpPatch Calls. The url should
	 * be passed as a parameter along with the execution and payload.  The method will
	 * return an APIResponse.
	 *
	 * @param execution
	 * @param url
	 * @param payload
	 *
	 * @return APIResponse
	 *
	 */
	public APIResponse executeAAIPatchCall(DelegateExecution execution, String url, String payload){
		msoLogger.trace("Started Execute AAI Patch Process ")
		APIResponse apiResponse = null
		try{
			String uuid = utils.getRequestID()
			msoLogger.debug("Generated uuid is: " + uuid)

			msoLogger.debug("URL to be used is: " + url)

			String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))

			RESTConfig config = new RESTConfig(url);
			RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/merge-patch+json").addHeader("Accept","application/json");
			if (basicAuthCred != null && !"".equals(basicAuthCred)) {
				client.addAuthorizationHeader(basicAuthCred)
			}
			apiResponse = client.httpPatch(payload)

			msoLogger.trace("Completed Execute AAI Patch Process ")
		}catch(Exception e){
			msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Patch Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
		}
		return apiResponse
	}


	/**
	 * This reusable method can be used for making AAI Delete Calls. The url should
	 * be passed as a parameter along with the execution.  The method will
	 * return an APIResponse.
	 *
	 * @param execution
	 * @param url
	 *
	 * @return APIResponse
	 *
	 */
	public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url){
		msoLogger.trace("Started Execute AAI Delete Process ")
		APIResponse apiResponse = null
		try{
			String uuid = utils.getRequestID()
			msoLogger.debug("Generated uuid is: " + uuid)
			msoLogger.debug("URL to be used is: " + url)

			String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))

			RESTConfig config = new RESTConfig(url);
			RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");
			if (basicAuthCred != null && !"".equals(basicAuthCred)) {
				client.addAuthorizationHeader(basicAuthCred)
			}
			apiResponse = client.delete()

			msoLogger.trace("Completed Execute AAI Delete Process ")
		}catch(Exception e){
			msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
		}
		return apiResponse
	}

	/**
	 * This reusable method can be used for making AAI Delete Calls. The url should
	 * be passed as a parameter along with the execution.  The method will
	 * return an APIResponse.
	 *
	 * @param execution
	 * @param url
	 * @param payload
	 *
	 * @return APIResponse
	 *
	 */
	public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url, String payload, String authHeader){
		msoLogger.trace("Started Execute AAI Delete Process ")
		APIResponse apiResponse = null
		try{
			String uuid = utils.getRequestID()
			msoLogger.debug("Generated uuid is: " + uuid)

			msoLogger.debug("URL to be used is: " + url)

			String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
			RESTConfig config = new RESTConfig(url);
			RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml").addAuthorizationHeader(authHeader);
			if (basicAuthCred != null && !"".equals(basicAuthCred)) {
				client.addAuthorizationHeader(basicAuthCred)
			}
			apiResponse = client.httpDelete(payload)

			msoLogger.trace("Completed Execute AAI Delete Process ")
		}catch(Exception e){
			msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
		}
		return apiResponse
	}

	/**
	 * This reusable method can be used for making AAI Post Calls. The url
	 * and payload should be passed as a parameters along with the execution.
	 * The method will return an APIResponse.
	 *
	 * @param execution
	 * @param url
	 * @param payload
	 *
	 * @return APIResponse
	 *
	 */
	public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload){
		msoLogger.trace("Started Execute AAI Post Process ")
		APIResponse apiResponse = null
		try{
			String uuid = utils.getRequestID()
			msoLogger.debug("Generated uuid is: " + uuid)
			msoLogger.debug("URL to be used is: " + url)

			String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
			RESTConfig config = new RESTConfig(url);
			RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");

			if (basicAuthCred != null && !"".equals(basicAuthCred)) {
				client.addAuthorizationHeader(basicAuthCred)
			}
			apiResponse = client.httpPost(payload)

			msoLogger.trace("Completed Execute AAI Post Process ")
		}catch(Exception e){
			msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
		}
		return apiResponse
	}

	/**
	 * This reusable method can be used for making AAI Post Calls. The url
	 * and payload should be passed as a parameters along with the execution.
	 * The method will return an APIResponse.
	 *
	 * @param execution
	 * @param url
	 * @param payload
	 * @param authenticationHeader - addAuthenticationHeader value
	 * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue)
	 * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue)
	 *
	 * @return APIResponse
	 *
	 */
	public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){
		msoLogger.trace("Started Execute AAI Post Process ")
		APIResponse apiResponse = null
		try{
			msoLogger.debug("URL to be used is: " + url)

			String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))

			RESTConfig config = new RESTConfig(url);
			RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue)
			if (basicAuthCred != null && !"".equals(basicAuthCred)) {
				client.addAuthorizationHeader(basicAuthCred)
			}
			apiResponse = client.httpPost(payload)

			msoLogger.trace("Completed Execute AAI Post Process ")
		}catch(Exception e){
			msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
		}
		return apiResponse
	}


	/* Utility to get the Cloud Region from AAI
	 * Returns String cloud region id, (ie, cloud-region-id)
	 * @param execution
	 * @param url  - url for AAI get cloud region
	 * @param backend - "PO" - real region, or "SDNC" - v2.5 (fake region).
	 */

	public String getAAICloudReqion(DelegateExecution execution, String url, String backend, inputCloudRegion){
		String regionId = ""
		try{
			APIResponse apiResponse = executeAAIGetCall(execution, url)
			String returnCode = apiResponse.getStatusCode()
			String aaiResponseAsString = apiResponse.getResponseBodyAsString()
			msoLogger.debug("Call AAI Cloud Region Return code: " + returnCode)
			execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode)

			if(returnCode == "200"){
				msoLogger.debug("Call AAI Cloud Region is Successful.")

				String regionVersion = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-version")
				msoLogger.debug("Cloud Region Version from AAI for " + backend + " is: " + regionVersion)
				if (backend == "PO") {
					regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
				} else { // backend not "PO"
					if (regionVersion == "2.5" ) {
						regionId = "AAIAIC25"
					} else {
						regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
					}
				}
				if(regionId == null){
					throw new BpmnError("MSOWorkflowException")
				}
				msoLogger.debug("Cloud Region Id from AAI " + backend + " is: " + regionId)
			}else if (returnCode == "404"){ // not 200
				if (backend == "PO") {
					regionId = inputCloudRegion
				}else{  // backend not "PO"
					regionId = "AAIAIC25"
				}
				msoLogger.debug("Cloud Region value for code='404' of " + backend + " is: " + regionId)
			}else{
				msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Call AAI Cloud Region is NOT Successful.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
				throw new BpmnError("MSOWorkflowException")
			}
		}catch(Exception e) {
			msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while getting the Cloud Reqion.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage());
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
		}
		return regionId
	}

	/* returns xml Node with service-type of searchValue */
	def searchServiceType(xmlInput, searchValue){
		def fxml= new XmlSlurper().parseText(xmlInput)
		def ret = fxml.'**'.find {it.'service-type' == searchValue}
		return ret
	}

	/* returns xml Node with service-instance-id of searchValue */
	def searchServiceInstanceId(xmlInput, searchValue){
		def ret = xmlInput.'**'.find {it.'service-instance-id' == searchValue}
		return ret
	}

	/**
	 * Get the lowest unused VF Module index from AAI response for a given module type. The criteria for
	 * determining module type is specified by "key" parameter (for example, "persona-model-id"),
	 * the value for filtering is specified in "value" parameter
	 *
	 * @param execution
	 * @param aaiVnfResponse
	 * @param key
	 * @param value
	 *
	 * @return moduleIndex
	 *
	 */
	public int getLowestUnusedVfModuleIndexFromAAIVnfResponse(DelegateExecution execution, String aaiVnfResponse, String key, String value) {
		if (aaiVnfResponse != null) {
			String vfModulesText = taskProcessor.utils.getNodeXml(aaiVnfResponse, "vf-modules")
			if (vfModulesText == null || vfModulesText.isEmpty()) {
				msoLogger.debug("There are no VF modules in this VNF yet")
				return 0
			}
			else {
				def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
				def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
				int vfModulesSize = 0
				if (vfModules != null) {
					vfModulesSize = vfModules.size()
				}
				String matchingVfModules = "<vfModules>"
				for (i in 0..vfModulesSize-1) {
					def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
					def keyFromAAI = taskProcessor.utils.getNodeText(vfModuleXml, key)
					if (keyFromAAI != null && keyFromAAI.equals(value)) {
						matchingVfModules = matchingVfModules + taskProcessor.utils.removeXmlPreamble(vfModuleXml)
					}
				}
				matchingVfModules = matchingVfModules + "</vfModules>"
				msoLogger.debug("Matching VF Modules: " + matchingVfModules)
				String lowestUnusedIndex = taskProcessor.utils.getLowestUnusedIndex(matchingVfModules)
				return Integer.parseInt(lowestUnusedIndex)
			}
		}
		else {
			return 0
		}
	}

	private def getPInterface(DelegateExecution execution, String aai_uri) {

		String namespace = getNamespaceFromUri(aai_uri)
		String aai_endpoint = execution.getVariable("URN_aai_endpoint")
		String serviceAaiPath = ${aai_endpoint}${aai_uri}

		APIResponse response = executeAAIGetCall(execution, serviceAaiPath)
		return new XmlParser().parseText(response.getResponseBodyAsString())
	}

	// This method checks if interface is remote
	private def isPInterfaceRemote(DelegateExecution execution, String uri) {
		if(uri.contains("ext-aai-network")) {
			return true
		} else {
			return false
		}
	}

	// This method returns Local and remote TPs information from AAI	
	public Map getTPsfromAAI(DelegateExecution execution) {
		Map tpInfo = [:]

		String aai_uri = '/aai/v14/network/logical-links'

		String aai_endpoint = execution.getVariable("URN_aai_endpoint")
		String serviceAaiPath = ${aai_endpoint}${aai_uri}

		APIResponse response = executeAAIGetCall(execution, serviceAaiPath)

		def logicalLinks = new XmlParser().parseText(response.getResponseBodyAsString())

		logicalLinks."logical-links".find { link ->
			def pInterface = []
			def relationship = link."relationship-list"."relationship"
			relationship.each {
				if ("p-interface".compareToIgnoreCase(it."related-to")) {
					pInterface.add(it)
				}
			}
			if (pInterface.size() == 2) {
				def localTP = null
				def remoteTP = null

				if (pInterface[0]."related-link".contains("ext-aai-networks")) {
					remoteTP = pInterface[0]
					localTP = pInterface[1]
				}

				if (pInterface[1]."related-link".contains("ext-aai-networks")) {
					localTP = pInterface[0]
					remoteTP = pInterface[1]
				}

				if (localTP != null && remoteTP != null) {
				
					// give local tp
					var intfLocal = getPInterface(execution, localTP."related-link")
					tpInfotpInfo.put("local-access-node-id", localTP."related-link".split("/")[6])
				
					def networkRef = intfLocal."network-ref".split("/")
					tpInfo.put("local-access-provider-id", networkRef[1])
					tpInfo.put("local-access-client-id", networkRef[3])
					tpInfo.put("local-access-topology-id", networkRef[5])
					tpInfo.put("local-access-ltp-id", localTP."interface-name")
					
					// give local tp
					var intfRemote = getPInterface(execution, remoteTP."related-link")
					tpInfo.put("remote-access-node-id", remoteTP."related-link".split("/")[6])					
					def networkRefRemote = intfRemote."network-ref".split("/")
					tpInfo.put("remote-access-provider-id", networkRefRemote[1])
					tpInfo.put("remote-access-client-id", networkRefRemote[3])
					tpInfo.put("remote-access-topology-id", networkRefRemote[5])
					tpInfo.put("remote-access-ltp-id", remoteTP."interface-name")
				}
			}

		}
		return tpInfo
	}
}