Merge "Fix logging in DeleteSDNCNetworkResource"
[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
32
33 class AaiUtil {
34         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, AaiUtil.class);
35
36
37         public MsoUtils utils = new MsoUtils()
38         public static final String AAI_NAMESPACE_STRING_KEY = 'mso.workflow.global.default.aai.namespace'
39         public static final String DEFAULT_VERSION_KEY = 'mso.workflow.global.default.aai.version'
40
41         private String aaiNamespace = null;
42
43         private AbstractServiceTaskProcessor taskProcessor
44
45         public AaiUtil(AbstractServiceTaskProcessor taskProcessor) {
46                 this.taskProcessor = taskProcessor
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 getBusinessCustomerUri(DelegateExecution execution) {
93                 def uri = getUri(execution, 'customer')
94                 msoLogger.debug('AaiUtil.getBusinessCustomerUri() - AAI URI: ' + uri)
95                 return uri
96         }
97         
98         public String getBusinessSPPartnerUri(DelegateExecution execution) {
99                 def uri = getUri(execution, 'sp-partner')
100                 msoLogger.debug('AaiUtil.getBusinessSPPartnerUri() - AAI URI: ' + uri)
101                 return uri
102         }
103
104         //public String getBusinessCustomerUriv7(DelegateExecution execution) {
105         //      //      //def uri = getUri(execution, BUSINESS_CUSTOMERV7)
106         //      def uri = getUri(execution, 'Customer')
107         //      msoLogger.debug('AaiUtil.getBusinessCustomerUriv7() - AAI URI: ' + uri)
108         //      return uri
109         //}
110
111         public String getCloudInfrastructureCloudRegionEndpoint(DelegateExecution execution) {
112                 String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
113                 def uri = getCloudInfrastructureCloudRegionUri(execution)
114                 msoLogger.debug('AaiUtil.getCloudInfrastructureCloudRegionEndpoint() - AAI endpoint: ' + endpoint + uri)
115                 return endpoint + uri
116         }
117
118         public String getCloudInfrastructureCloudRegionUri(DelegateExecution execution) {
119                 def uri = getUri(execution, 'cloud-region')
120                 msoLogger.debug('AaiUtil.getCloudInfrastructureCloudRegionUri() - AAI URI: ' + uri)
121                 return uri
122         }
123
124         public String getCloudInfrastructureTenantUri(DelegateExecution execution) {
125                 def uri = getUri(execution, 'tenant')
126                 msoLogger.debug('AaiUtil.getCloudInfrastructureTenantUri() - AAI URI: ' + uri)
127                 return uri
128         }
129
130         public String getSearchNodesQueryUri(DelegateExecution execution) {
131                 def uri = getUri(execution, 'nodes-query')
132                 msoLogger.debug('AaiUtil.getSearchNodesQueryUri() - AAI URI: ' + uri)
133                 return uri
134         }
135
136         public String getSearchNodesQueryEndpoint(DelegateExecution execution) {
137                 String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
138                 def uri = getSearchNodesQueryUri(execution)
139                 msoLogger.debug('AaiUtil.getSearchNodesQueryEndpoint() - AAI endpoint: ' + endpoint + uri)
140                 return endpoint + uri
141         }
142
143         public String getSearchGenericQueryUri(DelegateExecution execution) {
144                 def uri = getUri(execution, 'generic-query')
145                 msoLogger.debug('AaiUtil.getSearchGenericQueryUri() - AAI URI: ' + uri)
146                 return uri
147         }
148
149         public String getVersion(DelegateExecution execution, resourceName, processKey) {
150                 def versionWithResourceKey = "mso.workflow.default.aai.${resourceName}.version"
151                 def versionWithProcessKey = "mso.workflow.custom.${processKey}.aai.version"
152
153                 def version = UrnPropertiesReader.getVariable(versionWithProcessKey, execution)
154                 if (version) {
155                         msoLogger.debug("AaiUtil.getVersion() - using flow specific ${versionWithProcessKey}=${version}")
156                         return version
157                 }
158
159                 version = UrnPropertiesReader.getVariable(versionWithResourceKey, execution)
160                 if (version) {
161                         msoLogger.debug("AaiUtil.getVersion() - using resource specific ${versionWithResourceKey}=${version}")
162                         return version
163                 }
164
165                 version = UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY, execution)
166                 if (version) {
167                         msoLogger.debug("AaiUtil.getVersion() - using default version ${DEFAULT_VERSION_KEY}=${version}")
168                         return version
169                 }
170
171                 (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, "Internal Error: One of the following should be defined in MSO URN properties file: ${versionWithResourceKey}, ${versionWithProcessKey}, ${DEFAULT_VERSION_KEY}")
172         }
173
174         public String getUri(DelegateExecution execution, resourceName) {
175
176                 def processKey = taskProcessor.getMainProcessKey(execution)
177
178                 //set namespace
179                 setNamespace(execution)
180
181                 // Check for flow+resource specific first
182                 def key = "mso.workflow.${processKey}.aai.${resourceName}.uri"
183                 def uri = UrnPropertiesReader.getVariable(key, execution)
184                 if(uri) {
185                         msoLogger.debug("AaiUtil.getUri() - using flow+resource specific key: ${key}=${uri}")
186                         return uri
187                 }
188
189                 // Check for versioned key
190                 def version = getVersion(execution, resourceName, processKey)
191                 key = "mso.workflow.default.aai.v${version}.${resourceName}.uri"
192                 uri = UrnPropertiesReader.getVariable(key, execution)
193
194                 if(uri) {
195                         msoLogger.debug("AaiUtil.getUri() - using versioned URI key: ${key}=${uri}")
196                         return uri
197                 }
198
199                 (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file')
200         }
201
202         public String setNamespace(DelegateExecution execution) {
203                 def key = AAI_NAMESPACE_STRING_KEY
204                 aaiNamespace = UrnPropertiesReader.getVariable(key, execution)
205                 if (aaiNamespace == null ) {
206                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file')
207                 }
208         }
209
210         /**
211          * This method can be used for getting the building namespace out of uri.
212          *  NOTE: A getUri() method needs to be invoked first.
213          *        Alternative method is the getNamespaceFromUri(DelegateExecution execution, String uri)
214          * return namespace (plus version from uri)
215          *
216          * @param url
217          *
218          * @return namespace
219          */
220
221         public String getNamespaceFromUri(String uri) {
222                  if (aaiNamespace == null) {
223                         throw new Exception('Internal Error: AAI Namespace has not been set yet. A getUri() method needs to be invoked first.')
224                 }
225                 String namespace = aaiNamespace
226                 if(uri!=null){
227                         String version = getVersionFromUri(uri)
228                         return namespace + "v"+version
229                 }else{
230                         return namespace
231                 }
232         }
233
234         /**
235          * This method can be used for building namespace with aai version out of uri.
236          *   NOTE: 2 arguments: DelegateExecution execution & String uri
237          * @param execution
238          * @param url
239          *
240          * @return namespace
241          */
242         public String getNamespaceFromUri(DelegateExecution execution, String uri) {
243            String namespace = UrnPropertiesReader.getVariable(AAI_NAMESPACE_STRING_KEY, execution)
244            if (namespace == null ) {
245                    (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + AAI_NAMESPACE_STRING_KEY + ' not defined in the MSO URN properties file')
246            }
247            if(uri!=null){
248                    String version = getVersionFromUri(uri)
249                    return namespace + "v"+version
250            }else{
251                    return namespace
252            }
253    }
254
255         /**
256          * This is used to extract the version from uri.
257          *
258          * @param uri
259          *
260          * @return version
261          */
262         private String getVersionFromUri(String uri) {
263                 def version = ""
264                 def savedVersion = ""
265                 for (int x=2; x<6; x++) {
266                         version = uri.substring(uri.indexOf("v")+1,  uri.indexOf("v")+x)
267                         if (!Character.isDigit(version.charAt(version.size()-1))) {
268                                 break
269                         }
270                         savedVersion = version
271                 }
272                 return savedVersion
273         }
274
275
276         /**
277          * This reusable method can be used for making AAI Get Calls. The url should
278          * be passed as a parameter along with the execution.  The method will
279          * return an APIResponse.
280          *
281          * @param execution
282          * @param url
283          *
284          * @return APIResponse
285          *
286          */
287         public APIResponse executeAAIGetCall(DelegateExecution execution, String url){
288                 msoLogger.trace("STARTED Execute AAI Get Process ")
289                 APIResponse apiResponse = null
290                 try{
291                         String uuid = utils.getRequestID()
292                         msoLogger.debug("Generated uuid is: " + uuid)
293                         msoLogger.debug("URL to be used is: " + url)
294
295                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
296
297                         RESTConfig config = new RESTConfig(url);
298                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");
299
300                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
301                                 client.addAuthorizationHeader(basicAuthCred)
302                         }
303                         apiResponse = client.get()
304
305                         msoLogger.trace("COMPLETED Execute AAI Get Process ")
306                 }catch(Exception e){
307                         msoLogger.debug("Exception occured while executing AAI Get Call. Exception is: \n" + e)
308                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
309                 }
310                 return apiResponse
311         }
312
313
314         /**
315          * This reusable method can be used for making AAI httpPut Calls. The url should
316          * be passed as a parameter along with the execution and payload.  The method will
317          * return an APIResponse.
318          *
319          * @param execution
320          * @param url
321          * @param payload
322          *
323          * @return APIResponse
324          *
325          */
326         public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){
327                 msoLogger.trace("Started Execute AAI Put Process ")
328                 APIResponse apiResponse = null
329                 try{
330                         String uuid = utils.getRequestID()
331                         msoLogger.debug("Generated uuid is: " + uuid)
332                         msoLogger.debug("URL to be used is: " + url)
333
334                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
335
336                         RESTConfig config = new RESTConfig(url);
337                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");
338                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
339                                 client.addAuthorizationHeader(basicAuthCred)
340                         }
341                         apiResponse = client.httpPut(payload)
342
343                         msoLogger.trace("Completed Execute AAI Put Process ")
344                 }catch(Exception e){
345                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
346                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
347                 }
348                 return apiResponse
349         }
350
351         /**
352          * This reusable method can be used for making AAI httpPatch Calls. The url should
353          * be passed as a parameter along with the execution and payload.  The method will
354          * return an APIResponse.
355          *
356          * @param execution
357          * @param url
358          * @param payload
359          *
360          * @return APIResponse
361          *
362          */
363         public APIResponse executeAAIPatchCall(DelegateExecution execution, String url, String payload){
364                 msoLogger.trace("Started Execute AAI Patch Process ")
365                 APIResponse apiResponse = null
366                 try{
367                         String uuid = utils.getRequestID()
368                         msoLogger.debug("Generated uuid is: " + uuid)
369
370                         msoLogger.debug("URL to be used is: " + url)
371
372                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
373
374                         RESTConfig config = new RESTConfig(url);
375                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/merge-patch+json").addHeader("Accept","application/json");
376                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
377                                 client.addAuthorizationHeader(basicAuthCred)
378                         }
379                         apiResponse = client.httpPatch(payload)
380
381                         msoLogger.trace("Completed Execute AAI Patch Process ")
382                 }catch(Exception e){
383                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Patch Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
384                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
385                 }
386                 return apiResponse
387         }
388
389
390         /**
391          * This reusable method can be used for making AAI Delete Calls. The url should
392          * be passed as a parameter along with the execution.  The method will
393          * return an APIResponse.
394          *
395          * @param execution
396          * @param url
397          *
398          * @return APIResponse
399          *
400          */
401         public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url){
402                 msoLogger.trace("Started Execute AAI Delete Process ")
403                 APIResponse apiResponse = null
404                 try{
405                         String uuid = utils.getRequestID()
406                         msoLogger.debug("Generated uuid is: " + uuid)
407                         msoLogger.debug("URL to be used is: " + url)
408
409                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
410
411                         RESTConfig config = new RESTConfig(url);
412                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");
413                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
414                                 client.addAuthorizationHeader(basicAuthCred)
415                         }
416                         apiResponse = client.delete()
417
418                         msoLogger.trace("Completed Execute AAI Delete Process ")
419                 }catch(Exception e){
420                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
421                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
422                 }
423                 return apiResponse
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          * @param payload
434          *
435          * @return APIResponse
436          *
437          */
438         public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url, String payload, String authHeader){
439                 msoLogger.trace("Started Execute AAI Delete Process ")
440                 APIResponse apiResponse = null
441                 try{
442                         String uuid = utils.getRequestID()
443                         msoLogger.debug("Generated uuid is: " + uuid)
444
445                         msoLogger.debug("URL to be used is: " + url)
446
447                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
448                         RESTConfig config = new RESTConfig(url);
449                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml").addAuthorizationHeader(authHeader);
450                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
451                                 client.addAuthorizationHeader(basicAuthCred)
452                         }
453                         apiResponse = client.httpDelete(payload)
454
455                         msoLogger.trace("Completed Execute AAI Delete Process ")
456                 }catch(Exception e){
457                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
458                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
459                 }
460                 return apiResponse
461         }
462
463         /**
464          * This reusable method can be used for making AAI Post Calls. The url
465          * and payload should be passed as a parameters along with the execution.
466          * The method will return an APIResponse.
467          *
468          * @param execution
469          * @param url
470          * @param payload
471          *
472          * @return APIResponse
473          *
474          */
475         public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload){
476                 msoLogger.trace("Started Execute AAI Post Process ")
477                 APIResponse apiResponse = null
478                 try{
479                         String uuid = utils.getRequestID()
480                         msoLogger.debug("Generated uuid is: " + uuid)
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");
486
487                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
488                                 client.addAuthorizationHeader(basicAuthCred)
489                         }
490                         apiResponse = client.httpPost(payload)
491
492                         msoLogger.trace("Completed Execute AAI Post Process ")
493                 }catch(Exception e){
494                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
495                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
496                 }
497                 return apiResponse
498         }
499
500         /**
501          * This reusable method can be used for making AAI Post Calls. The url
502          * and payload should be passed as a parameters along with the execution.
503          * The method will return an APIResponse.
504          *
505          * @param execution
506          * @param url
507          * @param payload
508          * @param authenticationHeader - addAuthenticationHeader value
509          * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue)
510          * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue)
511          *
512          * @return APIResponse
513          *
514          */
515         public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){
516                 msoLogger.trace("Started Execute AAI Post Process ")
517                 APIResponse apiResponse = null
518                 try{
519                         msoLogger.debug("URL to be used is: " + url)
520
521                         String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
522
523                         RESTConfig config = new RESTConfig(url);
524                         RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue)
525                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
526                                 client.addAuthorizationHeader(basicAuthCred)
527                         }
528                         apiResponse = client.httpPost(payload)
529
530                         msoLogger.trace("Completed Execute AAI Post Process ")
531                 }catch(Exception e){
532                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
533                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
534                 }
535                 return apiResponse
536         }
537
538
539         /* Utility to get the Cloud Region from AAI
540          * Returns String cloud region id, (ie, cloud-region-id)
541          * @param execution
542          * @param url  - url for AAI get cloud region
543          * @param backend - "PO" - real region, or "SDNC" - v2.5 (fake region).
544          */
545
546         public String getAAICloudReqion(DelegateExecution execution, String url, String backend, inputCloudRegion){
547                 String regionId = ""
548                 try{
549                         APIResponse apiResponse = executeAAIGetCall(execution, url)
550                         String returnCode = apiResponse.getStatusCode()
551                         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
552                         msoLogger.debug("Call AAI Cloud Region Return code: " + returnCode)
553                         execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode)
554
555                         if(returnCode == "200"){
556                                 msoLogger.debug("Call AAI Cloud Region is Successful.")
557
558                                 String regionVersion = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-version")
559                                 msoLogger.debug("Cloud Region Version from AAI for " + backend + " is: " + regionVersion)
560                                 if (backend == "PO") {
561                                         regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
562                                 } else { // backend not "PO"
563                                         if (regionVersion == "2.5" ) {
564                                                 regionId = "AAIAIC25"
565                                         } else {
566                                                 regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
567                                         }
568                                 }
569                                 if(regionId == null){
570                                         throw new BpmnError("MSOWorkflowException")
571                                 }
572                                 msoLogger.debug("Cloud Region Id from AAI " + backend + " is: " + regionId)
573                         }else if (returnCode == "404"){ // not 200
574                                 if (backend == "PO") {
575                                         regionId = inputCloudRegion
576                                 }else{  // backend not "PO"
577                                         regionId = "AAIAIC25"
578                                 }
579                                 msoLogger.debug("Cloud Region value for code='404' of " + backend + " is: " + regionId)
580                         }else{
581                                 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Call AAI Cloud Region is NOT Successful.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
582                                 throw new BpmnError("MSOWorkflowException")
583                         }
584                 }catch(Exception e) {
585                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while getting the Cloud Reqion.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage());
586                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
587                 }
588                 return regionId
589         }
590
591         /* returns xml Node with service-type of searchValue */
592         def searchServiceType(xmlInput, searchValue){
593                 def fxml= new XmlSlurper().parseText(xmlInput)
594                 def ret = fxml.'**'.find {it.'service-type' == searchValue}
595                 return ret
596         }
597
598         /* returns xml Node with service-instance-id of searchValue */
599         def searchServiceInstanceId(xmlInput, searchValue){
600                 def ret = xmlInput.'**'.find {it.'service-instance-id' == searchValue}
601                 return ret
602         }
603
604         /**
605          * Get the lowest unused VF Module index from AAI response for a given module type. The criteria for
606          * determining module type is specified by "key" parameter (for example, "persona-model-id"),
607          * the value for filtering is specified in "value" parameter
608          *
609          * @param execution
610          * @param aaiVnfResponse
611          * @param key
612          * @param value
613          *
614          * @return moduleIndex
615          *
616          */
617         public int getLowestUnusedVfModuleIndexFromAAIVnfResponse(DelegateExecution execution, String aaiVnfResponse, String key, String value) {
618                 if (aaiVnfResponse != null) {
619                         String vfModulesText = taskProcessor.utils.getNodeXml(aaiVnfResponse, "vf-modules")
620                         if (vfModulesText == null || vfModulesText.isEmpty()) {
621                                 msoLogger.debug("There are no VF modules in this VNF yet")
622                                 return 0
623                         }
624                         else {
625                                 def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
626                                 def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
627                                 int vfModulesSize = 0
628                                 if (vfModules != null) {
629                                         vfModulesSize = vfModules.size()
630                                 }
631                                 String matchingVfModules = "<vfModules>"
632                                 for (i in 0..vfModulesSize-1) {
633                                         def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
634                                         def keyFromAAI = taskProcessor.utils.getNodeText(vfModuleXml, key)
635                                         if (keyFromAAI != null && keyFromAAI.equals(value)) {
636                                                 matchingVfModules = matchingVfModules + taskProcessor.utils.removeXmlPreamble(vfModuleXml)
637                                         }
638                                 }
639                                 matchingVfModules = matchingVfModules + "</vfModules>"
640                                 msoLogger.debug("Matching VF Modules: " + matchingVfModules)
641                                 String lowestUnusedIndex = taskProcessor.utils.getLowestUnusedIndex(matchingVfModules)
642                                 return Integer.parseInt(lowestUnusedIndex)
643                         }
644                 }
645                 else {
646                         return 0
647                 }
648         }
649 }