Merge "Sonar fixes"
[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, ROLE_NSSI,messageType,serviceInstanceId)
142         OofRequest oofPayload = new OofRequest()
143                 oofPayload.setApiPath("/api/oof/terminate/nxi/v1")
144                 oofPayload.setRequestDetails(oofRequest)
145                 execution.setVariable("oofAnNssiPayload", oofPayload)
146         logger.debug("Finish prepareOOFTerminationRequest")
147
148         }
149         
150         void performOofAnNSSITerminationCall(DelegateExecution execution) {
151                 boolean terminateAnNSSI = callOofAdapter(execution,execution.getVariable("oofAnNssiPayload"))
152                 execution.setVariable("terminateAnNSSI", terminateAnNSSI)
153         }
154         
155         /**
156          * @param execution
157          */
158         void prepareOOFAnNfNssiTerminationRequest(DelegateExecution execution) {
159                 logger.debug("Start prepareOOFAnNfNssiTerminationRequest")
160                 String requestId = execution.getVariable("msoRequestId")
161                 String messageType = "AN_NF_NSSITermination"
162                 String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
163                 String serviceInstanceId = execution.getVariable("anNssiId")
164
165                 String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"),AN_NF)
166                 execution.setVariable("anNfNssiId", anNfNssiId)
167
168                 String oofRequest = oofUtils.buildTerminateNxiRequest(requestId,anNfNssiId, ROLE_NSSI,messageType,serviceInstanceId)
169                 OofRequest oofPayload = new OofRequest()
170                 oofPayload.setApiPath("/api/oof/terminate/nxi/v1")
171                 oofPayload.setRequestDetails(oofRequest)
172                 execution.setVariable("oofAnNfNssiPayload", oofPayload)
173                 logger.debug("Finish prepareOOFAnNfNssiTerminationRequest")
174
175         }
176
177         void performOofAnNfNSSITerminationCall(DelegateExecution execution) {
178                 boolean terminateAnNfNSSI = callOofAdapter(execution,execution.getVariable("oofAnNfNssiPayload"))
179                 execution.setVariable("terminateAnNfNSSI", terminateAnNfNSSI)
180                 if(!terminateAnNfNSSI) {
181                         execution.setVariable("modifyAction",true)
182                 }
183         }
184         
185         void prepareSdnrRequest(DelegateExecution execution) {
186
187                 String anNfNssiId = execution.getVariable("anNfNssiId")
188                 String sNssai = execution.getVariable("sNssaiList")
189                 String reqId = execution.getVariable("msoRequestId")
190                 String messageType = "SDNRTerminateResponse"
191                 StringBuilder callbackURL = new StringBuilder(UrnPropertiesReader.getVariable("mso.workflow.message.endpoint", execution))
192                 callbackURL.append("/").append(messageType).append("/").append(reqId)
193
194                 JsonObject input = new JsonObject()
195                 input.addProperty("RANNFNSSIId", anNfNssiId)
196                 input.addProperty("callbackURL", callbackURL.toString())
197                 input.addProperty("s-NSSAI", sNssai)
198
199                 JsonObject Payload = new JsonObject()
200                 Payload.addProperty("version", "1.0")
201                 Payload.addProperty("rpc-name", "TerminateRANSlice")
202                 Payload.addProperty("correlation-id", reqId)
203                 Payload.addProperty("type", "request")
204
205                 JsonObject wrapinput = new JsonObject()
206                 wrapinput.addProperty("Action", "deallocate")
207
208                 JsonObject CommonHeader = new JsonObject()
209                 CommonHeader.addProperty("TimeStamp", new Date(System.currentTimeMillis()).format("yyyy-MM-ddTHH:mm:ss.sss", TimeZone.getDefault()))
210                 CommonHeader.addProperty("APIver", "1.0")
211                 CommonHeader.addProperty("RequestID", reqId)
212                 CommonHeader.addProperty("SubRequestID", "1")
213
214                 JsonObject body = new JsonObject()
215                 body.add("input", wrapinput)
216
217                 JsonObject sdnrRequest = new JsonObject()
218                 Payload.add("input", input)
219                 wrapinput.add("Payload", Payload)
220                 wrapinput.add("CommonHeader", CommonHeader)
221                 body.add("input", wrapinput)
222                 sdnrRequest.add("body", body)
223
224                 String json = sdnrRequest.toString()
225                 execution.setVariable("sdnrRequest", sdnrRequest)
226                 execution.setVariable("SDNR_messageType", messageType)
227                 execution.setVariable("SDNR_timeout", "PT10M")
228
229         }
230         
231         void processSdnrResponse(DelegateExecution execution) {
232                 logger.debug("${Prefix} processing SdnrResponse")
233                 Map<String, Object> resMap = objectMapper.readValue(execution.getVariable("SDNR_Response"),Map.class)
234                 String status = resMap.get("status")
235                 String reason = resMap.get("reason")
236                 if("success".equalsIgnoreCase(status)) {
237                         execution.setVariable("isAnNfTerminated", true)
238                 }else {
239                         execution.setVariable("isAnNfTerminated", false)
240                         logger.debug("AN NF Termination failed with reason ${reason}")
241                 }
242                 logger.debug("${Prefix} processed SdnrResponse")
243         }
244         
245         /**
246          * @param execution
247          * @param oofRequest - Request payload to be sent to adapter
248          * @return
249          */
250         boolean callOofAdapter(DelegateExecution execution, OofRequest oofRequest) {
251                 logger.debug("Start callOofAdapter")
252                 String requestId = execution.getVariable("msoRequestId")
253                 String oofAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.oof.endpoint", execution)
254                 URL requestUrl = new URL(oofAdapterEndpoint)
255                 logger.debug("Calling OOF adapter  : ${requestUrl} with payload : ${oofRequest}")
256                 HttpClient httpClient = new HttpClientFactory().newJsonClient(requestUrl, ONAPComponents.EXTERNAL)
257                 Response httpResponse = httpClient.post(oofRequest)
258                 int responseCode = httpResponse.getStatus()
259                 logger.debug("OOF sync response code is: " + responseCode)
260                 if(responseCode != 200){
261                         logger.debug("OOF request failed with reason : " + httpResponse)
262                         exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
263                 }else {
264                         Map<String,Object> response = objectMapper.readValue(httpResponse.getEntity(),Map.class)
265                         boolean terminateResponse =  response.get("terminateResponse")
266                         if(!terminateResponse) {
267                                 logger.debug("Terminate response is false because " + response.get("reason"))
268                         }
269                         return terminateResponse
270                 }
271         }
272         
273         void deallocateAnNfNssi(DelegateExecution execution) {
274                 logger.debug("${Prefix} - call deallocateAnNfNssi ")
275                 String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
276                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
277                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
278
279                 AAIResourcesClient client = new AAIResourcesClient()
280                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(anNfNssiId))
281                 if (!client.exists(uri)) {
282                         logger.debug("AN NF Service Instance was not found in aai : ${anNfNssiId}")
283                 }else {
284                         client.delete(uri)
285                 }
286         }
287         
288         /**
289          * Removes relationship between AN NSSI and AN_NF NSSI
290          * @param execution
291          */
292         void dissociateAnNfNssi(DelegateExecution execution) {
293                 logger.debug("${Prefix} - call dissociateAnNfNssi ")
294                 String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
295                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
296                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
297
298                 AAIResourcesClient client = new AAIResourcesClient()
299                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(anNfNssiId))
300                 if (!client.exists(uri)) {
301                         logger.debug("AN NF Service Instance was not found in aai : ${anNfNssiId}")
302                 }else {
303                         client.delete(uri)
304                 }
305         }
306         
307         /**
308          * Method to prepare request for AN NSSI modification
309          * Call Modify AN NSSI in case OOF sends Terminate NSSI=False
310          * @param execution
311          */
312         void preparejobForANNSSIModification(DelegateExecution execution) {
313
314                 String modificationJobId = UUID.randomUUID().toString()
315                 execution.setVariable("modificationJobId", modificationJobId)
316
317                 Map<String,Object> sliceParams = objectMapper.readValue(execution.getVariable("sliceParams"), Map.class)
318                 sliceParams.put("modifyAction", "deallocate")
319                 execution.setVariable("modificationsliceParams", sliceParams)
320
321                 String serviceId = execution.getVariable("serviceInstanceId")
322                 String nsiId = execution.getVariable("nsiId")
323                 logger.debug("Generated new job for Service Instance serviceId:" + serviceId + " operationId:" + modificationJobId)
324
325                 ResourceOperationStatus initStatus = new ResourceOperationStatus()
326                 initStatus.setServiceId(serviceId)
327                 initStatus.setOperationId(modificationJobId)
328                 initStatus.setResourceTemplateUUID(nsiId)
329                 initStatus.setOperType("Modify-Deallocate")
330                 requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
331
332                 logger.debug(Prefix + "prepareInitOperationStatus Exit")
333         }
334
335         void prepareQueryJobStatus(DelegateExecution execution,String jobId,String networkType,String instanceId) {
336
337                 String responseId = "1"
338                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
339                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
340
341                 EsrInfo esrInfo = new EsrInfo()
342                 esrInfo.setNetworkType(networkType)
343                 esrInfo.setVendor("ONAP")
344
345                 ServiceInfo serviceInfo = new ServiceInfo()
346                 serviceInfo.setNssiId(instanceId)
347                 serviceInfo.setNsiId(execution.getVariable("nsiId"))
348                 serviceInfo.setGlobalSubscriberId(globalSubscriberId)
349                 serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
350
351                 execution.setVariable("${networkType}_esrInfo", esrInfo)
352                 execution.setVariable("${networkType}_responseId", responseId)
353                 execution.setVariable("${networkType}_serviceInfo", serviceInfo)
354
355         }
356
357         void validateJobStatus(DelegateExecution execution,String responseDescriptor) {
358                 logger.debug("validateJobStatus ${responseDescriptor}")
359                 String status = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.status")
360                 String statusDescription = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.statusDescription")
361                 if("finished".equalsIgnoreCase(status)) {
362                         execution.setVariable("isSuccess", true)
363                 }else {
364                         execution.setVariable("isSuccess", false)
365                 }
366         }
367         
368         void prepareUpdateJobStatus(DelegateExecution execution,String status,String progress,String statusDescription) {
369                 String serviceId = execution.getVariable("anNssiId")
370                 String jobId = execution.getVariable("jobId")
371                 String nsiId = execution.getVariable("nsiId")
372
373                 ResourceOperationStatus roStatus = new ResourceOperationStatus()
374                 roStatus.setServiceId(serviceId)
375                 roStatus.setOperationId(jobId)
376                 roStatus.setResourceTemplateUUID(nsiId)
377                 roStatus.setOperType("DeAllocate")
378                 roStatus.setProgress(progress)
379                 roStatus.setStatus(status)
380                 roStatus.setStatusDescription(statusDescription)
381                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, status)
382         }
383         
384         void terminateTNFHNssi(DelegateExecution execution) {
385                 logger.debug("Start terminateTNFHNssi in ${Prefix}")
386                 String nssmfRequest = buildDeallocateNssiRequest(execution, TN_FH)
387                 String nssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_FH)
388                 execution.setVariable("tnFHNSSIId", nssiId)
389                 String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
390                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
391                                 if (nssmfResponse != null) {
392                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
393                                         execution.setVariable("TN_FH_jobId",jobId)
394                                 } else {
395                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
396                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
397                                 }
398                                 logger.debug("Exit terminateTNFHNssi in ${Prefix}")
399         }
400         
401         void terminateTNMHNssi(DelegateExecution execution) {
402                 logger.debug("Start terminateTNMHNssi in ${Prefix}")
403                 String nssmfRequest = buildDeallocateNssiRequest(execution, TN_MH)
404                 String nssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_MH)
405                 execution.setVariable("tnMHNSSIId", nssiId)
406                 String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
407                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
408                                 if (nssmfResponse != null) {
409                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
410                                         execution.setVariable("TN_MH_jobId",jobId)
411                                 } else {
412                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
413                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
414                                 }
415                                 logger.debug("Exit terminateTNMHNssi in ${Prefix}")
416         }
417         
418         void deleteRanNfSliceProfileInAAI(DelegateExecution execution) {
419                 logger.debug("${Prefix} delete Ran NF SliceProfile In AAI")
420                 String spId = execution.getVariable("anNfSliceProfileId")
421                 deleteServiceInstanceInAAI(execution, spId)
422         }
423         
424         void deleteTNSliceProfileInAAI(DelegateExecution execution) {
425                 logger.debug("${Prefix} delete TN FH SliceProfile In AAI")
426                 String fhSP = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_FH)
427                 deleteServiceInstanceInAAI(execution, fhSP)
428                 logger.debug("${Prefix} delete TN MH SliceProfile In AAI")
429                 String mhSP = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_MH)
430                 deleteServiceInstanceInAAI(execution, mhSP)
431         }
432         
433         void deleteANNSSI(DelegateExecution execution) {
434                 logger.debug("${Prefix} delete AN NSSI")
435                 String nssiId = execution.getVariable("serviceInstanceID")
436                 deleteServiceInstanceInAAI(execution, nssiId)
437         }
438         
439         /**
440          * Fetches a collection of service instances with the specific role and maps it based on workload context
441          * (AN-NF,TN-FH,TN-MH)
442          * @param execution
443          * @param role                  - nssi/slice profile instance
444          * @param instanceId    - id to which the related list to be found
445          * @return
446          */
447         private Map<String,ServiceInstance> getRelatedInstancesByRole(DelegateExecution execution,String role,String instanceId) {
448                 logger.debug("${Prefix} - Fetching related ${role} from AAI")
449                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
450                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
451
452                 if( isBlank(role) || isBlank(instanceId)) {
453                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Role and instanceId are mandatory")
454                 }
455
456                 Map<String,ServiceInstance> relatedInstances = new HashMap<>()
457
458                 AAIResourcesClient client = getAAIClient()
459                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(instanceId))
460                 if (!client.exists(uri)) {
461                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
462                 }
463                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
464                 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
465                 if(si.isPresent()) {
466                 List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
467                 for (Relationship relationship : relationshipList) {
468                         String relatedTo = relationship.getRelatedTo()
469                         if (relatedTo.toLowerCase() == "service-instance") {
470                                 String relatioshipurl = relationship.getRelatedLink()
471                                 String serviceInstanceId =
472                                                 relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
473                                 uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceInstanceId))
474                                 if (!client.exists(uri)) {
475                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
476                                                         "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
477                                 }
478                                 AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
479                                 Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
480                                 if (serviceInstance.isPresent()) {
481                                         ServiceInstance instance = serviceInstance.get()
482                                         if (role.equalsIgnoreCase(instance.getServiceRole())) {
483                                                 relatedInstances.put(instance.getWorkloadContext(),instance)
484                                         }
485                                 }
486                         }
487                 }
488                 }
489                 logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
490                 return relatedInstances
491         }
492         
493         private String getInstanceIdByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
494                 String instanceId = instances.get(workloadContext).getServiceInstanceId()
495                 if(instanceId == null) {
496                         throw new BpmnError( 2500, "${workloadContext} NSSI ID is not found.")
497                 }
498                 return instanceId
499         }
500         
501         /**
502          * Method to handle deallocation of RAN NSSI constituents(TN_FH/TN_MH)
503          * @param execution
504          * @param serviceFunction - TN_FH/TN_MH
505          * @return
506          */
507         private String buildDeallocateNssiRequest(DelegateExecution execution,String serviceFunction) {
508                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
509                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
510                 Map<String, ServiceInstance> relatedNssis = execution.getVariable("relatedNssis")
511
512                 String anNssiId = execution.getVariable("anNssiId")
513                 List<String> sNssaiList =  execution.getVariable("sNssaiList")
514
515                 Map<String, ServiceInstance> relatedSPs = execution.getVariable("relatedSPs")
516
517                 DeAllocateNssi deallocateNssi = new DeAllocateNssi()
518                 deallocateNssi.setNsiId(anNssiId)
519                 ServiceInstance tnNssi = relatedNssis.get(serviceFunction)
520                 String nssiId = tnNssi.getServiceInstanceId()
521
522                 deallocateNssi.setNssiId(nssiId)
523                 deallocateNssi.setScriptName(tnNssi.getServiceInstanceName())
524                 deallocateNssi.setSnssaiList(sNssaiList)
525                 deallocateNssi.setSliceProfileId(relatedSPs.get(serviceFunction).getServiceInstanceId())
526
527                 EsrInfo esrInfo = new EsrInfo()
528                 esrInfo.setVendor("ONAP")
529                 esrInfo.setNetworkType("TN")
530
531                 ServiceInfo serviceInfo = new ServiceInfo()
532                 serviceInfo.setServiceInvariantUuid(tnNssi.getModelInvariantId())
533                 serviceInfo.setServiceUuid(tnNssi.getModelVersionId())
534                 serviceInfo.setGlobalSubscriberId(globalSubscriberId)
535                 serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
536
537                 JsonObject json = new JsonObject()
538                 json.addProperty("deAllocateNssi", objectMapper.writeValueAsString(deallocateNssi))
539                 json.addProperty("esrInfo", objectMapper.writeValueAsString(esrInfo))
540                 json.addProperty("serviceInfo", objectMapper.writeValueAsString(serviceInfo))
541                 return json.toString()
542                 
543         }
544         
545         private void deleteServiceInstanceInAAI(DelegateExecution execution,String instanceId) {
546                 try {
547                         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("serviceType")).serviceInstance(instanceId))
548                         getAAIClient().delete(serviceInstanceUri)
549                         logger.debug("${Prefix} Exited deleteServiceInstance")
550                 }catch(Exception e){
551                         logger.debug("Error occured within deleteServiceInstance method: " + e)
552                 }
553         }
554
555 }