Fixed issues in AN NSSMF for modify & Deallocate flow
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeAllocateAccessNSSI.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020 Wipro Limited. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License")
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import static org.apache.commons.lang3.StringUtils.isBlank
24
25 import javax.ws.rs.NotFoundException
26 import javax.ws.rs.core.Response
27
28 import org.camunda.bpm.engine.delegate.BpmnError
29 import org.camunda.bpm.engine.delegate.DelegateExecution
30 import org.onap.aai.domain.yang.*
31 import org.onap.aaiclient.client.aai.AAIObjectType
32 import org.onap.aaiclient.client.aai.AAIResourcesClient
33 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
34 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
35 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
36 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
37 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
38 import org.onap.logging.filter.base.ONAPComponents
39 import org.onap.so.beans.nsmf.DeAllocateNssi
40 import org.onap.so.beans.nsmf.EsrInfo
41 import org.onap.so.beans.nsmf.ServiceInfo
42 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
43 import org.onap.so.bpmn.common.scripts.ExceptionUtil
44 import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
45 import org.onap.so.bpmn.common.scripts.OofUtils
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.client.oof.adapter.beans.payload.OofRequest
52 import org.onap.so.db.request.beans.ResourceOperationStatus
53 import org.slf4j.Logger
54 import org.slf4j.LoggerFactory
55
56 import com.fasterxml.jackson.databind.ObjectMapper
57 import com.google.gson.JsonObject
58
59
60 /**
61  * Internal AN NSSMF to handle NSSI Deallocation
62  */
63 class DoDeAllocateAccessNSSI extends AbstractServiceTaskProcessor {
64
65         String Prefix="DoDeAllocateAccessNSSI"
66         ExceptionUtil exceptionUtil = new ExceptionUtil()
67         RequestDBUtil requestDBUtil = new RequestDBUtil()
68         JsonUtils jsonUtil = new JsonUtils()
69         OofUtils oofUtils = new OofUtils()
70         ObjectMapper objectMapper = new ObjectMapper()
71         private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
72         
73         private static final Logger logger = LoggerFactory.getLogger(DoDeAllocateAccessNSSI.class)
74         private static final String ROLE_SLICE_PROFILE = "slice-profile-instance"
75         private static final String ROLE_NSSI = "nssi"
76
77         private static final String AN_NF = "AN-NF"
78         private static final String TN_FH = "TN-FH"
79         private static final String TN_MH = "TN-MH"
80
81         @Override
82         public void preProcessRequest(DelegateExecution execution) {
83                 logger.debug("${Prefix} - Start preProcessRequest")
84
85                 String sliceParams = execution.getVariable("sliceParams")
86                 String sNssaiList = jsonUtil.getJsonValue(sliceParams, "snssaiList")
87                 String anSliceProfileId = jsonUtil.getJsonValue(sliceParams, "sliceProfileId")
88                 String nsiId = jsonUtil.getJsonValue(sliceParams, "nsiId")
89                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
90                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
91                 String anNssiId = execution.getVariable("serviceInstanceID")
92
93                 if(isBlank(sNssaiList) || isBlank(anSliceProfileId) || isBlank(nsiId)) {
94                         String msg = "Input fields cannot be null : Mandatory attributes : [snssaiList, sliceProfileId, nsiId]"
95                         logger.debug(msg)
96                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
97                 }
98
99                 if( isBlank(anNssiId) || isBlank(globalSubscriberId) || isBlank(subscriptionServiceType)) {
100                         String msg = "Missing Input fields from main process : [serviceInstanceID, globalSubscriberId, subscriptionServiceType]"
101                         logger.debug(msg)
102                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
103                 }
104
105                 execution.setVariable("sNssaiList", sNssaiList)
106                 execution.setVariable("anSliceProfileId", anSliceProfileId)
107                 execution.setVariable("nsiId", nsiId)
108                 execution.setVariable("anNssiId", anNssiId)
109
110                 logger.debug("${Prefix} - Preprocessing completed with sliceProfileId : ${anSliceProfileId} , nsiId : ${nsiId} , nssiId : ${anNssiId}")
111         }
112
113         /**
114          * Method to fetch AN NSSI Constituents and Slice Profile constituents
115          * @param execution
116          */
117         void getRelatedInstances(DelegateExecution execution) {
118                 logger.debug("${Prefix} - Get Related Instances")
119                 String anSliceProfileId = execution.getVariable("anSliceProfileId")
120                 String anNssiId = execution.getVariable("anNssiId")
121
122                 Map<String,ServiceInstance> relatedSPs = new HashMap<>()
123                 execution.setVariable("relatedSPs", getRelatedInstancesByRole(execution, ROLE_SLICE_PROFILE, anSliceProfileId))
124                 execution.setVariable("anNfSliceProfileId", getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), AN_NF))
125
126                 Map<String,ServiceInstance> relatedNssis = new HashMap<>()
127                 execution.setVariable("relatedNssis", getRelatedInstancesByRole(execution, ROLE_NSSI, anNssiId))
128         }
129         
130
131         /**
132          * @param execution
133          */
134         void prepareOOFAnNssiTerminationRequest(DelegateExecution execution) {
135                 logger.debug("Start prepareOOFTerminationRequest")
136         String requestId = execution.getVariable("msoRequestId")
137                 String messageType = "AN_NSSITermination"
138                 String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
139                 String serviceInstanceId = execution.getVariable("nsiId")
140                 String anNssiId = execution.getVariable("anNssiId")
141         String oofRequest = oofUtils.buildTerminateNxiRequest(requestId,anNssiId, "NSSI",messageType,serviceInstanceId)
142                 execution.setVariable("oofAnNssiPayload", oofRequest)
143         logger.debug("Finish prepareOOFTerminationRequest")
144
145         }
146         
147         void performOofAnNSSITerminationCall(DelegateExecution execution) {
148                 boolean terminateAnNSSI = callOofAdapter(execution,execution.getVariable("oofAnNssiPayload"))
149                 execution.setVariable("terminateAnNSSI", terminateAnNSSI)
150         }
151         
152         /**
153          * @param execution
154          */
155         void prepareOOFAnNfNssiTerminationRequest(DelegateExecution execution) {
156                 logger.debug("Start prepareOOFAnNfNssiTerminationRequest")
157                 String requestId = execution.getVariable("msoRequestId")
158                 String messageType = "AN_NF_NSSITermination"
159                 String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
160                 String serviceInstanceId = execution.getVariable("anNssiId")
161
162                 String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"),AN_NF)
163                 execution.setVariable("anNfNssiId", anNfNssiId)
164
165                 String oofRequest = oofUtils.buildTerminateNxiRequest(requestId,anNfNssiId, "NSSI",messageType,serviceInstanceId)
166                 execution.setVariable("oofAnNfNssiPayload", oofRequest)
167                 logger.debug("Finish prepareOOFAnNfNssiTerminationRequest")
168
169         }
170
171         void performOofAnNfNSSITerminationCall(DelegateExecution execution) {
172                 boolean terminateAnNfNSSI = callOofAdapter(execution,execution.getVariable("oofAnNfNssiPayload"))
173                 execution.setVariable("terminateAnNfNSSI", terminateAnNfNSSI)
174                 if(!terminateAnNfNSSI) {
175                         execution.setVariable("modifyAction",true)
176                 }
177         }
178         
179         void prepareSdnrRequest(DelegateExecution execution) {
180
181                 String anNfNssiId = execution.getVariable("anNfNssiId")
182                 String sNssai = execution.getVariable("sNssaiList")
183                 String reqId = execution.getVariable("msoRequestId")
184                 String messageType = "SDNRTerminateResponse"
185                 StringBuilder callbackURL = new StringBuilder(UrnPropertiesReader.getVariable("mso.workflow.message.endpoint", execution))
186                 callbackURL.append("/").append(messageType).append("/").append(reqId)
187
188                 JsonObject input = new JsonObject()
189                 input.addProperty("RANNFNSSIId", anNfNssiId)
190                 input.addProperty("callbackURL", callbackURL.toString())
191                 input.addProperty("s-NSSAI", sNssai)
192
193                 JsonObject Payload = new JsonObject()
194                 Payload.addProperty("version", "1.0")
195                 Payload.addProperty("rpc-name", "terminateRANSliceInstance")
196                 Payload.addProperty("correlation-id", reqId)
197                 Payload.addProperty("type", "request")
198
199                 JsonObject wrapinput = new JsonObject()
200                 wrapinput.addProperty("action", "deallocate")
201
202                 JsonObject CommonHeader = new JsonObject()
203                 CommonHeader.addProperty("time-stamp", new Date(System.currentTimeMillis()).format("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", TimeZone.getDefault()))
204                 CommonHeader.addProperty("api-ver", "1.0")
205                 CommonHeader.addProperty("request-id", reqId)
206                 CommonHeader.addProperty("sub-request-id", "1")
207
208                 JsonObject body = new JsonObject()
209                 body.add("input", wrapinput)
210
211                 JsonObject sdnrRequest = new JsonObject()
212                 Payload.add("input", input)
213                 wrapinput.add("payload", Payload)
214                 wrapinput.add("common-header", CommonHeader)
215                 body.add("input", wrapinput)
216                 sdnrRequest.add("body", body)
217
218                 String json = sdnrRequest.toString()
219                 execution.setVariable("sdnrRequest", sdnrRequest)
220                 execution.setVariable("SDNR_messageType", messageType)
221                 execution.setVariable("SDNR_timeout", "PT10M")
222
223         }
224         
225         void processSdnrResponse(DelegateExecution execution) {
226                 logger.debug("${Prefix} processing SdnrResponse")
227                 Map<String, Object> resMap = objectMapper.readValue(execution.getVariable("SDNR_Response"),Map.class)
228                 String status = resMap.get("status")
229                 String reason = resMap.get("reason")
230                 if("success".equalsIgnoreCase(status)) {
231                         execution.setVariable("isAnNfTerminated", true)
232                 }else {
233                         execution.setVariable("isAnNfTerminated", false)
234                         logger.debug("AN NF Termination failed with reason ${reason}")
235                 }
236                 logger.debug("${Prefix} processed SdnrResponse")
237         }
238         
239         /**
240          * @param execution
241          * @param oofRequest - Request payload to be sent to adapter
242          * @return
243          */
244         boolean callOofAdapter(DelegateExecution execution, Object oofRequest) {
245                 logger.debug("Start callOofAdapter")
246                 String requestId = execution.getVariable("msoRequestId")
247                 String oofAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.oof.endpoint", execution)
248                 URL requestUrl = new URL(oofAdapterEndpoint)
249                 OofRequest oofPayload = new OofRequest()
250                 oofPayload.setApiPath("/api/oof/terminate/nxi/v1")
251                 oofPayload.setRequestDetails(oofRequest)
252                 String requestJson = objectMapper.writeValueAsString(oofPayload)
253                 logger.debug("Calling OOF adapter  : ${requestUrl} with payload : ${requestJson}")
254                 HttpClient httpClient = new HttpClientFactory().newJsonClient(requestUrl, ONAPComponents.EXTERNAL)
255                 Response httpResponse = httpClient.post(requestJson)
256                 int responseCode = httpResponse.getStatus()
257                 logger.debug("OOF sync response code is: " + responseCode)
258                 if(responseCode < 200 || responseCode >= 300){
259                         logger.debug("OOF request failed with reason : " + httpResponse)
260                         exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
261                 }else {
262                         Map<String,Object> response = objectMapper.readValue(httpResponse.getEntity(),Map.class)
263                         boolean terminateResponse =  response.get("terminateResponse")
264                         if(!terminateResponse) {
265                                 logger.debug("Terminate response is false because " + response.get("reason"))
266                         }
267                         return terminateResponse
268                 }
269         }
270         
271         void deallocateAnNfNssi(DelegateExecution execution) {
272                 logger.debug("${Prefix} - call deallocateAnNfNssi ")
273                 String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
274                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
275                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
276
277                 AAIResourcesClient client = new AAIResourcesClient()
278                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(anNfNssiId))
279                 if (!client.exists(uri)) {
280                         logger.debug("AN NF Service Instance was not found in aai : ${anNfNssiId}")
281                 }else {
282                         client.delete(uri)
283                 }
284         }
285         
286         /**
287          * Removes relationship between AN NSSI and AN_NF NSSI
288          * @param execution
289          */
290         void dissociateAnNfNssi(DelegateExecution execution) {
291                 logger.debug("${Prefix} - call dissociateAnNfNssi ")
292                 String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
293                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
294                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
295
296                 AAIResourcesClient client = new AAIResourcesClient()
297                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(anNfNssiId))
298                 if (!client.exists(uri)) {
299                         logger.debug("AN NF Service Instance was not found in aai : ${anNfNssiId}")
300                 }else {
301                         client.delete(uri)
302                 }
303         }
304         
305         /**
306          * Method to prepare request for AN NSSI modification
307          * Call Modify AN NSSI in case OOF sends Terminate NSSI=False
308          * @param execution
309          */
310         void preparejobForANNSSIModification(DelegateExecution execution) {
311
312                 String modificationJobId = UUID.randomUUID().toString()
313                 execution.setVariable("modificationJobId", modificationJobId)
314
315                 Map<String,Object> sliceParams = objectMapper.readValue(execution.getVariable("sliceParams"), Map.class)
316                 sliceParams.put("modifyAction", "deallocate")
317                 execution.setVariable("modificationsliceParams", objectMapper.writeValueAsString(sliceParams))
318
319                 String serviceId = execution.getVariable("serviceInstanceID")
320                 String nsiId = execution.getVariable("nsiId")
321                 logger.debug("Generated new job for Service Instance serviceId:" + serviceId + " operationId:" + modificationJobId)
322
323                 ResourceOperationStatus initStatus = new ResourceOperationStatus()
324                 initStatus.setServiceId(serviceId)
325                 initStatus.setOperationId(modificationJobId)
326                 initStatus.setResourceTemplateUUID(nsiId)
327                 initStatus.setOperType("Modify-Deallocate")
328                 requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
329
330                 logger.debug(Prefix + "prepareInitOperationStatus Exit")
331         }
332
333         void prepareQueryJobStatus(DelegateExecution execution,String jobId,String networkType,String instanceId) {
334
335                 String responseId = "1"
336                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
337                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
338
339                 EsrInfo esrInfo = new EsrInfo()
340                 esrInfo.setNetworkType(networkType)
341                 esrInfo.setVendor("ONAP")
342
343                 ServiceInfo serviceInfo = new ServiceInfo()
344                 serviceInfo.setNssiId(instanceId)
345                 serviceInfo.setNsiId(execution.getVariable("nsiId"))
346                 serviceInfo.setGlobalSubscriberId(globalSubscriberId)
347                 serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
348
349                 execution.setVariable("${networkType}_esrInfo", esrInfo)
350                 execution.setVariable("${networkType}_responseId", responseId)
351                 execution.setVariable("${networkType}_serviceInfo", serviceInfo)
352
353         }
354
355         void validateJobStatus(DelegateExecution execution,String responseDescriptor) {
356                 logger.debug("validateJobStatus ${responseDescriptor}")
357                 String status = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.status")
358                 String statusDescription = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.statusDescription")
359                 if("finished".equalsIgnoreCase(status)) {
360                         execution.setVariable("isSuccess", true)
361                 }else {
362                         execution.setVariable("isSuccess", false)
363                 }
364         }
365         
366         void prepareUpdateJobStatus(DelegateExecution execution,String status,String progress,String statusDescription) {
367                 String serviceId = execution.getVariable("anNssiId")
368                 String jobId = execution.getVariable("jobId")
369                 String nsiId = execution.getVariable("nsiId")
370
371                 ResourceOperationStatus roStatus = new ResourceOperationStatus()
372                 roStatus.setServiceId(serviceId)
373                 roStatus.setOperationId(jobId)
374                 roStatus.setResourceTemplateUUID(nsiId)
375                 roStatus.setOperType("DeAllocate")
376                 roStatus.setProgress(progress)
377                 roStatus.setStatus(status)
378                 roStatus.setStatusDescription(statusDescription)
379                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, roStatus)
380         }
381         
382         void terminateTNFHNssi(DelegateExecution execution) {
383                 logger.debug("Start terminateTNFHNssi in ${Prefix}")
384                 String nssmfRequest = buildDeallocateNssiRequest(execution, TN_FH)
385                 String nssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_FH)
386                 execution.setVariable("tnFHNSSIId", nssiId)
387                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles/" + nssiId
388                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
389                                 if (nssmfResponse != null) {
390                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
391                                         execution.setVariable("TN_FH_jobId",jobId)
392                                 } else {
393                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
394                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
395                                 }
396                                 logger.debug("Exit terminateTNFHNssi in ${Prefix}")
397         }
398         
399         void terminateTNMHNssi(DelegateExecution execution) {
400                 logger.debug("Start terminateTNMHNssi in ${Prefix}")
401                 String nssmfRequest = buildDeallocateNssiRequest(execution, TN_MH)
402                 String nssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_MH)
403                 execution.setVariable("tnMHNSSIId", nssiId)
404                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles/" + nssiId
405                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
406                                 if (nssmfResponse != null) {
407                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
408                                         execution.setVariable("TN_MH_jobId",jobId)
409                                 } else {
410                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
411                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
412                                 }
413                                 logger.debug("Exit terminateTNMHNssi in ${Prefix}")
414         }
415         
416         void deleteRanNfSliceProfileInAAI(DelegateExecution execution) {
417                 logger.debug("${Prefix} delete Ran NF SliceProfile In AAI")
418                 String spId = execution.getVariable("anNfSliceProfileId")
419                 deleteServiceInstanceInAAI(execution, spId)
420         }
421         
422         void deleteTNSliceProfileInAAI(DelegateExecution execution) {
423                 logger.debug("${Prefix} delete TN FH SliceProfile In AAI")
424                 String fhSP = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_FH)
425                 deleteServiceInstanceInAAI(execution, fhSP)
426                 logger.debug("${Prefix} delete TN MH SliceProfile In AAI")
427                 String mhSP = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_MH)
428                 deleteServiceInstanceInAAI(execution, mhSP)
429         }
430         
431         void deleteANNSSI(DelegateExecution execution) {
432                 logger.debug("${Prefix} delete AN NSSI")
433                 String nssiId = execution.getVariable("serviceInstanceID")
434                 deleteServiceInstanceInAAI(execution, nssiId)
435         }
436         
437         /**
438          * Fetches a collection of service instances with the specific role and maps it based on workload context
439          * (AN-NF,TN-FH,TN-MH)
440          * @param execution
441          * @param role                  - nssi/slice profile instance
442          * @param instanceId    - id to which the related list to be found
443          * @return
444          */
445         private Map<String,ServiceInstance> getRelatedInstancesByRole(DelegateExecution execution,String role,String instanceId) {
446                 logger.debug("${Prefix} - Fetching related ${role} from AAI")
447                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
448                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
449
450                 if( isBlank(role) || isBlank(instanceId)) {
451                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Role and instanceId are mandatory")
452                 }
453
454                 Map<String,ServiceInstance> relatedInstances = new HashMap<>()
455
456                 AAIResourcesClient client = getAAIClient()
457                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(instanceId))
458                 if (!client.exists(uri)) {
459                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
460                 }
461                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
462                 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
463                 if(si.isPresent()) {
464                 List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
465                 for (Relationship relationship : relationshipList) {
466                         String relatedTo = relationship.getRelatedTo()
467                         if (relatedTo.toLowerCase() == "service-instance") {
468                                 String relatioshipurl = relationship.getRelatedLink()
469                                 String serviceInstanceId =
470                                                 relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
471                                 uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceInstanceId))
472                                 if (!client.exists(uri)) {
473                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
474                                                         "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
475                                 }
476                                 AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
477                                 Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
478                                 if (serviceInstance.isPresent()) {
479                                         ServiceInstance instance = serviceInstance.get()
480                                         if (role.equalsIgnoreCase(instance.getServiceRole())) {
481                                                 relatedInstances.put(instance.getWorkloadContext(),instance)
482                                         }
483                                 }
484                         }
485                 }
486                 }
487                 logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
488                 return relatedInstances
489         }
490         
491         private String getInstanceIdByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
492                 String instanceId = instances.get(workloadContext).getServiceInstanceId()
493                 if(instanceId == null) {
494                         throw new BpmnError( 2500, "${workloadContext} NSSI ID is not found.")
495                 }
496                 return instanceId
497         }
498         
499         /**
500          * Method to handle deallocation of RAN NSSI constituents(TN_FH/TN_MH)
501          * @param execution
502          * @param serviceFunction - TN_FH/TN_MH
503          * @return
504          */
505         private String buildDeallocateNssiRequest(DelegateExecution execution,String serviceFunction) {
506                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
507                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
508                 Map<String, ServiceInstance> relatedNssis = execution.getVariable("relatedNssis")
509
510                 String anNssiId = execution.getVariable("anNssiId")
511                 List<String> sNssaiList =  execution.getVariable("sNssaiList")
512
513                 Map<String, ServiceInstance> relatedSPs = execution.getVariable("relatedSPs")
514
515                 DeAllocateNssi deallocateNssi = new DeAllocateNssi()
516                 deallocateNssi.setNsiId(anNssiId)
517                 ServiceInstance tnNssi = relatedNssis.get(serviceFunction)
518                 String nssiId = tnNssi.getServiceInstanceId()
519
520                 deallocateNssi.setNssiId(nssiId)
521                 deallocateNssi.setScriptName(tnNssi.getServiceInstanceName())
522                 deallocateNssi.setSnssaiList(sNssaiList)
523                 deallocateNssi.setSliceProfileId(relatedSPs.get(serviceFunction).getServiceInstanceId())
524
525                 EsrInfo esrInfo = new EsrInfo()
526                 esrInfo.setVendor("ONAP")
527                 esrInfo.setNetworkType("TN")
528
529                 ServiceInfo serviceInfo = new ServiceInfo()
530                 serviceInfo.setServiceInvariantUuid(tnNssi.getModelInvariantId())
531                 serviceInfo.setServiceUuid(tnNssi.getModelVersionId())
532                 serviceInfo.setGlobalSubscriberId(globalSubscriberId)
533                 serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
534
535                 JsonObject json = new JsonObject()
536                 json.addProperty("deAllocateNssi", objectMapper.writeValueAsString(deallocateNssi))
537                 json.addProperty("esrInfo", objectMapper.writeValueAsString(esrInfo))
538                 json.addProperty("serviceInfo", objectMapper.writeValueAsString(serviceInfo))
539                 return json.toString()
540                 
541         }
542         
543         private void deleteServiceInstanceInAAI(DelegateExecution execution,String instanceId) {
544                 try {
545                         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("serviceType")).serviceInstance(instanceId))
546                         getAAIClient().delete(serviceInstanceUri)
547                         logger.debug("${Prefix} Exited deleteServiceInstance")
548                 }catch(Exception e){
549                         logger.debug("Error occured within deleteServiceInstance method: " + e)
550                 }
551         }
552
553 }