49aeec8ee303eca70c4ea45f69bd61efcf6df6b9
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020  TIM
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 com.fasterxml.jackson.databind.ObjectMapper
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.aai.domain.yang.CloudRegion
26 import org.onap.aai.domain.yang.Customer
27 import org.onap.aai.domain.yang.ModelVer
28 import org.onap.aai.domain.yang.OwningEntities
29 import org.onap.aai.domain.yang.ServiceSubscription
30 import org.onap.aai.domain.yang.SliceProfile
31 import org.onap.aai.domain.yang.GenericVnf
32 import org.onap.aai.domain.yang.ServiceInstance
33 import org.onap.aai.domain.yang.Tenant
34 import org.onap.aai.domain.yang.VfModule
35 import org.onap.aaiclient.client.aai.AAIClient
36 import org.onap.aaiclient.client.aai.AAIObjectType
37 import org.onap.aaiclient.client.aai.AAIResourcesClient
38 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
39 import org.onap.aaiclient.client.aai.entities.Relationships
40 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
41 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
42 import org.onap.logging.filter.base.ONAPComponents
43 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
44 import org.onap.so.bpmn.common.scripts.ExceptionUtil
45 import org.onap.so.bpmn.common.scripts.MsoUtils
46 import org.onap.so.bpmn.common.scripts.RequestDBUtil
47 import org.onap.so.bpmn.core.UrnPropertiesReader
48 import org.onap.so.bpmn.core.json.JsonUtils
49 import org.onap.so.client.HttpClient
50 import org.onap.so.client.HttpClientFactory
51 import org.onap.so.db.request.beans.OperationStatus
52 import org.onap.so.requestsdb.RequestsDbConstant
53 import org.onap.so.serviceinstancebeans.CloudConfiguration
54 import org.onap.so.serviceinstancebeans.LineOfBusiness
55 import org.onap.so.serviceinstancebeans.ModelInfo
56 import org.onap.so.serviceinstancebeans.ModelType
57 import org.onap.so.serviceinstancebeans.OwningEntity
58 import org.onap.so.serviceinstancebeans.Project
59 import org.onap.so.serviceinstancebeans.RequestDetails
60 import org.onap.so.serviceinstancebeans.RequestInfo
61 import org.onap.so.serviceinstancebeans.RequestParameters
62 import org.onap.so.serviceinstancebeans.Resources
63 import org.onap.so.serviceinstancebeans.Service
64 import org.onap.so.serviceinstancebeans.SubscriberInfo
65 import org.onap.so.serviceinstancebeans.VfModules
66 import org.onap.so.serviceinstancebeans.Vnfs
67 import org.slf4j.Logger
68 import org.slf4j.LoggerFactory
69
70 import javax.ws.rs.core.Response
71
72 class DoDeallocateCoreNSSI extends AbstractServiceTaskProcessor {
73     private final String PREFIX ="DoDeallocateCoreNSSI"
74
75     private ExceptionUtil exceptionUtil = new ExceptionUtil()
76     private RequestDBUtil requestDBUtil = new RequestDBUtil()
77     private MsoUtils utils = new MsoUtils()
78     private JsonUtils jsonUtil = new JsonUtils()
79
80     private static final Logger LOGGER = LoggerFactory.getLogger( DoDeallocateCoreNSSI.class)
81
82     @Override
83     void preProcessRequest(DelegateExecution execution) {
84         LOGGER.trace("${PREFIX} Start preProcessRequest")
85
86         def currentNSSI = execution.getVariable("currentNSSI")
87         if (!currentNSSI) {
88             String msg = "currentNSSI is null"
89             LOGGER.error(msg)
90             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
91         }
92
93         LOGGER.trace("***** ${PREFIX} Exit preProcessRequest")
94     }
95
96
97     /**
98      * Queries OOF for NSSI termination
99      * @param execution
100      */
101     void executeTerminateNSSIQuery(DelegateExecution execution) {
102         // TO DO: Unit test
103         LOGGER.trace("${PREFIX} Start executeTerminateNSSIQuery")
104
105         def currentNSSI = execution.getVariable("currentNSSI")
106
107         String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
108
109         //Prepare auth for OOF
110         def authHeader = ""
111         String basicAuth = UrnPropertiesReader.getVariable("mso.oof.auth", execution)
112         String msokey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
113
114         String basicAuthValue = encryptBasicAuth(basicAuth, msokey)
115         if (basicAuthValue != null) {
116             String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msokey)
117             String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
118             if(errorCode == null || errorCode.isEmpty()) { // No error
119                 authHeader = responseAuthHeader
120             }
121             else {
122                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
123             }
124         } else {
125             LOGGER.error( "Unable to obtain BasicAuth - BasicAuth value null")
126             exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
127                     "value null")
128         }
129
130         //Prepare send request to OOF
131         String oofRequest = buildOOFRequest(execution)
132
133         String callOOFResponse = callOOF(urlString, authHeader, oofRequest)
134         String errorCode = jsonUtil.getJsonValue(callOOFResponse, "errorCode")
135         if(errorCode == null || errorCode.isEmpty()) { // No error
136             String oofResponse = callOOFResponse
137             String isTerminateNSSI = jsonUtil.getJsonValue(oofResponse, "terminateResponse")
138
139             execution.setVariable("isTerminateNSSI", Boolean.parseBoolean(isTerminateNSSI))
140         }
141         else {
142             LOGGER.error(jsonUtil.getJsonValue(callOOFResponse, "errorMessage"))
143             exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callOOFResponse, "errorMessage"))
144         }
145
146
147         LOGGER.trace("${PREFIX} Exit executeTerminateNSSIQuery")
148     }
149
150
151     /**
152      * Executes sync call to OOF
153      * @return OOF response
154      */
155     String callOOF(String urlString, String authHeader, String oofRequest) {
156         String errorCode = ""
157         String errorMessage = ""
158         String response = ""
159
160         try {
161             URL url = new URL(urlString + "/api/oof/terminate/nxi/v1")
162             HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.OOF)
163             httpClient.addAdditionalHeader("Authorization", authHeader)
164             httpClient.addAdditionalHeader("Accept", "application/json")
165             httpClient.addAdditionalHeader("Content-Type", "application/json")
166
167             Response httpResponse = httpClient.post(oofRequest)
168
169             int responseCode = httpResponse.getStatus()
170             LOGGER.debug("OOF sync response code is: " + responseCode)
171
172             if (responseCode != 202) { // Accepted
173                 errorCode = responseCode
174                 errorMessage = "Received a Bad Sync Response from OOF."
175
176                 response =  "{\n" +
177                         " \"errorCode\": \"${errorCode}\",\n" +
178                         " \"errorMessage\": \"${errorMessage}\"\n" +
179                         "}"
180                 //exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
181             }
182
183             if (httpResponse.hasEntity()) {
184                 response = httpResponse.readEntity(String.class)
185             }
186             else {
187                 errorCode = 500
188                 errorMessage = "No response received from OOF."
189
190                 response =  "{\n" +
191                         " \"errorCode\": \"${errorCode}\",\n" +
192                         " \"errorMessage\": \"${errorMessage}\"\n" +
193                         "}"
194             }
195         }
196         catch(Exception e) {
197             errorCode = 400
198             errorMessage = e.getMessage()
199
200             response =  "{\n" +
201                     " \"errorCode\": \"${errorCode}\",\n" +
202                     " \"errorMessage\": \"${errorMessage}\"\n" +
203                     "}"
204         }
205
206
207         return response
208     }
209
210
211     String encryptBasicAuth(String basicAuth, String msoKey) {
212         return utils.encrypt(basicAuth, msoKey)
213     }
214
215
216     String getAuthHeader(DelegateExecution execution, String basicAuthValue, String msokey) {
217         String response = ""
218         String errorCode = ""
219         String errorMessage = ""
220
221         LOGGER.debug("Obtained BasicAuth username and password for OOF: " + basicAuthValue)
222         try {
223             response = utils.getBasicAuth(basicAuthValue, msokey)
224         } catch (Exception ex) {
225             LOGGER.error("Unable to encode username and password string: ", ex)
226
227             errorCode = "401"
228             errorMessage = "Internal Error - Unable to encode username and password string"
229
230             response =  "{\n" +
231                     " \"errorCode\": \"${errorCode}\",\n" +
232                     " \"errorMessage\": \"${errorMessage}\"\n" +
233                     "}"
234         }
235
236         return response
237     }
238
239
240
241     /**
242      * Builds OOF request
243      * @param execution
244      * @return
245      */
246     private String buildOOFRequest(DelegateExecution execution) {
247
248         def currentNSSI = execution.getVariable("currentNSSI")
249
250         String nssiId = currentNSSI['nssiId']
251         String requestId = execution.getVariable("mso-request-id")
252
253         String request =    "{\n" +
254                             "  \"type\": \"NSSI\",\n" +
255                             "  \"NxIId\": \"${nssiId}\",\n" +
256                             "  \"requestInfo\": {\n" +
257                             "    \"transactionId\": \"${requestId}\",\n" +
258                             "    \"requestId\": \"${requestId}\",\n" +
259                             "    \"sourceId\": \"so\",\n" +
260                             "    }\n" +
261                             "}"
262
263         return request
264     }
265
266
267
268     /**
269      * Queries Network Service Instance in AAI
270      * @param execution
271      */
272     void getNetworkServiceInstance(DelegateExecution execution) {
273         LOGGER.trace("${PREFIX} Start getNetworkServiceInstance")
274
275         AAIResourcesClient client = getAAIClient()
276
277         def currentNSSI = execution.getVariable("currentNSSI")
278
279         String globalSubscriberId = currentNSSI['globalSubscriberId']
280         String serviceType = currentNSSI['serviceType']
281         String nssiId = currentNSSI['nssiId']
282
283         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
284         Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, nssiUri)
285
286         if (nssiOpt.isPresent()) {
287             ServiceInstance nssi = nssiOpt.get()
288             currentNSSI['nssi'] = nssi
289
290             ServiceInstance networkServiceInstance = handleNetworkInstance(execution, nssiId, nssiUri, client)
291             currentNSSI['networkServiceInstance'] = networkServiceInstance
292         }
293         else {
294             String msg = String.format("NSSI %s not found in AAI", nssiId)
295             LOGGER.error(msg)
296             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
297         }
298
299         LOGGER.trace("${PREFIX} Exit getNetworkServiceInstance")
300     }
301
302
303     /**
304      * Handles Network Service
305      * @param nssiId
306      * @param nssiUri
307      * @param client
308      * @return Network Service Instance
309      */
310     private ServiceInstance handleNetworkInstance(DelegateExecution execution, String nssiId, AAIResourceUri nssiUri, AAIResourcesClient client ) {
311         ServiceInstance networkServiceInstance = null
312
313         def currentNSSI = execution.getVariable("currentNSSI")
314
315         AAIResultWrapper wrapper = client.get(nssiUri)
316         Optional<Relationships> relationships = wrapper.getRelationships()
317
318         if (relationships.isPresent()) {
319             for (AAIResourceUri networkServiceInstanceUri : relationships.get().getRelatedAAIUris(AAIObjectType.SERVICE_INSTANCE)) {
320                 Optional<ServiceInstance> networkServiceInstanceOpt = client.get(ServiceInstance.class, networkServiceInstanceUri)
321                 if (networkServiceInstanceOpt.isPresent()) {
322                     networkServiceInstance = networkServiceInstanceOpt.get()
323
324                     if (networkServiceInstance.getServiceRole().equals("Network Service")) { // Network Service role
325                         currentNSSI['networkServiceInstanceUri'] = networkServiceInstanceUri
326                         break
327                     }
328                 }
329                 else {
330                     String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
331                     LOGGER.error(msg)
332                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
333                 }
334             }
335         }
336         else {
337             String msg = String.format("No relationship presented for NSSI %s in AAI", nssiId)
338             LOGGER.error(msg)
339             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
340         }
341
342         if(networkServiceInstance == null) {
343             String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
344             LOGGER.error(msg)
345             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
346         }
347
348         return networkServiceInstance
349     }
350
351
352     /**
353      * Invokes deleteServiceOrder external API
354      * @param execution
355      */
356     void deleteServiceOrder(DelegateExecution execution) {
357         LOGGER.trace("${PREFIX} Start deleteServiceOrder")
358
359         def currentNSSI = execution.getVariable("currentNSSI")
360
361         try {
362             //url:/nbi/api/v4/serviceOrder/"
363             def nbiEndpointUrl = UrnPropertiesReader.getVariable("nbi.endpoint.url", execution)
364
365             ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
366
367             String url = String.format("${nbiEndpointUrl}/api/v4/serviceOrder/%s", networkServiceInstance.getServiceInstanceId()) // Service Order ID = Network Service Instance ID
368
369             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
370             String basicAuth =  UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
371
372             String basicAuthValue = encryptBasicAuth(basicAuth, msoKey)
373             def authHeader = ""
374             if (basicAuthValue != null) {
375                 String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey)
376                 String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
377                 if(errorCode == null || errorCode.isEmpty()) { // No error
378                     authHeader = responseAuthHeader
379                 }
380                 else {
381                     exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
382                 }
383             } else {
384                 LOGGER.error( "Unable to obtain BasicAuth - BasicAuth value null")
385                 exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
386                         "value null")
387             }
388
389             String callDeleteServiceOrderResponse = callDeleteServiceOrder(execution, url, authHeader)
390             String errorCode = jsonUtil.getJsonValue(callDeleteServiceOrderResponse, "errorCode")
391             String deleteServcieResponse = ""
392
393             if(errorCode == null || errorCode.isEmpty()) { // No error
394                 deleteServcieResponse = callDeleteServiceOrderResponse // check the response ???
395             }
396             else {
397                 LOGGER.error(jsonUtil.getJsonValue(callDeleteServiceOrderResponse, "errorMessage"))
398                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callDeleteServiceOrderResponse, "errorMessage"))
399             }
400         } catch (any) {
401             String msg = "Exception in DoDeallocateCoreNSSI.deleteServiceOrder. " + any.getCause()
402             LOGGER.error(msg)
403             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
404         }
405
406         LOGGER.trace("${PREFIX} Exit deleteServiceOrder")
407     }
408
409
410     String callDeleteServiceOrder(DelegateExecution execution, String urlString, String authHeader) {
411         String errorCode = ""
412         String errorMessage = ""
413         String response = ""
414
415         try {
416             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(urlString), ONAPComponents.EXTERNAL)
417             httpClient.addAdditionalHeader("Authorization", authHeader)
418             httpClient.addAdditionalHeader("Accept", "application/json")
419             Response httpResponse = httpClient.delete()
420
421             if (httpResponse.hasEntity()) {
422                 response = httpResponse.readEntity(String.class)
423             }
424             else {
425                 errorCode = 500
426                 errorMessage = "No response received."
427
428                 response =  "{\n" +
429                         " \"errorCode\": \"${errorCode}\",\n" +
430                         " \"errorMessage\": \"${errorMessage}\"\n" +
431                         "}"
432             }
433         }
434         catch (any) {
435             String msg = "Exception in DoDeallocateCoreNSSI.deleteServiceOrder. " + any.getCause()
436
437             response =  "{\n" +
438                     " \"errorCode\": \"7000\",\n" +
439                     " \"errorMessage\": \"${msg}\"\n" +
440                     "}"
441         }
442
443         return response
444     }
445
446
447     /**
448      * Queries constitute VNF from Network Service Instance
449      * @param execution
450      */
451     void getConstituteVNFFromNetworkServiceInst(DelegateExecution execution) {
452         LOGGER.trace("${PREFIX} Start getConstituteVNFFromNetworkServiceInst")
453
454         def currentNSSI = execution.getVariable("currentNSSI")
455
456         AAIResourcesClient client = getAAIClient()
457
458         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
459         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri);
460         Optional<Relationships> relationships = wrapper.getRelationships()
461         if (relationships.isPresent()) {
462             for (AAIResourceUri constituteVnfUri : relationships.get().getRelatedAAIUris(AAIObjectType.GENERIC_VNF)) {
463                 currentNSSI['constituteVnfUri'] = constituteVnfUri
464                 Optional<GenericVnf> constituteVnfOpt = client.get(GenericVnf.class, constituteVnfUri)
465                 if(constituteVnfOpt.isPresent()) {
466                     GenericVnf constituteVnf = constituteVnfOpt.get()
467                     currentNSSI['constituteVnf'] = constituteVnf
468                 }
469                 else {
470                     String msg = String.format("No constitute VNF found for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
471                     LOGGER.error(msg)
472                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
473                 }
474
475                 break  // Should be only one constitute VNF
476             }
477         }
478         else {
479             String msg = String.format("No relationship presented for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
480             LOGGER.error(msg)
481             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
482         }
483
484         LOGGER.trace("${PREFIX} Exit getConstituteVNFFromNetworkServiceInst")
485
486     }
487
488
489     /**
490      * Retrieves NSSI associated profiles from AAI
491      * @param execution
492      */
493     void getNSSIAssociatedProfiles(DelegateExecution execution) {
494         LOGGER.trace("${PREFIX} Start getNSSIAssociatedProfiles")
495
496         def currentNSSI = execution.getVariable("currentNSSI")
497
498         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
499
500         List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
501
502         if(associatedProfiles.isEmpty()) {
503             String msg = String.format("No associated profiles found for NSSI %s in AAI", nssi.getServiceInstanceId())
504             LOGGER.error(msg)
505             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
506         }
507         else {
508             currentNSSI['associatedProfiles'] =  associatedProfiles
509         }
510
511         LOGGER.trace("${PREFIX} Exit getNSSIAssociatedProfiles")
512     }
513
514
515     /**
516      * Calculates a final list of S-NSSAI
517      * @param execution
518      */
519     void calculateSNSSAI(DelegateExecution execution) {
520         LOGGER.trace("${PREFIX} Start calculateSNSSAI")
521
522         def currentNSSI = execution.getVariable("currentNSSI")
523
524         List<SliceProfile> associatedProfiles = (List<SliceProfile>)currentNSSI['associatedProfiles']
525
526         String currentSNSSAI = currentNSSI['S-NSSAI']
527
528         List<String> snssais = new ArrayList<>()
529
530         for(SliceProfile associatedProfile:associatedProfiles) {
531             if(!associatedProfile.getSNssai().equals(currentSNSSAI)) { // not current S-NSSAI
532                 snssais.add(associatedProfile.getSNssai())
533             }
534             else {
535                 currentNSSI['sliceProfileS-NSSAI'] = associatedProfile
536             }
537         }
538
539         currentNSSI['S-NSSAIs'] = snssais
540
541         LOGGER.trace("${PREFIX} Exit calculateSNSSAI")
542     }
543
544
545     /**
546      * Invoke PUT Service Instance API
547      * @param execution
548      */
549     void invokePUTServiceInstance(DelegateExecution execution) {
550         LOGGER.trace("${PREFIX} Start invokePUTServiceInstance")
551
552         def currentNSSI = execution.getVariable("currentNSSI")
553
554         try {
555             //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}/vnfs/{vnfId}"
556             def nsmfЕndpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
557
558             ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
559
560             GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
561
562             String url = String.format("${nsmfЕndpoint}/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s", networkServiceInstance.getServiceInstanceId(), constituteVnf.getVnfId())
563
564             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
565             String basicAuth =  UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
566
567             def authHeader = ""
568             String basicAuthValue = encryptBasicAuth(basicAuth, msoKey) //utils.encrypt(basicAuth, msoKey)
569             String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey) //utils.getBasicAuth(basicAuthValue, msoKey)
570
571             String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
572             if(errorCode == null || errorCode.isEmpty()) { // No error
573                 authHeader = responseAuthHeader
574             }
575             else {
576                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
577             }
578
579             def requestDetails = ""
580             String prepareRequestDetailsResponse = prepareRequestDetails(execution)
581             errorCode = jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorCode")
582             if(errorCode == null || errorCode.isEmpty()) { // No error
583                 requestDetails = prepareRequestDetailsResponse
584             }
585             else {
586                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorMessage"))
587             }
588
589             String callPUTServiceInstanceResponse = callPUTServiceInstance(url, authHeader, requestDetails)
590             String putServiceInstanceResponse = ""
591
592             if(errorCode == null || errorCode.isEmpty()) { // No error
593                 putServiceInstanceResponse = callPUTServiceInstanceResponse // check the response ???
594             }
595             else {
596                 LOGGER.error(jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
597                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
598             }
599
600         } catch (any) {
601             String msg = "Exception in DoDeallocateCoreNSSI.invokePUTServiceInstance. " + any.getCause()
602             LOGGER.error(msg)
603             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
604         }
605
606         LOGGER.trace("${PREFIX} Exit invokePUTServiceInstance")
607     }
608
609
610     String callPUTServiceInstance(String url, String authHeader, String requestDetailsStr) {
611         String errorCode = ""
612         String errorMessage = ""
613         String response
614
615         try {
616             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
617             httpClient.addAdditionalHeader("Authorization", authHeader)
618             httpClient.addAdditionalHeader("Accept", "application/json")
619
620             Response httpResponse = httpClient.put(requestDetailsStr) // check http code ???
621
622
623             if (httpResponse.hasEntity()) {
624                 response = httpResponse.readEntity(String.class)
625             }
626             else {
627                 errorCode = 500
628                 errorMessage = "No response received."
629
630                 response =  "{\n" +
631                         " \"errorCode\": \"${errorCode}\",\n" +
632                         " \"errorMessage\": \"${errorMessage}\"\n" +
633                         "}"
634             }
635         }
636         catch (any) {
637             String msg = "Exception in DoDeallocateCoreNSSI.invokePUTServiceInstance. " + any.getCause()
638             LOGGER.error(msg)
639
640             response =  "{\n" +
641                     " \"errorCode\": \"7000\",\n" +
642                     " \"errorMessage\": \"${msg}\"\n" +
643                     "}"
644
645         }
646
647         return response
648
649     }
650
651
652     /**
653      * Prepare model info
654      * @param execution
655      * @param requestDetails
656      * @return ModelInfo
657      */
658     ModelInfo prepareModelInfo(DelegateExecution execution) {
659
660         def currentNSSI = execution.getVariable("currentNSSI")
661         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
662
663         ModelInfo modelInfo = new ModelInfo()
664
665         modelInfo.setModelType(ModelType.service)
666         modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
667
668         AAIResourcesClient client = getAAIClient()
669
670         AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, networkServiceInstance.getModelInvariantId(), networkServiceInstance.getModelVersionId())
671         Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
672
673         if (modelVerOpt.isPresent()) {
674             modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
675             modelInfo.setModelName(modelVerOpt.get().getModelName())
676             modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
677         }
678
679         return modelInfo
680     }
681
682
683     /**
684      * Prepares subscriber info
685      * @param execution
686      * @return SubscriberInfo
687      */
688     SubscriberInfo prepareSubscriberInfo(DelegateExecution execution) {
689         def currentNSSI = execution.getVariable("currentNSSI")
690
691         String globalSubscriberId = currentNSSI['globalSubscriberId']
692
693         String subscriberName = currentNSSI['subscriberName']
694
695         SubscriberInfo subscriberInfo = new SubscriberInfo()
696         subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
697         subscriberInfo.setSubscriberName(subscriberName)
698
699         /*
700         AAIResourcesClient client = getAAIClient()
701
702         Customer customer = null
703
704         AAIResourceUri networkServiceInstanceUri = currentNSSI['networkServiceInstanceUri']
705         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
706         Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
707         if(serviceSubscriptionRelationshipsOps.isPresent()) {
708             List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.SERVICE_SUBSCRIPTION)
709             if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
710                 AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
711                 Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
712
713                 if(serviceSubscriptionOpt.isPresent()) {
714                     currentNSSI['serviceSubscription'] = serviceSubscriptionOpt.get()
715                 }
716
717                 wrapper = client.get(serviceSubscriptionUri)
718                 Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
719                 if(customerRelationshipsOps.isPresent()) {
720                     List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CUSTOMER)
721                     if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
722                         Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
723                         if(customerOpt.isPresent()) {
724                             customer = customerOpt.get()
725                             subscriberInfo.setSubscriberName(customer.getSubscriberName())
726                         }
727                     }
728                 }
729             }
730
731         } */
732
733         return subscriberInfo
734     }
735
736
737     /**
738      * Prepares Request Info
739      * @param execution
740      * @return RequestInfo
741      */
742     RequestInfo prepareRequestInfo(DelegateExecution execution, ServiceInstance networkServiceInstance) {
743         def currentNSSI = execution.getVariable("currentNSSI")
744
745         String serviceId = currentNSSI['serviceId']
746
747         RequestInfo requestInfo = new RequestInfo()
748
749         requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
750         requestInfo.setSource("VID")
751         requestInfo.setProductFamilyId(serviceId)
752         requestInfo.setRequestorId("NBI")
753
754         return requestInfo
755     }
756
757
758     /**
759      * Prepares Model Info
760      * @param networkServiceInstance
761      * @param modelInfo
762      * @return ModelInfo
763      */
764     ModelInfo prepareServiceModelInfo(ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
765
766         ModelInfo serviceModelInfo = new ModelInfo()
767         serviceModelInfo.setModelType(ModelType.service)
768         serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
769
770         serviceModelInfo.setModelVersionId(modelInfo.getModelVersionId())
771         serviceModelInfo.setModelName(modelInfo.getModelName())
772         serviceModelInfo.setModelVersion(modelInfo.getModelVersion())
773
774         return serviceModelInfo
775     }
776
777
778     /**
779      * Prepares Cloud configuration
780      * @param execution
781      * @return CloudConfiguration
782      */
783     CloudConfiguration prepareCloudConfiguration(DelegateExecution execution) {
784         def currentNSSI = execution.getVariable("currentNSSI")
785
786         CloudConfiguration cloudConfiguration = new CloudConfiguration()
787
788         AAIResourcesClient client = getAAIClient()
789
790         AAIResourceUri constituteVnfUri = currentNSSI['constituteVnfUri']
791         AAIResultWrapper wrapper = client.get(constituteVnfUri)
792         Optional<Relationships> cloudRegionRelationshipsOps = wrapper.getRelationships()
793
794         if(cloudRegionRelationshipsOps.isPresent()) {
795             List<AAIResourceUri> cloudRegionRelatedAAIUris = cloudRegionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CLOUD_REGION)
796             if (!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
797                 AAIResourceUri cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
798                 currentNSSI['cloudRegionRelatedAAIUri'] = cloudRegionRelatedAAIUri
799
800                 Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
801                 CloudRegion cloudRegion = null
802                 if (cloudRegionrOpt.isPresent()) {
803                     cloudRegion = cloudRegionrOpt.get()
804                     cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
805                     for (Tenant tenant : cloudRegion.getTenants().getTenant()) {
806                         cloudConfiguration.setTenantId(tenant.getTenantId())
807                         break // only one is required
808                     }
809
810                     cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
811                 }
812             }
813         }
814
815         return cloudConfiguration
816     }
817
818
819     /**
820      * Prepares a list of VF Modules
821      * @param execution
822      * @param constituteVnf
823      * @return List<VfModules>
824      */
825     List<VfModules> prepareVfModules(DelegateExecution execution, GenericVnf constituteVnf) {
826
827         AAIResourcesClient client = getAAIClient()
828
829         List<VfModules> vfModuless = new ArrayList<>()
830         for (VfModule vfModule : constituteVnf.getVfModules().getVfModule()) {
831             VfModules vfmodules = new VfModules()
832
833             ModelInfo vfModuleModelInfo = new ModelInfo()
834             vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
835             vfModuleModelInfo.setModelCustomizationId(vfModule.getModelCustomizationId())
836
837             AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, vfModule.getModelInvariantId(), vfModule.getModelVersionId())
838
839             Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
840
841             if (vfModuleModelVerOpt.isPresent()) {
842                 vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
843                 vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
844                 vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
845
846                 // No model customization ID
847             }
848             vfmodules.setModelInfo(vfModuleModelInfo)
849
850             vfmodules.setInstanceName(vfModule.getVfModuleName()) // ???
851
852             vfModuless.add(vfmodules)
853         }
854
855         return vfModuless
856     }
857
858
859     /**
860      * prepares VNF Model Info
861      * @param execution
862      * @param constituteVnf
863      * @return ModelInfo
864      */
865     ModelInfo prepareVNFModelInfo(DelegateExecution execution, GenericVnf constituteVnf) {
866         ModelInfo vnfModelInfo = new ModelInfo()
867
868         AAIResourcesClient client = getAAIClient()
869
870         vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
871         vnfModelInfo.setModelCustomizationId(constituteVnf.getModelCustomizationId())
872         vnfModelInfo.setModelInstanceName(constituteVnf.getVnfName())
873
874         AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, constituteVnf.getModelInvariantId(), constituteVnf.getModelVersionId())
875
876         Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
877
878         if (vnfModelVerOpt.isPresent()) {
879             vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
880             vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
881             vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
882
883             // No model instance name
884         }
885
886         return vnfModelInfo
887     }
888
889
890     List<Map<String, Object>> prepareInstanceParams(DelegateExecution execution) {
891         def currentNSSI = execution.getVariable("currentNSSI")
892
893         List<Map<String, Object>> instanceParams = new ArrayList<>()
894         Map<String, Object> instanceParamsMap = new HashMap<>()
895
896         // Supported S-NSSAI
897         List<String> snssais = (List<String>) currentNSSI['S-NSSAIs']
898
899         ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
900
901         String orchStatus = nssi.getOrchestrationStatus()
902
903
904         List<Map<String, String>> snssaiList = new ArrayList<>()
905
906         for(String snssai:snssais) {
907            Map<String, String> snssaisMap = new HashMap<>()
908             snssaisMap.put("snssai", snssai)
909             snssaisMap.put("status", orchStatus)
910             snssaiList.add(snssaisMap)
911         }
912
913     //    Map<String, List<Map<String, String>>> supportedNssaiDetails = new HashMap<>()
914     //    supportedNssaiDetails.put("sNssai", supportedNssaiDetails)
915
916         ObjectMapper mapper = new ObjectMapper()
917
918         String supportedNssaiDetailsStr = mapper.writeValueAsString(snssaiList)
919
920
921         instanceParamsMap.put("k8s-rb-profile-name", "default") // ???
922         instanceParamsMap.put("config-type", "day2") // ???
923         instanceParamsMap.put("supportedNssai", supportedNssaiDetailsStr)
924         instanceParams.add(instanceParamsMap)
925
926         // No other instance params, e.g. config-type
927
928         return instanceParams
929     }
930
931     /**
932      * Prepares Resources
933      * @param execution
934      * @return Resources
935      */
936     Resources prepareResources(DelegateExecution execution) {
937         def currentNSSI = execution.getVariable("currentNSSI")
938
939         Resources resources = new Resources()
940
941         // VNFs
942         List<Vnfs> vnfs = new ArrayList<>()
943         // VNF
944         Vnfs vnf = new Vnfs()
945
946         // Line of Business
947         LineOfBusiness lob = new LineOfBusiness()
948         lob.setLineOfBusinessName("VNF")
949         vnf.setLineOfBusiness(lob)
950
951         // Product family ID
952         GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
953         vnf.setProductFamilyId(constituteVnf.getServiceId())
954
955         // Cloud configuration
956         vnf.setCloudConfiguration(prepareCloudConfiguration(execution))
957
958         // VF Modules
959         vnf.setVfModules(prepareVfModules(execution, constituteVnf))
960
961         // Model Info
962         vnf.setModelInfo(prepareVNFModelInfo(execution, constituteVnf))
963
964         // Instance name
965         vnf.setInstanceName(constituteVnf.getVnfName())
966
967         // Instance params
968         vnf.setInstanceParams(prepareInstanceParams(execution))
969
970         // No platform data
971
972         vnfs.add(vnf)
973         resources.setVnfs(vnfs)
974
975         return resources
976     }
977
978
979     /**
980      * Prepare Service
981      * @return Service
982      */
983     Service prepareService(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
984         Service service = new Service()
985
986         // Model Info
987         service.setModelInfo(prepareServiceModelInfo(networkServiceInstance, modelInfo))
988
989         service.setInstanceName(networkServiceInstance.getServiceInstanceName())
990
991         // Resources
992         service.setResources(prepareResources(execution))
993
994         return service
995
996     }
997
998
999     /**
1000      * Prepares request parameters
1001      * @param execution
1002      * @return RequestParameters
1003      */
1004     RequestParameters prepareRequestParameters(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
1005         def currentNSSI = execution.getVariable("currentNSSI")
1006
1007         RequestParameters requestParameters = new RequestParameters()
1008
1009         ServiceSubscription serviceSubscription = (ServiceSubscription)currentNSSI['serviceSubscription']
1010
1011         if(serviceSubscription != null) {
1012             requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
1013         }
1014
1015         // User params
1016         List<Map<String, Object>> userParams = new ArrayList<>()
1017
1018         Map<String, Object> userParam = new HashMap<>()
1019         userParam.put("Homing_Solution", "none")
1020         userParams.add(userParam)
1021
1022         // Service
1023         Map<String, Object> serviceMap = new HashMap<>()
1024         serviceMap.put("service", prepareService(execution, networkServiceInstance, modelInfo))
1025         userParams.add(serviceMap)
1026         requestParameters.setUserParams(userParams)
1027
1028         // No other user params
1029
1030         return requestParameters
1031     }
1032
1033
1034     /**
1035      * Prepare Owning Entity
1036      * @param execution
1037      * @return OwningEntity
1038      */
1039     OwningEntity prepareOwningEntity(DelegateExecution execution) {
1040         def currentNSSI = execution.getVariable("currentNSSI")
1041
1042         AAIResourcesClient client = getAAIClient()
1043
1044         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
1045
1046         OwningEntity owningEntity = new OwningEntity()
1047         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
1048         Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
1049         if (owningEntityRelationshipsOps.isPresent()) {
1050             List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.OWNING_ENTITY)
1051
1052             if (!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
1053                 Optional<org.onap.aai.domain.yang.OwningEntity> owningEntityOpt = client.get(org.onap.aai.domain.yang.OwningEntity.class, owningEntityRelatedAAIUris.get(0)) // Many-To-One relation
1054                 if (owningEntityOpt.isPresent()) {
1055                     owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
1056                     owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
1057
1058                 }
1059             }
1060         }
1061
1062         return owningEntity
1063     }
1064
1065
1066     /**
1067      * Prepares Project
1068      * @param execution
1069      * @return Project
1070      */
1071     Project prepareProject(DelegateExecution execution) {
1072         def currentNSSI = execution.getVariable("currentNSSI")
1073
1074         AAIResourcesClient client = getAAIClient()
1075
1076         Project project = new Project()
1077
1078         AAIResourceUri cloudRegionRelatedAAIUri = (AAIResourceUri)currentNSSI['cloudRegionRelatedAAIUri']
1079
1080         if (cloudRegionRelatedAAIUri != null) {
1081             AAIResultWrapper wrapper = client.get(cloudRegionRelatedAAIUri)
1082             Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
1083             if (cloudRegionOps.isPresent()) {
1084                 List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedAAIUris(AAIObjectType.PROJECT)
1085                 if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
1086                     Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.Project.class, projectAAIUris.get(0))
1087                     if (projectOpt.isPresent()) {
1088                         project.setProjectName(projectOpt.get().getProjectName())
1089                     }
1090                 }
1091             }
1092         }
1093
1094         return project
1095     }
1096
1097
1098     /**
1099      * Prepares RequestDetails object
1100      * @param execution
1101      * @return
1102      */
1103      String prepareRequestDetails(DelegateExecution execution) {
1104          String errorCode = ""
1105          String errorMessage = ""
1106          String response
1107
1108         RequestDetails requestDetails = new RequestDetails()
1109
1110         def currentNSSI = execution.getVariable("currentNSSI")
1111
1112         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
1113
1114          try {
1115              // Model Info
1116              ModelInfo modelInfo = prepareModelInfo(execution)
1117              requestDetails.setModelInfo(modelInfo)
1118
1119              // Subscriber Info
1120              requestDetails.setSubscriberInfo(prepareSubscriberInfo(execution))
1121
1122              // Request Info
1123              requestDetails.setRequestInfo(prepareRequestInfo(execution, networkServiceInstance))
1124
1125              // Request Parameters
1126              requestDetails.setRequestParameters(prepareRequestParameters(execution, networkServiceInstance, modelInfo))
1127
1128              // Cloud configuration
1129              requestDetails.setCloudConfiguration(prepareCloudConfiguration(execution))
1130
1131              // Owning entity
1132              requestDetails.setOwningEntity(prepareOwningEntity(execution))
1133
1134              // Project
1135              requestDetails.setProject(prepareProject(execution))
1136
1137              ObjectMapper mapper = new ObjectMapper()
1138
1139              response = mapper.writeValueAsString(requestDetails)
1140          }
1141          catch (any) {
1142              String msg = "Exception in DoDeallocateCoreNSSI.prepareRequestDetails. " + any.getCause()
1143              LOGGER.error(msg)
1144
1145              response =  "{\n" +
1146                      " \"errorCode\": \"7000\",\n" +
1147                      " \"errorMessage\": \"${msg}\"\n" +
1148                      "}"
1149
1150          }
1151
1152          return response
1153     }
1154
1155
1156     /**
1157      * Removes NSSI association with NSI
1158      * @param execution
1159      */
1160     void removeNSSIAssociationWithNSI(DelegateExecution execution) {
1161         LOGGER.trace("${PREFIX} Start removeNSSIAssociationWithNSI")
1162
1163         AAIResourcesClient client = getAAIClient()
1164
1165         def currentNSSI = execution.getVariable("currentNSSI")
1166
1167         String nssiId = currentNSSI['nssiId']
1168         String nsiId = currentNSSI['nsiId']
1169
1170         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
1171         AAIResourceUri nsiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nsiId)
1172
1173         try {
1174             client.disconnect(nssiUri, nsiUri)
1175         }catch(Exception e){
1176             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while NSSI association with NSI disconnect call: " + e.getMessage())
1177         }
1178
1179         LOGGER.trace("${PREFIX} Exit removeNSSIAssociationWithNSI")
1180     }
1181
1182
1183     /**
1184      * Removes Slice Profile association with NSSI
1185      * @param execution
1186      */
1187     void removeSPAssociationWithNSSI(DelegateExecution execution) {
1188         LOGGER.trace("${PREFIX} Start removeSPAssociationWithNSSI")
1189
1190         AAIResourcesClient client = getAAIClient()
1191
1192         def currentNSSI = execution.getVariable("currentNSSI")
1193
1194         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
1195
1196         String nssiId = currentNSSI['nssiId']
1197         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
1198
1199         List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
1200
1201         String currentSNSSAI = currentNSSI['S-NSSAI']
1202
1203         associatedProfiles.removeIf({ associatedProfile -> (associatedProfile.getSNssai().equals(currentSNSSAI)) })
1204
1205         try {
1206             getAAIClient().update(nssiUri, nssi)
1207         }catch(Exception e){
1208             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI update call: " + e.getMessage())
1209         }
1210
1211         LOGGER.trace("${PREFIX} Exit removeSPAssociationWithNSSI")
1212     }
1213
1214
1215     /**
1216      * Deletes Slice Profile Instance
1217      * @param execution
1218      */
1219     void deleteSliceProfileInstance(DelegateExecution execution) {
1220         LOGGER.trace("${PREFIX} Start deleteSliceProfileInstance")
1221
1222         AAIResourcesClient client = getAAIClient()
1223
1224         def currentNSSI = execution.getVariable("currentNSSI")
1225
1226         SliceProfile sliceProfileContainsSNSSAI = (SliceProfile)currentNSSI['sliceProfileS-NSSAI']
1227
1228         String globalSubscriberId = currentNSSI['globalSubscriberId']
1229         String serviceType = currentNSSI['serviceType']
1230         String nssiId = currentNSSI['nssiId']
1231
1232         // global-customer-id, service-type, service-instance-id, profile-id
1233         AAIResourceUri sliceProfileUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, globalSubscriberId, serviceType, nssiId, sliceProfileContainsSNSSAI.getProfileId())
1234
1235         try {
1236             getAAIClient().delete(sliceProfileUri)
1237         }catch(Exception e){
1238             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
1239         }
1240
1241         LOGGER.trace("${PREFIX} Exit deleteSliceProfileInstance")
1242     }
1243
1244
1245     /**
1246      * Delets NSSI Service Instance
1247      * @param execution
1248      */
1249     void deleteNSSIServiceInstance(DelegateExecution execution) {
1250         LOGGER.trace("${PREFIX} Start deleteNSSIServiceInstance")
1251
1252         AAIResourcesClient client = getAAIClient()
1253
1254         def currentNSSI = execution.getVariable("currentNSSI")
1255
1256         String nssiId = currentNSSI['nssiId']
1257         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
1258
1259         try {
1260             getAAIClient().delete(nssiUri)
1261         }catch(Exception e){
1262             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while NSSI Service Instance delete call: " + e.getMessage())
1263         }
1264
1265         LOGGER.trace("${PREFIX} Exit deleteNSSIServiceInstance")
1266     }
1267
1268
1269     /**
1270      * Updates operation status
1271      * @param execution
1272      */
1273     void updateServiceOperationStatus(DelegateExecution execution) {
1274         LOGGER.trace("${PREFIX} Start updateServiceOperationStatus")
1275
1276         def currentNSSI = execution.getVariable("currentNSSI")
1277
1278         OperationStatus operationStatus = new OperationStatus()
1279         operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
1280         operationStatus.setOperationId(currentNSSI['operationId'] as String)
1281         operationStatus.setOperation(currentNSSI['operationType'] as String)
1282         operationStatus.setResult(RequestsDbConstant.Status.FINISHED)
1283
1284         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
1285
1286         LOGGER.trace("${PREFIX} Exit updateServiceOperationStatus")
1287     }
1288
1289
1290     /**
1291      * Returns AAI client
1292      * @return AAI client
1293      */
1294     AAIResourcesClient getAAIClient() {
1295         return new AAIResourcesClient()
1296     }
1297
1298 }