fcb3b5232249e072537813c93166d945ba07b078
[so.git] /
1 package org.onap.so.bpmn.infrastructure.scripts
2
3 import com.fasterxml.jackson.databind.ObjectMapper
4 import org.camunda.bpm.engine.delegate.DelegateExecution
5 import org.onap.aai.domain.yang.CloudRegion
6 import org.onap.aai.domain.yang.Customer
7 import org.onap.aai.domain.yang.ModelVer
8 import org.onap.aai.domain.yang.OwningEntities
9 import org.onap.aai.domain.yang.ServiceSubscription
10 import org.onap.aai.domain.yang.SliceProfile
11 import org.onap.aai.domain.yang.GenericVnf
12 import org.onap.aai.domain.yang.ServiceInstance
13 import org.onap.aai.domain.yang.Tenant
14 import org.onap.aai.domain.yang.VfModule
15 import org.onap.aaiclient.client.aai.AAIObjectType
16 import org.onap.aaiclient.client.aai.AAIResourcesClient
17 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
18 import org.onap.aaiclient.client.aai.entities.Relationships
19 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
20 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
21 import org.onap.logging.filter.base.ONAPComponents
22 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
23 import org.onap.so.bpmn.common.scripts.ExceptionUtil
24 import org.onap.so.bpmn.common.scripts.MsoUtils
25 import org.onap.so.bpmn.common.scripts.RequestDBUtil
26 import org.onap.so.bpmn.core.UrnPropertiesReader
27 import org.onap.so.bpmn.core.json.JsonUtils
28 import org.onap.so.client.HttpClient
29 import org.onap.so.client.HttpClientFactory
30 import org.onap.so.db.request.beans.OperationStatus
31 import org.onap.so.requestsdb.RequestsDbConstant
32 import org.onap.so.serviceinstancebeans.CloudConfiguration
33 import org.onap.so.serviceinstancebeans.ModelInfo
34 import org.onap.so.serviceinstancebeans.ModelType
35 import org.onap.so.serviceinstancebeans.OwningEntity
36 import org.onap.so.serviceinstancebeans.Project
37 import org.onap.so.serviceinstancebeans.RequestDetails
38 import org.onap.so.serviceinstancebeans.RequestInfo
39 import org.onap.so.serviceinstancebeans.RequestParameters
40 import org.onap.so.serviceinstancebeans.Resources
41 import org.onap.so.serviceinstancebeans.Service
42 import org.onap.so.serviceinstancebeans.SubscriberInfo
43 import org.onap.so.serviceinstancebeans.VfModules
44 import org.onap.so.serviceinstancebeans.Vnfs
45 import org.slf4j.Logger
46 import org.slf4j.LoggerFactory
47
48 import javax.ws.rs.core.Response
49
50 class DoDeallocateCoreNSSI extends AbstractServiceTaskProcessor {
51     private final String PREFIX ="DoDeallocateCoreNSSI"
52
53     private ExceptionUtil exceptionUtil = new ExceptionUtil()
54     private RequestDBUtil requestDBUtil = new RequestDBUtil()
55     private MsoUtils utils = new MsoUtils()
56     private JsonUtils jsonUtil = new JsonUtils()
57
58     private static final Logger LOGGER = LoggerFactory.getLogger( DoDeallocateCoreNSSI.class)
59
60     @Override
61     void preProcessRequest(DelegateExecution execution) {
62         LOGGER.trace("${PREFIX} Start preProcessRequest")
63
64         def currentNSSI = execution.getVariable("currentNSSI")
65         if (!currentNSSI) {
66             String msg = "currentNSSI is null"
67             LOGGER.error(msg)
68             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
69         }
70
71         LOGGER.trace("***** ${PREFIX} Exit preProcessRequest")
72     }
73
74
75     /**
76      * Queries OOF for NSSI termination
77      * @param execution
78      */
79     void executeTerminateNSSIQuery(DelegateExecution execution) {
80         // TO DO: Unit test
81         LOGGER.trace("${PREFIX} Start executeTerminateNSSIQuery")
82
83         def currentNSSI = execution.getVariable("currentNSSI")
84
85         String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
86
87         //Prepare auth for OOF
88         def authHeader = ""
89         String basicAuth = UrnPropertiesReader.getVariable("mso.oof.auth", execution)
90         String msokey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
91
92         String basicAuthValue = utils.encrypt(basicAuth, msokey)
93         if (basicAuthValue != null) {
94             logger.debug( "Obtained BasicAuth username and password for OOF: " + basicAuthValue)
95             try {
96                 authHeader = utils.getBasicAuth(basicAuthValue, msokey)
97                 execution.setVariable("BasicAuthHeaderValue", authHeader)
98             } catch (Exception ex) {
99                 logger.debug( "Unable to encode username and password string: " + ex)
100                 exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - Unable to " +
101                         "encode username and password string")
102             }
103         } else {
104             logger.debug( "Unable to obtain BasicAuth - BasicAuth value null")
105             exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
106                     "value null")
107         }
108
109         //Prepare send request to OOF
110         String oofRequest = buildOOFRequest(execution)
111
112         URL url = new URL(urlString+"/api/oof/terminate/nxi/v1")
113         HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.OOF)
114         httpClient.addAdditionalHeader("Authorization", authHeader)
115         httpClient.addAdditionalHeader("Accept", "application/json")
116         httpClient.addAdditionalHeader("Content-Type", "application/json")
117
118         Response httpResponse = httpClient.post(oofRequest)
119
120         int responseCode = httpResponse.getStatus()
121         logger.debug("OOF sync response code is: " + responseCode)
122
123         if(responseCode != 202){ // Accepted
124             exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
125         }
126
127         if(httpResponse.hasEntity()){
128             String OOFResponse = httpResponse.readEntity(Boolean.class)
129             String isTerminateNSSI = jsonUtil.getJsonValue(OOFResponse, "terminateResponse")
130
131             execution.setVariable("isTerminateNSSI", Boolean.parseBoolean(isTerminateNSSI))
132         }
133
134         LOGGER.trace("${PREFIX} Exit executeTerminateNSSIQuery")
135     }
136
137
138     /**
139      * Builds OOF request
140      * @param execution
141      * @return
142      */
143     private String buildOOFRequest(DelegateExecution execution) {
144
145         def currentNSSI = execution.getVariable("currentNSSI")
146
147         String nssiId = currentNSSI['nssiId']
148         String requestId = execution.getVariable("mso-request-id")
149
150         String request =    "{\n" +
151                             "  \"type\": \"NSSI\",\n" +
152                             "  \"NxIId\": \"${nssiId}\",\n" +
153                             "  \"requestInfo\": {\n" +
154                             "    \"transactionId\": \"${requestId}\",\n" +
155                             "    \"requestId\": \"${requestId}\",\n" +
156                             "    \"sourceId\": \"so\",\n" +
157                             "    }\n" +
158                             "}"
159
160         return request
161     }
162
163
164
165     /**
166      * Queries Network Service Instance in AAI
167      * @param execution
168      */
169     void getNetworkServiceInstance(DelegateExecution execution) {
170         LOGGER.trace("${PREFIX} Start getNetworkServiceInstance")
171
172         AAIResourcesClient client = getAAIClient()
173
174         def currentNSSI = execution.getVariable("currentNSSI")
175
176         String globalSubscriberId = currentNSSI['globalSubscriberId']
177         String serviceType = currentNSSI['serviceType']
178         String nssiId = currentNSSI['nssiId']
179
180         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId) //AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nssiId)
181         Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, nssiUri)
182
183         if (nssiOpt.isPresent()) {
184             ServiceInstance nssi = nssiOpt.get()
185             currentNSSI['nssi'] = nssi
186
187             ServiceInstance networkServiceInstance = handleNetworkInstance(execution, nssiId, nssiUri, client)
188             currentNSSI['networkServiceInstance'] = networkServiceInstance
189         }
190         else {
191             String msg = String.format("NSSI %s not found in AAI", nssiId)
192             LOGGER.error(msg)
193             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
194         }
195
196         LOGGER.trace("${PREFIX} Exit getNetworkServiceInstance")
197     }
198
199
200     /**
201      * Handles Network Service
202      * @param nssiId
203      * @param nssiUri
204      * @param client
205      * @return Network Service Instance
206      */
207     private ServiceInstance handleNetworkInstance(DelegateExecution execution, String nssiId, AAIResourceUri nssiUri, AAIResourcesClient client ) {
208         ServiceInstance networkServiceInstance = null
209
210         def currentNSSI = execution.getVariable("currentNSSI")
211
212         AAIResultWrapper wrapper = client.get(nssiUri)
213         Optional<Relationships> relationships = wrapper.getRelationships()
214
215         if (relationships.isPresent()) {
216             for (AAIResourceUri networkServiceInstanceUri : relationships.get().getRelatedAAIUris(AAIObjectType.SERVICE_INSTANCE)) {
217                 Optional<ServiceInstance> networkServiceInstanceOpt = client.get(ServiceInstance.class, networkServiceInstanceUri)
218                 if (networkServiceInstanceOpt.isPresent()) {
219                     networkServiceInstance = networkServiceInstanceOpt.get()
220
221                     if (networkServiceInstance.getServiceRole().equals("Network Service")) { // Network Service role
222                         currentNSSI['networkServiceInstanceUri'] = networkServiceInstanceUri
223                         break
224                     }
225                 }
226                 else {
227                     String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
228                     LOGGER.error(msg)
229                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
230                 }
231             }
232         }
233         else {
234             String msg = String.format("No relationship presented for NSSI %s in AAI", nssiId)
235             LOGGER.error(msg)
236             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
237         }
238
239         if(networkServiceInstance == null) {
240             String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
241             LOGGER.error(msg)
242             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
243         }
244
245         return networkServiceInstance
246     }
247
248
249     /**
250      * Invokes deleteServiceOrder external API
251      * @param execution
252      */
253     void deleteServiceOrder(DelegateExecution execution) {
254         // TO DO: Unit test
255         LOGGER.trace("${PREFIX} Start deleteServiceOrder")
256
257         def currentNSSI = execution.getVariable("currentNSSI")
258
259         try {
260             //url:/nbi/api/v4/serviceOrder/"
261             def nbiEndpointUrl = UrnPropertiesReader.getVariable("nbi.endpoint.url", execution) // ???
262
263             ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
264
265             String url = String.format("${nbiEndpointUrl}/api/v4/serviceOrder/%s", networkServiceInstance.getServiceInstanceId()) // Service Order ID = Network Service Instance ID ???
266
267             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
268             String basicAuth =  UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
269             String basicAuthValue = utils.encrypt(basicAuth, msoKey)
270             String encodeString = utils.getBasicAuth(basicAuthValue, msoKey)
271
272             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
273             httpClient.addAdditionalHeader("Authorization", encodeString)
274             httpClient.addAdditionalHeader("Accept", "application/json")
275             Response httpResponse = httpClient.delete() // check http code ???
276         } catch (any) {
277             String msg = "Exception in DoDeallocateCoreNSSI.deleteServiceOrder. " + any.getCause()
278             LOGGER.error(msg)
279             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
280         }
281
282         LOGGER.trace("${PREFIX} Exit deleteServiceOrder")
283     }
284
285
286     /**
287      * Queries constitute VNF from Network Service Instance
288      * @param execution
289      */
290     void getConstituteVNFFromNetworkServiceInst(DelegateExecution execution) {
291         LOGGER.trace("${PREFIX} Start getConstituteVNFFromNetworkServiceInst")
292
293         def currentNSSI = execution.getVariable("currentNSSI")
294
295         AAIResourcesClient client = getAAIClient()
296
297         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
298         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri);
299         Optional<Relationships> relationships = wrapper.getRelationships()
300         if (relationships.isPresent()) {
301             for (AAIResourceUri constituteVnfUri : relationships.get().getRelatedAAIUris(AAIObjectType.GENERIC_VNF)) {  // ???
302                 execution.setVariable("constituteVnfUri", constituteVnfUri)
303                 Optional<GenericVnf> constituteVnfOpt = client.get(GenericVnf.class, constituteVnfUri)
304                 if(constituteVnfOpt.isPresent()) {
305                     GenericVnf constituteVnf = constituteVnfOpt.get()
306                     execution.setVariable("constituteVnf", constituteVnf)
307                 }
308                 else {
309                     String msg = String.format("No constitute VNF found for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
310                     LOGGER.error(msg)
311                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
312                 }
313
314                 break  // Should be only one constitute VNF
315             }
316         }
317         else {
318             String msg = String.format("No relationship presented for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
319             LOGGER.error(msg)
320             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
321         }
322
323         LOGGER.trace("${PREFIX} Exit getConstituteVNFFromNetworkServiceInst")
324
325     }
326
327
328     /**
329      * Retrieves NSSI associated profiles from AAI
330      * @param execution
331      */
332     void getNSSIAssociatedProfiles(DelegateExecution execution) {
333         LOGGER.trace("${PREFIX} Start getNSSIAssociatedProfiles")
334
335         def currentNSSI = execution.getVariable("currentNSSI")
336
337         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
338
339         List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
340
341         if(associatedProfiles.isEmpty()) {
342             String msg = String.format("No associated profiles found for NSSI %s in AAI", nssi.getServiceInstanceId())
343             LOGGER.error(msg)
344             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
345         }
346         else {
347             execution.setVariable("associatedProfiles", associatedProfiles)
348         }
349
350         LOGGER.trace("${PREFIX} Exit getNSSIAssociatedProfiles")
351     }
352
353
354     /**
355      * Calculates a final list of S-NSSAI
356      * @param execution
357      */
358     void calculateSNSSAI(DelegateExecution execution) {
359         LOGGER.trace("${PREFIX} Start calculateSNSSAI")
360
361         List<SliceProfile> associatedProfiles = (List<SliceProfile>)execution.getVariable("associatedProfiles")
362
363         def currentNSSI = execution.getVariable("currentNSSI")
364
365         String currentSNSSAI = currentNSSI['S-NSSAI']
366
367         List<String> snssais = new ArrayList<>()
368
369         for(SliceProfile associatedProfile:associatedProfiles) {
370             if(!associatedProfile.getSNssai().equals(currentNSSI)) { // not current S-NSSAI
371                 snssais.add(associatedProfile.getSNssai())
372             }
373         }
374
375         execution.setVariable("S-NSSAIs", snssais)
376
377         LOGGER.trace("${PREFIX} Exit calculateSNSSAI")
378     }
379
380
381     /**
382      * Invoke PUT Service Instance API
383      * @param execution
384      */
385     void invokePUTServiceInstance(DelegateExecution execution) {
386         LOGGER.trace("${PREFIX} Start invokePUTServiceInstance")
387
388         def currentNSSI = execution.getVariable("currentNSSI")
389
390         try {
391             //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}/vnfs/{vnfId}"
392             def nsmfЕndpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
393
394             ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
395
396             GenericVnf constituteVnf = (GenericVnf)execution.getVariable("constituteVnf")
397
398             String url = String.format("${nsmfЕndpoint}/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s", networkServiceInstance.getServiceInstanceId(), constituteVnf.getVnfId()) // ???
399
400             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
401             String basicAuth =  UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
402             String basicAuthValue = utils.encrypt(basicAuth, msoKey)
403             String encodeString = utils.getBasicAuth(basicAuthValue, msoKey)
404
405             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
406             httpClient.addAdditionalHeader("Authorization", encodeString)
407             httpClient.addAdditionalHeader("Accept", "application/json")
408
409             RequestDetails requestDetails = prepareRequestDetails(execution)
410             ObjectMapper mapper = new ObjectMapper()
411             String requestDetailsStr = mapper.writeValueAsString(requestDetails)
412
413             Response httpResponse = httpClient.put(requestDetailsStr) // check http code ???
414         } catch (any) {
415             String msg = "Exception in DoDeallocateCoreNSSI.deleteServiceOrder. " + any.getCause()
416             LOGGER.error(msg)
417             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
418         }
419
420         LOGGER.trace("${PREFIX} Exit invokePUTServiceInstance")
421     }
422
423
424     /**
425      * Prepare model info
426      * @param execution
427      * @param requestDetails
428      * @return
429      */
430     private ModelInfo prepareModelInfo(DelegateExecution execution) {
431         ModelInfo modelInfo = new ModelInfo()
432
433         modelInfo.setModelType(ModelType.service)
434         modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
435
436         AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, networkServiceInstance.getModelInvariantId()) // model of Network Service Instance ???
437         Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
438
439         if (modelVerOpt.isPresent()) {
440             modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
441             modelInfo.setModelName(modelVerOpt.get().getModelName())
442             modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
443         }
444
445
446         return modelInfo
447     }
448
449
450     /**
451      * Prepares RequestDetails object
452      * @param execution
453      * @return
454      */
455     private RequestDetails prepareRequestDetails(DelegateExecution execution) {
456         RequestDetails requestDetails = new RequestDetails()
457
458         def currentNSSI = execution.getVariable("currentNSSI")
459
460         String globalSubscriberId = currentNSSI['globalSubscriberId']
461
462         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
463
464
465         AAIResourcesClient client = getAAIClient()
466
467         // Model Info
468         requestDetails.setModelInfo(prepareModelInfo(execution))
469
470         // Subscriber Info
471         SubscriberInfo subscriberInfo = new SubscriberInfo()
472         subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
473
474         Customer customer = null
475         ServiceSubscription serviceSubscription = null
476
477         AAIResourceUri networkServiceInstanceUri = currentNSSI['networkServiceInstanceUri']
478         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
479         Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
480         if(serviceSubscriptionRelationshipsOps.isPresent()) {
481             List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.SERVICE_SUBSCRIPTION)
482             if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
483                 AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
484                 Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
485                 if(serviceSubscriptionOpt.isPresent()) {
486                     serviceSubscription = serviceSubscriptionOpt.get()
487                 }
488
489                 wrapper = client.get(serviceSubscriptionUri)
490                 Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
491                 if(customerRelationshipsOps.isPresent()) {
492                     List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CUSTOMER)
493                     if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
494                         Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
495                         if(customerOpt.isPresent()) {
496                             customer = customerOpt.get()
497                             subscriberInfo.setSubscriberName(customer.getSubscriberName())
498                         }
499                     }
500                 }
501             }
502
503         }
504         requestDetails.setSubscriberInfo(subscriberInfo)
505
506         // Request Info
507         RequestInfo requestInfo = new RequestInfo()
508         requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
509
510         /* No found data to provide ???
511         requestInfo.setSource()
512         requestInfo.setSuppressRollback()
513         requestInfo.setRequestorId()
514         requestInfo.setProductFamilyId()
515         */
516
517         requestDetails.setRequestInfo(requestInfo)
518
519
520         // Request Parameters
521         RequestParameters requestParameters = new RequestParameters()
522
523         // No found data to provide ??? requestParameters.setaLaCarte()
524         requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
525
526         // User params
527         List<Map<String, Object>> userParams = new ArrayList<>()
528         // Service
529         Service service = new Service()
530         // Model Info
531         ModelInfo serviceModelInfo = new ModelInfo()
532         serviceModelInfo.setModelType(ModelType.service)
533         serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
534
535         serviceModelInfo.setModelVersionId(modelInfo.get().getModelVersionId())
536         serviceModelInfo.setModelName(modelInfo.get().getModelName())
537         serviceModelInfo.setModelVersion(modelInfo.get().getModelVersion())
538
539         service.setModelInfo(serviceModelInfo)
540
541         // Resources
542         Resources resources = new Resources()
543
544         CloudRegion cloudRegion = null
545         AAIResourceUri cloudRegionRelatedAAIUri = null
546         // VNFs
547         List<Vnfs> vnfs = new ArrayList<>()
548         // VNF
549         Vnfs vnf = new Vnfs()
550
551         // Cloud configuration
552         CloudConfiguration cloudConfiguration = new CloudConfiguration()
553
554         AAIResourceUri constituteVnfUri = (AAIResourceUri)execution.getVariable("constituteVnfUri")
555         wrapper = client.get(constituteVnfUri)
556         Optional<Relationships> constituteVnfOps = wrapper.getRelationships()
557         if(constituteVnfOps.isPresent()) {
558             List<AAIResourceUri> cloudRegionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CLOUD_REGION)
559             if(!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
560                 cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
561                 Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
562                 if(cloudRegionrOpt.isPresent()) {
563                     cloudRegion = cloudRegionrOpt.get()
564                     cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
565                     for(Tenant tenant:cloudRegion.getTenants()) {
566                         cloudConfiguration.setTenantId(tenant.getTenantId())
567                         break // only one is required
568                     }
569
570                     cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
571                 }
572             }
573         }
574
575         vnf.setCloudConfiguration(cloudConfiguration)
576
577         // VF Modules
578         GenericVnf constituteVnf = execution.getVariable("constituteVnf")
579         List<VfModules> vfModuless = new ArrayList<>()
580         for(VfModule vfModule:constituteVnf.getVfModules()) {
581             VfModules vfmodules = new VfModules()
582
583             ModelInfo vfModuleModelInfo = new ModelInfo()
584             vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
585
586             AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, vfModule.getModelInvariantId()) // ???
587             Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
588
589             if (vfModuleModelVerOpt.isPresent()) {
590                 vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
591                 vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
592                 vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
593
594                 // No model customization ID
595             }
596             vfmodules.setModelInfo(vfModuleModelInfo)
597
598             vfmodules.setInstanceName(vfModule.getVfModuleName()) // ???
599
600             vfModuless.add(vfmodules)
601         }
602         vnf.setVfModules(vfModuless)
603
604         // Model Info
605         ModelInfo vnfModelInfo = new ModelInfo()
606         vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
607         AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, constituteVnf.getModelInvariantId()) // ???
608         Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
609
610         if (vnfModelVerOpt.isPresent()) {
611             vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
612             vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
613             vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
614
615             // No model customization ID
616             // No model instance name
617         }
618
619         vnf.setModelInfo(vnfModelInfo)
620
621         // Instance name
622         vnf.setInstanceName(constituteVnf.getVnfInstanceId())
623
624         // Instance params
625         List<Map<String, Object>> instanceParams = new ArrayList<>()
626         Map<String, Object> supporrtedNSSAIMap = new HashMap<>()
627
628         // Supported S-NSSAI
629         List<String> snssais = ( List<String>)execution.getVariable("S-NSSAIs")
630         supporrtedNSSAIMap.put("supporrtedNSSAI", snssais) // remaining S-NSSAIs ??? there is no status for each s-nssai
631         instanceParams.add(supporrtedNSSAIMap)
632
633         // No other instance params, e.g. config-type
634
635         vnf.setInstanceParams(instanceParams)
636
637         // No platform data
638
639         vnfs.add(vnf)
640         resources.setVnfs(vnfs)
641
642         service.setResources(resources)
643
644         Map<String, Object> serviceMap = new HashMap<>()
645         serviceMap.put("service", service)
646         userParams.add(serviceMap)
647         requestParameters.setUserParams(userParams)
648
649         // No other user params
650
651         requestDetails.setRequestParameters(requestParameters)
652
653         // No other request params
654
655         // Cloud configuration
656         requestDetails.setCloudConfiguration(cloudConfiguration)
657
658         // Owning entity
659         OwningEntity owningEntity = new OwningEntity()
660         wrapper = client.get(networkServiceInstanceUri)
661         Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
662         if(owningEntityRelationshipsOps.isPresent()) {
663             List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.OWNING_ENTITY)
664
665             if(!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
666                 Optional<org.onap.aai.domain.yang.OwningEntity> owningEntityOpt = client.get(org.onap.aai.domain.yang.OwningEntity.class, owningEntityRelatedAAIUris.get(0)) // Many-To-One relation
667                 if(owningEntityOpt.isPresent()) {
668                     owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
669                     owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
670                     requestDetails.setOwningEntity(owningEntity)
671                 }
672             }
673         }
674
675         // Project
676         Project project = new Project()
677         if(cloudRegionRelatedAAIUri != null) {
678             wrapper = client.get(cloudRegionRelatedAAIUri)
679             Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
680             if(cloudRegionOps.isPresent()) {
681                 List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedAAIUris(AAIObjectType.PROJECT)
682                 if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
683                     Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.Project.class, projectAAIUris.get(0))
684                     if(projectOpt.isPresent()) {
685                         project.setProjectName(projectOpt.get().getProjectName())
686                     }
687                 }
688             }
689         }
690         requestDetails.setProject(project)
691
692         return requestDetails
693     }
694
695
696     /**
697      * Removes NSSI association with NSI
698      * @param execution
699      */
700     void removeNSSIAssociationWithNSI(DelegateExecution execution) {
701         LOGGER.trace("${PREFIX} Start removeNSSIAssociationWithNSI")
702
703         AAIResourcesClient client = getAAIClient()
704
705         def currentNSSI = execution.getVariable("currentNSSI")
706
707         String nssiId = currentNSSI['nssiServiceInstanceId']
708         String nsiId = currentNSSI['nsiId']
709
710         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
711         AAIResourceUri nsiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nsiId)
712
713         try {
714             getAAIClient().disconnect(nssiUri, nsiUri)
715         }catch(Exception e){
716             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while NSSI association with NSI disconnect call: " + e.getMessage())
717         }
718
719         LOGGER.trace("${PREFIX} Exit removeNSSIAssociationWithNSI")
720     }
721
722
723     /**
724      * Removes Slice Profile association with NSSI
725      * @param execution
726      */
727     void removeSPAssociationWithNSSI(DelegateExecution execution) {
728         LOGGER.trace("${PREFIX} Start removeSPAssociationWithNSSI")
729
730         AAIResourcesClient client = getAAIClient()
731
732         def currentNSSI = execution.getVariable("currentNSSI")
733
734         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
735
736         String nssiId = currentNSSI['nssiServiceInstanceId']
737         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
738
739         List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
740
741         String currentSNSSAI = currentNSSI['S-NSSAI']
742
743         associatedProfiles.removeIf({ associatedProfile -> (associatedProfile.getSNssai().equals(currentSNSSAI)) })
744
745         try {
746             getAAIClient().update(nssiUri, nssi)
747         }catch(Exception e){
748             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI update call: " + e.getMessage())
749         }
750
751         LOGGER.trace("${PREFIX} Exit removeSPAssociationWithNSSI")
752     }
753
754
755     /**
756      * Deletes Slice Profile Instance
757      * @param execution
758      */
759     void deleteSliceProfileInstance(DelegateExecution execution) {
760         LOGGER.trace("${PREFIX} Start deleteSliceProfileInstance")
761
762         AAIResourcesClient client = getAAIClient()
763
764         def currentNSSI = execution.getVariable("currentNSSI")
765
766         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
767
768         List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
769
770         String currentSNSSAI = currentNSSI['S-NSSAI']
771
772         AAIResourceUri sliceProfileUri = null
773
774         for(SliceProfile associatedProfile:associatedProfiles) {
775             if(!associatedProfile.getSNssai().equals(currentNSSI)) { // not current S-NSSAI
776                 sliceProfileUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, associatedProfile.getProfileId())
777                 break
778             }
779         }
780
781         try {
782             getAAIClient().delete(sliceProfileUri)
783         }catch(Exception e){
784             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
785         }
786
787         LOGGER.trace("${PREFIX} Exit deleteSliceProfileInstance")
788     }
789
790
791     /**
792      * Delets NSSI Service Instance
793      * @param execution
794      */
795     void deleteNSSIServiceInstance(DelegateExecution execution) {
796         LOGGER.trace("${PREFIX} Start deleteNSSIServiceInstance")
797
798         AAIResourcesClient client = getAAIClient()
799
800         def currentNSSI = execution.getVariable("currentNSSI")
801
802         String nssiId = currentNSSI['nssiServiceInstanceId']
803         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
804
805         try {
806             getAAIClient().delete(nssiUri)
807         }catch(Exception e){
808             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while NSSI Service Instance delete call: " + e.getMessage())
809         }
810
811         LOGGER.trace("${PREFIX} Exit deleteNSSIServiceInstance")
812     }
813
814
815     /**
816      * Updates operation status
817      * @param execution
818      */
819     void updateServiceOperationStatus(DelegateExecution execution) {
820         LOGGER.trace("${PREFIX} Start updateServiceOperationStatus")
821
822         def currentNSSI = execution.getVariable("currentNSSI")
823
824         OperationStatus operationStatus = new OperationStatus()
825         operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
826         operationStatus.setOperationId(currentNSSI['operationId'] as String)
827         operationStatus.setOperation(currentNSSI['operationType'] as String)
828         operationStatus.setResult(RequestsDbConstant.Status.FINISHED)
829
830         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
831
832         LOGGER.trace("${PREFIX} Exit updateServiceOperationStatus")
833     }
834
835
836     /**
837      * Returns AAI client
838      * @return AAI client
839      */
840     AAIResourcesClient getAAIClient() {
841         return new AAIResourcesClient()
842     }
843
844 }