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