c77e6b8a7599c658cbc58ed33d6a5c9a751d217f
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / ServiceIntentUtils.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.infrastructure.scripts
22
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.aai.domain.yang.AllottedResources
26 import org.onap.aai.domain.yang.LogicalLink
27 import org.onap.aai.domain.yang.NetworkPolicy
28 import org.onap.aai.domain.yang.Relationship
29 import org.onap.aai.domain.yang.ServiceInstance
30 import org.onap.aaiclient.client.aai.AAIResourcesClient
31 import org.onap.aaiclient.client.aai.AAIVersion
32 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
33 import org.onap.aaiclient.client.aai.entities.Relationships
34 import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri
35 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
36 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
37 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
38 import org.onap.so.bpmn.common.scripts.ExceptionUtil
39 import org.onap.so.bpmn.common.scripts.MsoUtils
40 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
41 import org.onap.so.bpmn.core.RollbackData
42 import org.onap.so.bpmn.core.UrnPropertiesReader
43 import org.onap.so.bpmn.core.WorkflowException
44 import org.onap.so.bpmn.core.json.JsonUtils
45 import org.onap.so.db.request.beans.ResourceOperationStatus
46 import org.slf4j.Logger
47 import org.slf4j.LoggerFactory
48
49 import static org.apache.commons.lang3.StringUtils.isBlank
50 import static org.apache.commons.lang3.StringUtils.isNotBlank
51
52 class ServiceIntentUtils {
53     static final String AAI_VERSION = AAIVersion.LATEST
54     private static final Logger logger = LoggerFactory.getLogger(ServiceIntentUtils.class);
55
56
57     ExceptionUtil exceptionUtil = new ExceptionUtil()
58     JsonUtils jsonUtil = new JsonUtils()
59     MsoUtils msoUtils = new MsoUtils()
60     SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
61
62     ServiceIntentUtils() {
63     }
64
65
66     void setCommonExecutionVars(DelegateExecution execution) {
67         setCommonExecutionVars(execution, true)
68     }
69
70     void setCommonExecutionVars(DelegateExecution execution, boolean exceptionOnErr) {
71         def msg
72         try {
73             // get request input
74             String bpmnRequestStr = execution.getVariable("bpmnRequest")
75             logger.debug("Input Request: " + bpmnRequestStr)
76
77             String requestId = execution.getVariable("mso-request-id")
78             execution.setVariable("msoRequestId", requestId)
79             logger.debug("requestId: " + requestId)
80
81             //subscriberInfo
82             String globalSubscriberId = jsonUtil.getJsonValue(bpmnRequestStr, "globalSubscriberId")
83             if (isBlank(globalSubscriberId) && exceptionOnErr) {
84                 msg = "Input globalSubscriberId' is null"
85                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
86             } else {
87                 execution.setVariable("globalSubscriberId", globalSubscriberId)
88             }
89
90             String serviceType = jsonUtil.getJsonValue(bpmnRequestStr, "serviceType")
91             if (isBlank(serviceType) && exceptionOnErr) {
92                 msg = "Input serviceType is null"
93                 logger.debug(msg)
94                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
95             } else {
96                 execution.setVariable("serviceType", serviceType)
97             }
98
99             String servicename = jsonUtil.getJsonValue(bpmnRequestStr, "name")
100             if (isNotBlank(servicename)) {
101                 execution.setVariable("servicename", servicename)
102             } else {
103                 logger.debug("erviceIntentUtils.setCommonExecutionVars: servicename is NOT set")
104             }
105
106             //requestParameters, subscriptionServiceType is 5G
107             String subscriptionServiceType = jsonUtil.getJsonValue(bpmnRequestStr, "subscriptionServiceType")
108             if (isBlank(subscriptionServiceType)) {
109                 msg = "Input subscriptionServiceType is null"
110                 logger.debug(msg)
111                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
112             } else {
113                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
114             }
115
116             String jobId = UUID.randomUUID().toString()
117             execution.setVariable("jobId", jobId)
118
119             String sliceParams = jsonUtil.getJsonValue(bpmnRequestStr, "additionalProperties")
120             execution.setVariable("serviceIntentParams", sliceParams)
121
122         } catch (BpmnError e) {
123             throw e
124         } catch (Exception ex) {
125             msg = "Exception in ServiceIntentUtils.setCommonExecutionVars: " + ex.getMessage()
126             logger.debug(msg)
127             if (exceptionOnErr) {
128                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
129             }
130         }
131     }
132
133     void setSdncCallbackUrl(DelegateExecution execution, boolean exceptionOnErr) {
134         setSdncCallbackUrl(execution, "sdncCallbackUrl", exceptionOnErr)
135     }
136
137     void setSdncCallbackUrl(DelegateExecution execution, String variableName, boolean exceptionOnErr) {
138         String sdncCallbackUrl = UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback', execution)
139
140         if (isBlank(sdncCallbackUrl) && exceptionOnErr) {
141             String msg = "mso.workflow.sdncadapter.callback is null"
142             logger.debug(msg)
143             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
144         } else {
145             execution.setVariable(variableName, sdncCallbackUrl)
146         }
147     }
148
149     String buildSDNCRequest(DelegateExecution execution, String svcInstId, String svcAction) {
150         String reqAction
151         switch (svcAction) {
152             case "create":
153                 reqAction = "CreateCloudLeasedLineInstance"
154                 break
155             case "delete":
156                 reqAction = "DeleteCloudLeasedLineInstance"
157                 break
158             case "activate":
159                 reqAction = "ActivateCloudLeasedLineInstance"
160                 break
161             case "deactivate":
162                 reqAction = "DeactivateCloudLeasedLineInstance"
163                 break
164             case "update":
165                 reqAction = "ModifyCloudLeasedLineInstance"
166                 break
167             default:
168                 reqAction = svcAction
169         }
170
171         buildSDNCRequest(execution, svcInstId, svcAction, reqAction)
172     }
173
174     String buildSDNCRequest(DelegateExecution execution, String svcInstId, String svcAction, String reqAction) {
175
176         String uuid = execution.getVariable('testReqId') // for junits
177         if (uuid == null) {
178             uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis()
179         }
180
181         def callbackURL = execution.getVariable("sdncCallbackUrl")
182         def requestId = execution.getVariable("msoRequestId")
183         def serviceId = execution.getVariable("sliceServiceInstanceId")
184         def subServiceType = execution.getVariable("subscriptionServiceType")
185         def vnfType = execution.getVariable("serviceType")
186         def vnfName = execution.getVariable("sliceServiceInstanceName")
187         def tenantId = execution.getVariable("sliceServiceInstanceId")
188         def source = execution.getVariable("sliceServiceInstanceId")
189         def vnfId = execution.getVariable("sliceServiceInstanceId")
190         def cloudSiteId = execution.getVariable("sliceServiceInstanceId")
191         def serviceModelInfo = execution.getVariable("serviceModelInfo")
192         def vnfModelInfo = execution.getVariable("serviceModelInfo")
193         def globalSubscriberId = execution.getVariable("globalSubscriberId")
194
195         String vnfNameString = """<vnf-name>${MsoUtils.xmlEscape(vnfName)}</vnf-name>"""
196         String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo)
197         String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo)
198
199         String sdncVNFParamsXml = ""
200
201         if (execution.getVariable("vnfParamsExistFlag") == true) {
202             sdncVNFParamsXml = buildSDNCParamsXml(execution)
203         } else {
204             sdncVNFParamsXml = buildDefaultVnfInputParams(vnfId)
205         }
206
207         String sdncRequest =
208                 """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
209                                                     xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
210                                                     xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
211          <sdncadapter:RequestHeader>
212             <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
213             <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
214             <sdncadapter:SvcAction>${MsoUtils.xmlEscape(svcAction)}</sdncadapter:SvcAction>
215             <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
216             <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
217             <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
218          </sdncadapter:RequestHeader>
219     <sdncadapterworkflow:SDNCRequestData>
220         <request-information>
221             <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
222             <request-action>${MsoUtils.xmlEscape(reqAction)}</request-action>
223             <source>${MsoUtils.xmlEscape(source)}</source>
224             <notification-url/>
225             <order-number/>
226             <order-version/>
227         </request-information>
228         <service-information>
229             <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
230             <subscription-service-type>${MsoUtils.xmlEscape(subServiceType)}</subscription-service-type>
231             ${serviceEcompModelInformation}
232             <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
233             <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
234         </service-information>
235         <vnf-information>
236             <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
237             <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
238             ${vnfEcompModelInformation}
239         </vnf-information>
240         <vnf-request-input>
241             ${vnfNameString}
242             <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
243             <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
244             ${sdncVNFParamsXml}
245         </vnf-request-input>
246     </sdncadapterworkflow:SDNCRequestData>
247     </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
248
249         logger.debug("sdncRequest:  " + sdncRequest)
250         return sdncRequest
251     }
252
253
254     String buildDefaultVnfInputParams(String vnfName) {
255         String res =
256                 """<vnf-input-parameters>
257                       <param>
258                           <name>${MsoUtils.xmlEscape(vnfName)}</name>
259                       </param>
260                    </vnf-input-parameters>"""
261
262         return res
263     }
264
265     String buildSDNCParamsXml(DelegateExecution execution) {
266         String params = ""
267         StringBuilder sb = new StringBuilder()
268         Map<String, String> paramsMap = execution.getVariable("TNNSSMF_vnfParamsMap")
269
270         for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
271             String paramsXml
272             String key = entry.getKey();
273             String value = entry.getValue()
274             paramsXml = """<${key}>$value</$key>"""
275             params = sb.append(paramsXml)
276         }
277         return params
278     }
279
280     void validateSDNCResponse(DelegateExecution execution, String response, String method) {
281         validateSDNCResponse(execution, response, method, true)
282     }
283
284     void validateSDNCResponse(DelegateExecution execution, String response, String method, boolean exceptionOnErr) {
285         logger.debug("STARTED ValidateSDNCResponse Process")
286
287         String msg
288
289         String prefix = execution.getVariable("prefix")
290         if (isBlank(prefix)) {
291             if (exceptionOnErr) {
292                 msg = "validateSDNCResponse: prefix is null"
293                 logger.error(msg)
294                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
295             }
296             return
297         }
298
299         WorkflowException workflowException = execution.getVariable("WorkflowException")
300         boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
301
302         logger.debug("ServiceIntentUtils.validateSDNCResponse: SDNCResponse: " + response)
303         logger.debug("ServiceIntentUtils.validateSDNCResponse: workflowException: " + workflowException)
304
305         sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
306
307         String sdncResponse = response
308         if (execution.getVariable(prefix + 'sdncResponseSuccess') == true) {
309             logger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse)
310             RollbackData rollbackData = execution.getVariable("rollbackData")
311             if (rollbackData == null) {
312                 rollbackData = new RollbackData()
313             }
314
315             if (method.equals("allocate")) {
316                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestAllocate", "true")
317             } else if (method.equals("deallocate")) {
318                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeallocate", "true")
319             } else if (method.equals("activate")) {
320                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestActivate", "true")
321             } else if (method.equals("deactivate")) {
322                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestDeactivate", "true")
323             } else if (method.equals("modify")) {
324                 rollbackData.put("VNFMODULE", "rollbackSDNCRequestModify", "true")
325             }
326             execution.setVariable("rollbackData", rollbackData)
327         } else {
328             if (exceptionOnErr) {
329                 msg = "ServiceIntentUtils.validateSDNCResponse: bad Response from SDNC Adapter for " + method + " SDNC Call."
330                 logger.error(msg)
331                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
332             }
333         }
334
335         logger.debug("COMPLETED ValidateSDNCResponse Process")
336     }
337
338     String getExecutionInputParams(DelegateExecution execution) {
339         String res = "\n msoRequestId=" + execution.getVariable("msoRequestId") +
340                 "\n modelInvariantUuid=" + execution.getVariable("modelInvariantUuid") +
341                 "\n modelUuid=" + execution.getVariable("modelUuid") +
342                 "\n serviceInstanceID=" + execution.getVariable("serviceInstanceID") +
343                 "\n operationType=" + execution.getVariable("operationType") +
344                 "\n globalSubscriberId=" + execution.getVariable("globalSubscriberId") +
345                 "\n dummyServiceId=" + execution.getVariable("dummyServiceId") +
346                 "\n nsiId=" + execution.getVariable("nsiId") +
347                 "\n serviceType=" + execution.getVariable("serviceType") +
348                 "\n subscriptionServiceType=" + execution.getVariable("subscriptionServiceType") +
349                 "\n jobId=" + execution.getVariable("jobId") +
350                 "\n serviceIntentParams=" + execution.getVariable("serviceIntentParams") +
351                 "\n servicename=" + execution.getVariable("servicename")
352
353         return res
354     }
355
356     String getFirstSnssaiFromSliceProfile(String sliceProfileStr) {
357         String snssaiListStr = jsonUtil.getJsonValue(sliceProfileStr, "snssaiList")
358         String snssai = jsonUtil.StringArrayToList(snssaiListStr).get(0)
359
360         return snssai
361     }
362
363     String getFirstPlmnIdFromSliceProfile(String sliceProfileStr) {
364         String plmnListStr = jsonUtil.getJsonValue(sliceProfileStr, "pLMNIdList")
365         String res = jsonUtil.StringArrayToList(plmnListStr).get(0)
366
367         return res
368     }
369
370     void createRelationShipInAAI(DelegateExecution execution, AAIResourceUri uri, Relationship relationship) {
371         logger.debug("createRelationShipInAAI Start")
372         String msg
373         AAIResourcesClient client = new AAIResourcesClient()
374         try {
375             if (!client.exists(uri)) {
376                 logger.info("ERROR: createRelationShipInAAI: not exist: uri={}", uri)
377                 return
378             }
379             AAIResourceUri from = ((AAIResourceUri) (uri.clone())).relationshipAPI()
380             client.create(from, relationship)
381
382         } catch (BpmnError e) {
383             throw e
384         } catch (Exception ex) {
385             msg = "Exception in createRelationShipInAAI. " + ex.getMessage()
386             logger.info(msg)
387             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
388         }
389         logger.debug("createRelationShipInAAI Exit")
390     }
391
392     void attachLogicalLinkToAllottedResource(DelegateExecution execution, String aaiVersion, AAIResourceUri arUri,
393                                              String logicalLinkId) {
394
395         String toLink = "aai/${aaiVersion}/network/logical-links/logical-link/${logicalLinkId}"
396
397         Relationship relationship = new Relationship()
398         relationship.setRelatedLink(toLink)
399         relationship.setRelatedTo("logical-link")
400         relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
401
402         createRelationShipInAAI(execution, arUri, relationship)
403     }
404
405     void attachNetworkPolicyToAllottedResource(DelegateExecution execution, String aaiVersion,
406                                                AAIResourceUri aaiResourceUri, String networkPolicyId) {
407
408         String toLink = "aai/${aaiVersion}/network/network-policies/network-policy/${networkPolicyId}"
409
410         Relationship relationship = new Relationship()
411         relationship.setRelatedLink(toLink)
412         relationship.setRelatedTo("network-policy")
413         relationship.setRelationshipLabel("org.onap.relationships.inventory.Uses")
414
415         createRelationShipInAAI(execution, aaiResourceUri, relationship)
416
417     }
418
419     ResourceOperationStatus buildRoStatus(String nsstId,
420                                           String nssiId,
421                                           String jobId,
422                                           String nsiId,
423                                           String action,
424                                           String status,
425                                           String progress,
426                                           String statusDescription) {
427         ResourceOperationStatus roStatus = new ResourceOperationStatus()
428         roStatus.setResourceTemplateUUID(nsstId)
429         roStatus.setResourceInstanceID(nssiId)
430         roStatus.setServiceId(nsiId)
431         roStatus.setOperationId(jobId)
432         roStatus.setOperType(action)
433         roStatus.setProgress(progress)
434         roStatus.setStatus(status)
435         roStatus.setStatusDescription(statusDescription)
436
437         return roStatus
438     }
439
440
441     void setEnableSdncConfig(DelegateExecution execution) {
442         String enableSdnc = UrnPropertiesReader.getVariable(
443                 "mso.workflow.TnNssmf.enableSDNCNetworkConfig")
444         if (isBlank(enableSdnc)) {
445             logger.debug("mso.workflow.TnNssmf.enableSDNCNetworkConfig is undefined, so use default value (true)")
446             enableSdnc = "true"
447         }
448
449         logger.debug("setEnableSdncConfig: enableSdnc=" + enableSdnc)
450
451         execution.setVariable("enableSdnc", enableSdnc)
452     }
453
454     String setExecVarFromJsonIfExists(DelegateExecution execution,
455                                       String jsonStr, String jsonKey, String varName) {
456         return setExecVarFromJsonStr(execution, jsonStr, jsonKey, varName, false)
457     }
458
459     String setExecVarFromJsonStr(DelegateExecution execution,
460                                  String jsonStr, String jsonKey, String varName,
461                                  boolean exceptionOnErr) {
462         String msg = ""
463         String valueStr = jsonUtil.getJsonValue(jsonStr, jsonKey)
464         if (isBlank(valueStr)) {
465             if (exceptionOnErr) {
466                 msg = "cannot find " + jsonKey + " in " + jsonStr
467                 logger.debug(msg)
468                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
469             }
470         } else {
471             execution.setVariable(varName, valueStr)
472         }
473
474         return valueStr
475     }
476
477     ServiceInstance getServiceInstanceFromAai(String serviceInstanceId) {
478         if (isBlank(serviceInstanceId)) {
479             logger.error("ERROR: getServiceInstanceFromAai: serviceInstanceId is blank")
480             return null
481         }
482
483         ServiceInstance nssi = null
484         AAIResourcesClient client = new AAIResourcesClient()
485         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.Types.SERVICE_INSTANCE
486                 .getFragment(serviceInstanceId))
487         Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, uri)
488
489         if (nssiOpt.isPresent()) {
490             nssi = nssiOpt.get()
491             return nssi
492         } else {
493             String msg = String.format("ERROR: getServiceInstanceFromAai: NSSI %s not found in AAI", serviceInstanceId)
494             logger.error(msg)
495         }
496
497         return nssi;
498     }
499
500     String getModelUuidFromServiceInstance(String serviceInstanceId) {
501         ServiceInstance si = getServiceInstanceFromAai(serviceInstanceId)
502         if (si == null) {
503             String msg = String.format("ERROR: getModelUuidFromServiceInstance: getServiceInstanceFromAai() failed. " +
504                     "serviceInstanceId=%s", serviceInstanceId)
505             logger.error(msg)
506             return null
507         }
508
509         return si.getModelVersionId()
510     }
511
512     AAIResourceUri buildNetworkPolicyUri(String networkPolicyId) {
513         AAIResourceUri networkPolicyUri =
514                 AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().networkPolicy(networkPolicyId))
515
516         return networkPolicyUri
517     }
518
519     AAIResourceUri buildAllottedResourceUri(DelegateExecution execution, String serviceInstanceId,
520                                             String allottedResourceId) {
521
522         AAIResourceUri allottedResourceUri =
523                 AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
524                         .customer(execution.getVariable("globalSubscriberId"))
525                         .serviceSubscription(execution.getVariable("subscriptionServiceType"))
526                         .serviceInstance(serviceInstanceId)
527                         .allottedResource(allottedResourceId))
528
529         return allottedResourceUri
530     }
531
532     AAIPluralResourceUri buildAllottedResourcesUri(DelegateExecution execution, String serviceInstanceId) {
533
534         AAIPluralResourceUri arsUri =
535                 AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
536                         .customer(execution.getVariable("globalSubscriberId"))
537                         .serviceSubscription(execution.getVariable("subscriptionServiceType"))
538                         .serviceInstance(serviceInstanceId)
539                         .allottedResources())
540
541         return arsUri
542     }
543
544     AllottedResources getAllottedResourcesFromAai(DelegateExecution execution, String serviceInstanceId, boolean exceptionOnErr) {
545         AllottedResources res
546         try {
547             AAIResourcesClient client = new AAIResourcesClient()
548
549             AAIPluralResourceUri arsUri = buildAllottedResourcesUri(execution, serviceInstanceId)
550
551             //AAIResultWrapper wrapperAllotted = client.get(arsUri, NotFoundException.class)
552             //Optional<AllottedResources> allAllotted = wrapperAllotted.asBean(AllottedResources.class)
553             //AllottedResources allottedResources = allAllotted.get()
554
555             Optional<AllottedResources> arsOpt = client.get(AllottedResources.class, arsUri)
556             if (arsOpt.isPresent()) {
557                 res = arsOpt.get()
558                 return res
559             } else {
560                 String msg = String.format("ERROR: getAllottedResourcesFromAai: ars not found. nssiId=%s", serviceInstanceId)
561                 logger.error(msg)
562                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
563             }
564         } catch (BpmnError e) {
565             if (exceptionOnErr) {
566                 throw e;
567             }
568         } catch (Exception ex) {
569             if (exceptionOnErr) {
570                 String msg = String.format("ERROR: getAllottedResourcesFromAai: %s", ex.getMessage())
571                 logger.error(msg)
572                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
573             }
574         }
575
576         return res
577     }
578
579     String getPolicyIdFromAr(DelegateExecution execution, String serviceInstanceId,
580                              String arId, boolean exceptionOnErr) {
581         String res
582         try {
583             AAIResourcesClient client = new AAIResourcesClient()
584
585             AAIResourceUri arUri = buildAllottedResourceUri(execution, serviceInstanceId, arId)
586             List<AAIResourceUri> policyUriList = getRelationshipUriListInAai(execution, arUri,
587                     AAIFluentTypeBuilder.Types.NETWORK_POLICY, exceptionOnErr)
588             for (AAIResourceUri policyUri : policyUriList) {
589                 Optional<NetworkPolicy> policyOpt = client.get(NetworkPolicy.class, policyUri)
590                 if (policyOpt.isPresent()) {
591                     NetworkPolicy policy = policyOpt.get()
592                     return policy.getNetworkPolicyId()
593                 } else {
594                     String msg = String.format("ERROR: getPolicyIdFromAr: arUri=%s", policyUri)
595                     logger.error(msg)
596                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
597                 }
598             }
599         } catch (BpmnError e) {
600             if (exceptionOnErr) {
601                 throw e;
602             }
603         } catch (Exception ex) {
604             if (exceptionOnErr) {
605                 String msg = String.format("ERROR: getPolicyIdFromAr: %s", ex.getMessage())
606                 logger.error(msg)
607                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
608             }
609         }
610
611         return res
612     }
613
614
615     List<AAIResourceUri> getRelationshipUriListInAai(DelegateExecution execution,
616                                                      AAIResourceUri uri,
617                                                      Object info,
618                                                      boolean exceptionOnErr) {
619         AAIResourcesClient client = new AAIResourcesClient()
620         AAIResultWrapper wrapper = client.get(uri);
621         Optional<Relationships> relationships = wrapper.getRelationships()
622         if (relationships.isPresent()) {
623             return relationships.get().getRelatedUris(info)
624         } else {
625             if (exceptionOnErr) {
626                 String msg = "ERROR: getRelationshipUriListInAai: No relationship found"
627                 logger.error(msg)
628                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
629             }
630         }
631
632         return null
633     }
634
635     List<String> getLogicalLinkNamesFromAr(DelegateExecution execution, String serviceInstanceId,
636                                            String arId, boolean exceptionOnErr) {
637         List<String> res = new ArrayList<>()
638         try {
639             AAIResourcesClient client = new AAIResourcesClient()
640
641             AAIResourceUri arUri = buildAllottedResourceUri(execution, serviceInstanceId, arId)
642             List<AAIResourceUri> logicalLinkUriList = getRelationshipUriListInAai(execution, arUri,
643                     AAIFluentTypeBuilder.Types.LOGICAL_LINK, exceptionOnErr)
644             for (AAIResourceUri logicalLinkUri : logicalLinkUriList) {
645                 Optional<LogicalLink> logicalLinkOpt = client.get(LogicalLink.class, logicalLinkUri)
646                 if (logicalLinkOpt.isPresent()) {
647                     LogicalLink logicalLink = logicalLinkOpt.get()
648                     res.add(logicalLink.getLinkName())
649                 } else {
650                     String msg = String.format("ERROR: getLogicalLinkNamesFromAr: logicalLinkUri=%s", logicalLinkUri)
651                     logger.error(msg)
652                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
653                 }
654             }
655         } catch (BpmnError e) {
656             if (exceptionOnErr) {
657                 throw e;
658             }
659         } catch (Exception ex) {
660             if (exceptionOnErr) {
661                 String msg = String.format("ERROR: getLogicalLinkNamesFromAr: %s", ex.getMessage())
662                 logger.error(msg)
663                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
664             }
665         }
666
667         return res
668     }
669 }