Implement Deallocate RAN NSSI Workflow
[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.logging.filter.base.ONAPComponents
37 import org.onap.so.beans.nsmf.DeAllocateNssi
38 import org.onap.so.beans.nsmf.EsrInfo
39 import org.onap.so.beans.nsmf.ServiceInfo
40 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
41 import org.onap.so.bpmn.common.scripts.ExceptionUtil
42 import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
43 import org.onap.so.bpmn.common.scripts.OofUtils
44 import org.onap.so.bpmn.common.scripts.RequestDBUtil
45 import org.onap.so.bpmn.core.UrnPropertiesReader
46 import org.onap.so.bpmn.core.json.JsonUtils
47 import org.onap.so.client.HttpClient
48 import org.onap.so.client.HttpClientFactory
49 import org.onap.so.client.oof.adapter.beans.payload.OofRequest
50 import org.onap.so.db.request.beans.ResourceOperationStatus
51 import org.slf4j.Logger
52 import org.slf4j.LoggerFactory
53
54 import com.fasterxml.jackson.databind.ObjectMapper
55 import com.google.gson.JsonObject
56
57 /**
58  * Internal AN NSSMF to handle NSSI Deallocation
59  */
60 class DoDeAllocateAccessNSSI extends AbstractServiceTaskProcessor {
61
62         String Prefix="DoDeAllocateAccessNSSI"
63         ExceptionUtil exceptionUtil = new ExceptionUtil()
64         RequestDBUtil requestDBUtil = new RequestDBUtil()
65         JsonUtils jsonUtil = new JsonUtils()
66         OofUtils oofUtils = new OofUtils()
67         ObjectMapper objectMapper = new ObjectMapper()
68         private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
69         
70         private static final Logger logger = LoggerFactory.getLogger(DoDeAllocateAccessNSSI.class)
71         private static final String ROLE_SLICE_PROFILE = "slice-profile-instance"
72         private static final String ROLE_NSSI = "nssi"
73
74         private static final String AN_NF = "AN-NF"
75         private static final String TN_FH = "TN-FH"
76         private static final String TN_MH = "TN-MH"
77
78         @Override
79         public void preProcessRequest(DelegateExecution execution) {
80                 logger.debug("${Prefix} - Start preProcessRequest")
81
82                 String sliceParams = execution.getVariable("sliceParams")
83                 String sNssaiList = jsonUtil.getJsonValue(sliceParams, "snssaiList")
84                 String anSliceProfileId = jsonUtil.getJsonValue(sliceParams, "sliceProfileId")
85                 String nsiId = jsonUtil.getJsonValue(sliceParams, "nsiId")
86                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
87                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
88                 String anNssiId = execution.getVariable("serviceInstanceID")
89
90                 if(isBlank(sNssaiList) || isBlank(anSliceProfileId) || isBlank(nsiId)) {
91                         String msg = "Input fields cannot be null : Mandatory attributes : [snssaiList, sliceProfileId, nsiId]"
92                         logger.debug(msg)
93                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
94                 }
95
96                 if( isBlank(anNssiId) || isBlank(globalSubscriberId) || isBlank(subscriptionServiceType)) {
97                         String msg = "Missing Input fields from main process : [serviceInstanceID, globalSubscriberId, subscriptionServiceType]"
98                         logger.debug(msg)
99                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
100                 }
101
102                 execution.setVariable("sNssaiList", sNssaiList)
103                 execution.setVariable("anSliceProfileId", anSliceProfileId)
104                 execution.setVariable("nsiId", nsiId)
105                 execution.setVariable("anNssiId", anNssiId)
106
107                 logger.debug("${Prefix} - Preprocessing completed with sliceProfileId : ${anSliceProfileId} , nsiId : ${nsiId} , nssiId : ${anNssiId}")
108         }
109
110         /**
111          * Method to fetch AN NSSI Constituents and Slice Profile constituents
112          * @param execution
113          */
114         void getRelatedInstances(DelegateExecution execution) {
115                 logger.debug("${Prefix} - Get Related Instances")
116                 String anSliceProfileId = execution.getVariable("anSliceProfileId")
117                 String anNssiId = execution.getVariable("anNssiId")
118
119                 Map<String,ServiceInstance> relatedSPs = new HashMap<>()
120                 execution.setVariable("relatedSPs", getRelatedInstancesByRole(execution, ROLE_SLICE_PROFILE, anSliceProfileId))
121                 execution.setVariable("anNfSliceProfileId", getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), AN_NF))
122
123                 Map<String,ServiceInstance> relatedNssis = new HashMap<>()
124                 execution.setVariable("relatedNssis", getRelatedInstancesByRole(execution, ROLE_NSSI, anNssiId))
125         }
126         
127
128         /**
129          * @param execution
130          */
131         void prepareOOFAnNssiTerminationRequest(DelegateExecution execution) {
132                 logger.debug("Start prepareOOFTerminationRequest")
133         String requestId = execution.getVariable("msoRequestId")
134                 String messageType = "AN_NSSITermination"
135                 String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
136                 String serviceInstanceId = execution.getVariable("nsiId")
137                 String anNssiId = execution.getVariable("anNssiId")
138         String oofRequest = oofUtils.buildTerminateNxiRequest(requestId,anNssiId, ROLE_NSSI,messageType,serviceInstanceId)
139         OofRequest oofPayload = new OofRequest()
140                 oofPayload.setApiPath("/api/oof/terminate/nxi/v1")
141                 oofPayload.setRequestDetails(oofRequest)
142                 execution.setVariable("oofAnNssiPayload", oofPayload)
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, ROLE_NSSI,messageType,serviceInstanceId)
166                 OofRequest oofPayload = new OofRequest()
167                 oofPayload.setApiPath("/api/oof/terminate/nxi/v1")
168                 oofPayload.setRequestDetails(oofRequest)
169                 execution.setVariable("oofAnNfNssiPayload", oofPayload)
170                 logger.debug("Finish prepareOOFAnNfNssiTerminationRequest")
171
172         }
173
174         void performOofAnNfNSSITerminationCall(DelegateExecution execution) {
175                 boolean terminateAnNfNSSI = callOofAdapter(execution,execution.getVariable("oofAnNfNssiPayload"))
176                 execution.setVariable("terminateAnNfNSSI", terminateAnNfNSSI)
177                 if(!terminateAnNfNSSI) {
178                         execution.setVariable("modifyAction",true)
179                 }
180         }
181         
182         void prepareSdnrRequest(DelegateExecution execution) {
183
184                 String anNfNssiId = execution.getVariable("anNfNssiId")
185                 String sNssai = execution.getVariable("sNssaiList")
186                 String reqId = execution.getVariable("msoRequestId")
187                 String messageType = "SDNRTerminateResponse"
188                 StringBuilder callbackURL = new StringBuilder(UrnPropertiesReader.getVariable("mso.workflow.message.endpoint", execution))
189                 callbackURL.append("/").append(messageType).append("/").append(reqId)
190
191                 JsonObject input = new JsonObject()
192                 input.addProperty("RANNFNSSIId", anNfNssiId)
193                 input.addProperty("callbackURL", callbackURL.toString())
194                 input.addProperty("s-NSSAI", sNssai)
195
196                 JsonObject Payload = new JsonObject()
197                 Payload.addProperty("version", "1.0")
198                 Payload.addProperty("rpc-name", "TerminateRANSlice")
199                 Payload.addProperty("correlation-id", reqId)
200                 Payload.addProperty("type", "request")
201
202                 JsonObject wrapinput = new JsonObject()
203                 wrapinput.addProperty("Action", "deallocate")
204
205                 JsonObject CommonHeader = new JsonObject()
206                 CommonHeader.addProperty("TimeStamp", new Date(System.currentTimeMillis()).format("yyyy-MM-ddTHH:mm:ss.sss", TimeZone.getDefault()))
207                 CommonHeader.addProperty("APIver", "1.0")
208                 CommonHeader.addProperty("RequestID", reqId)
209                 CommonHeader.addProperty("SubRequestID", "1")
210
211                 JsonObject body = new JsonObject()
212                 body.add("input", wrapinput)
213
214                 JsonObject sdnrRequest = new JsonObject()
215                 Payload.add("input", input)
216                 wrapinput.add("Payload", Payload)
217                 wrapinput.add("CommonHeader", CommonHeader)
218                 body.add("input", wrapinput)
219                 sdnrRequest.add("body", body)
220
221                 String json = sdnrRequest.toString()
222                 execution.setVariable("sdnrRequest", sdnrRequest)
223                 execution.setVariable("SDNR_messageType", messageType)
224                 execution.setVariable("SDNR_timeout", "PT10M")
225
226         }
227         
228         void processSdnrResponse(DelegateExecution execution) {
229                 logger.debug("${Prefix} processing SdnrResponse")
230                 Map<String, Object> resMap = objectMapper.readValue(execution.getVariable("SDNR_Response"),Map.class)
231                 String status = resMap.get("status")
232                 String reason = resMap.get("reason")
233                 if("success".equalsIgnoreCase(status)) {
234                         execution.setVariable("isAnNfTerminated", true)
235                 }else {
236                         execution.setVariable("isAnNfTerminated", false)
237                         logger.debug("AN NF Termination failed with reason ${reason}")
238                 }
239                 logger.debug("${Prefix} processed SdnrResponse")
240         }
241         
242         /**
243          * @param execution
244          * @param oofRequest - Request payload to be sent to adapter
245          * @return
246          */
247         boolean callOofAdapter(DelegateExecution execution, OofRequest oofRequest) {
248                 logger.debug("Start callOofAdapter")
249                 String requestId = execution.getVariable("msoRequestId")
250                 String oofAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.oof.endpoint", execution)
251                 URL requestUrl = new URL(oofAdapterEndpoint)
252                 logger.debug("Calling OOF adapter  : ${requestUrl} with payload : ${oofRequest}")
253                 HttpClient httpClient = new HttpClientFactory().newJsonClient(requestUrl, ONAPComponents.EXTERNAL)
254                 Response httpResponse = httpClient.post(oofRequest)
255                 int responseCode = httpResponse.getStatus()
256                 logger.debug("OOF sync response code is: " + responseCode)
257                 if(responseCode != 200){
258                         logger.debug("OOF request failed with reason : " + httpResponse)
259                         exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
260                 }else {
261                         Map<String,Object> response = objectMapper.readValue(httpResponse.getEntity(),Map.class)
262                         boolean terminateResponse =  response.get("terminateResponse")
263                         if(!terminateResponse) {
264                                 logger.debug("Terminate response is false because " + response.get("reason"))
265                         }
266                         return terminateResponse
267                 }
268         }
269         
270         void deallocateAnNfNssi(DelegateExecution execution) {
271                 logger.debug("${Prefix} - call deallocateAnNfNssi ")
272                 String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
273                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
274                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
275
276                 AAIResourcesClient client = new AAIResourcesClient()
277                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
278                                 globalSubscriberId, subscriptionServiceType, 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(AAIObjectType.SERVICE_INSTANCE,
298                                 globalSubscriberId, subscriptionServiceType, anNfNssiId)
299                 if (!client.exists(uri)) {
300                         logger.debug("AN NF Service Instance was not found in aai : ${anNfNssiId}")
301                 }else {
302                         client.delete(uri)
303                 }
304         }
305         
306         /**
307          * Method to prepare request for AN NSSI modification
308          * Call Modify AN NSSI in case OOF sends Terminate NSSI=False
309          * @param execution
310          */
311         void preparejobForANNSSIModification(DelegateExecution execution) {
312
313                 String modificationJobId = UUID.randomUUID().toString()
314                 execution.setVariable("modificationJobId", modificationJobId)
315
316                 Map<String,Object> sliceParams = objectMapper.readValue(execution.getVariable("sliceParams"), Map.class)
317                 sliceParams.put("modifyAction", "deallocate")
318                 execution.setVariable("modificationsliceParams", sliceParams)
319
320                 String serviceId = execution.getVariable("serviceInstanceId")
321                 String nsiId = execution.getVariable("nsiId")
322                 logger.debug("Generated new job for Service Instance serviceId:" + serviceId + " operationId:" + modificationJobId)
323
324                 ResourceOperationStatus initStatus = new ResourceOperationStatus()
325                 initStatus.setServiceId(serviceId)
326                 initStatus.setOperationId(modificationJobId)
327                 initStatus.setResourceTemplateUUID(nsiId)
328                 initStatus.setOperType("Modify-Deallocate")
329                 requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
330
331                 logger.debug(Prefix + "prepareInitOperationStatus Exit")
332         }
333
334         void prepareQueryJobStatus(DelegateExecution execution,String jobId,String networkType,String instanceId) {
335
336                 String responseId = "1"
337                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
338                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
339
340                 EsrInfo esrInfo = new EsrInfo()
341                 esrInfo.setNetworkType(networkType)
342                 esrInfo.setVendor("ONAP")
343
344                 ServiceInfo serviceInfo = new ServiceInfo()
345                 serviceInfo.setNssiId(instanceId)
346                 serviceInfo.setNsiId(execution.getVariable("nsiId"))
347                 serviceInfo.setGlobalSubscriberId(globalSubscriberId)
348                 serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
349
350                 execution.setVariable("${networkType}_esrInfo", esrInfo)
351                 execution.setVariable("${networkType}_responseId", responseId)
352                 execution.setVariable("${networkType}_serviceInfo", serviceInfo)
353
354         }
355
356         void validateJobStatus(DelegateExecution execution,String responseDescriptor) {
357                 logger.debug("validateJobStatus ${responseDescriptor}")
358                 String status = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.status")
359                 String statusDescription = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.statusDescription")
360                 if("finished".equalsIgnoreCase(status)) {
361                         execution.setVariable("isSuccess", true)
362                 }else {
363                         execution.setVariable("isSuccess", false)
364                 }
365         }
366         
367         void prepareUpdateJobStatus(DelegateExecution execution,String status,String progress,String statusDescription) {
368                 String serviceId = execution.getVariable("anNssiId")
369                 String jobId = execution.getVariable("jobId")
370                 String nsiId = execution.getVariable("nsiId")
371
372                 ResourceOperationStatus roStatus = new ResourceOperationStatus()
373                 roStatus.setServiceId(serviceId)
374                 roStatus.setOperationId(jobId)
375                 roStatus.setResourceTemplateUUID(nsiId)
376                 roStatus.setOperType("DeAllocate")
377                 roStatus.setProgress(progress)
378                 roStatus.setStatus(status)
379                 roStatus.setStatusDescription(statusDescription)
380                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, status)
381         }
382         
383         void terminateTNFHNssi(DelegateExecution execution) {
384                 logger.debug("Start terminateTNFHNssi in ${Prefix}")
385                 String nssmfRequest = buildDeallocateNssiRequest(execution, TN_FH)
386                 String nssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_FH)
387                 execution.setVariable("tnFHNSSIId", nssiId)
388                 String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
389                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
390                                 if (nssmfResponse != null) {
391                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
392                                         execution.setVariable("TN_FH_jobId",jobId)
393                                 } else {
394                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
395                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
396                                 }
397                                 logger.debug("Exit terminateTNFHNssi in ${Prefix}")
398         }
399         
400         void terminateTNMHNssi(DelegateExecution execution) {
401                 logger.debug("Start terminateTNMHNssi in ${Prefix}")
402                 String nssmfRequest = buildDeallocateNssiRequest(execution, TN_MH)
403                 String nssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_MH)
404                 execution.setVariable("tnMHNSSIId", nssiId)
405                 String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
406                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
407                                 if (nssmfResponse != null) {
408                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
409                                         execution.setVariable("TN_MH_jobId",jobId)
410                                 } else {
411                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
412                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
413                                 }
414                                 logger.debug("Exit terminateTNMHNssi in ${Prefix}")
415         }
416         
417         void deleteRanNfSliceProfileInAAI(DelegateExecution execution) {
418                 logger.debug("${Prefix} delete Ran NF SliceProfile In AAI")
419                 String spId = execution.getVariable("anNfSliceProfileId")
420                 deleteServiceInstanceInAAI(execution, spId)
421         }
422         
423         void deleteTNSliceProfileInAAI(DelegateExecution execution) {
424                 logger.debug("${Prefix} delete TN FH SliceProfile In AAI")
425                 String fhSP = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_FH)
426                 deleteServiceInstanceInAAI(execution, fhSP)
427                 logger.debug("${Prefix} delete TN MH SliceProfile In AAI")
428                 String mhSP = getInstanceIdByWorkloadContext(execution.getVariable("relatedSPs"), TN_MH)
429                 deleteServiceInstanceInAAI(execution, mhSP)
430         }
431         
432         void deleteANNSSI(DelegateExecution execution) {
433                 logger.debug("${Prefix} delete AN NSSI")
434                 String nssiId = execution.getVariable("serviceInstanceID")
435                 deleteServiceInstanceInAAI(execution, nssiId)
436         }
437         
438         /**
439          * Fetches a collection of service instances with the specific role and maps it based on workload context
440          * (AN-NF,TN-FH,TN-MH)
441          * @param execution
442          * @param role                  - nssi/slice profile instance
443          * @param instanceId    - id to which the related list to be found
444          * @return
445          */
446         private Map<String,ServiceInstance> getRelatedInstancesByRole(DelegateExecution execution,String role,String instanceId) {
447                 logger.debug("${Prefix} - Fetching related ${role} from AAI")
448                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
449                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
450
451                 if( isBlank(role) || isBlank(instanceId)) {
452                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Role and instanceId are mandatory")
453                 }
454
455                 Map<String,ServiceInstance> relatedInstances = new HashMap<>()
456
457                 AAIResourcesClient client = getAAIClient()
458                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
459                                 globalSubscriberId, subscriptionServiceType, 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(AAIObjectType.SERVICE_INSTANCE,
474                                                 globalSubscriberId, subscriptionServiceType, serviceInstanceId)
475                                 if (!client.exists(uri)) {
476                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
477                                                         "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
478                                 }
479                                 AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
480                                 Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
481                                 if (serviceInstance.isPresent()) {
482                                         ServiceInstance instance = serviceInstance.get()
483                                         if (role.equalsIgnoreCase(instance.getServiceRole())) {
484                                                 relatedInstances.put(instance.getWorkloadContext(),instance)
485                                         }
486                                 }
487                         }
488                 }
489                 }
490                 logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
491                 return relatedInstances
492         }
493         
494         private String getInstanceIdByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
495                 String instanceId = instances.get(workloadContext).getServiceInstanceId()
496                 if(instanceId == null) {
497                         throw new BpmnError( 2500, "${workloadContext} NSSI ID is not found.")
498                 }
499                 return instanceId
500         }
501         
502         /**
503          * Method to handle deallocation of RAN NSSI constituents(TN_FH/TN_MH)
504          * @param execution
505          * @param serviceFunction - TN_FH/TN_MH
506          * @return
507          */
508         private String buildDeallocateNssiRequest(DelegateExecution execution,String serviceFunction) {
509                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
510                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
511                 Map<String, ServiceInstance> relatedNssis = execution.getVariable("relatedNssis")
512
513                 String anNssiId = execution.getVariable("anNssiId")
514                 List<String> sNssaiList =  execution.getVariable("sNssaiList")
515
516                 Map<String, ServiceInstance> relatedSPs = execution.getVariable("relatedSPs")
517
518                 DeAllocateNssi deallocateNssi = new DeAllocateNssi()
519                 deallocateNssi.setNsiId(anNssiId)
520                 ServiceInstance tnNssi = relatedNssis.get(serviceFunction)
521                 String nssiId = tnNssi.getServiceInstanceId()
522
523                 deallocateNssi.setNssiId(nssiId)
524                 deallocateNssi.setScriptName(tnNssi.getServiceInstanceName())
525                 deallocateNssi.setSnssaiList(sNssaiList)
526                 deallocateNssi.setSliceProfileId(relatedSPs.get(serviceFunction).getServiceInstanceId())
527
528                 EsrInfo esrInfo = new EsrInfo()
529                 esrInfo.setVendor("ONAP")
530                 esrInfo.setNetworkType("TN")
531
532                 ServiceInfo serviceInfo = new ServiceInfo()
533                 serviceInfo.setServiceInvariantUuid(tnNssi.getModelInvariantId())
534                 serviceInfo.setServiceUuid(tnNssi.getModelVersionId())
535                 serviceInfo.setGlobalSubscriberId(globalSubscriberId)
536                 serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
537
538                 JsonObject json = new JsonObject()
539                 json.addProperty("deAllocateNssi", objectMapper.writeValueAsString(deallocateNssi))
540                 json.addProperty("esrInfo", objectMapper.writeValueAsString(esrInfo))
541                 json.addProperty("serviceInfo", objectMapper.writeValueAsString(serviceInfo))
542                 return json.toString()
543                 
544         }
545         
546         private void deleteServiceInstanceInAAI(DelegateExecution execution,String instanceId) {
547                 try {
548                         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), instanceId)
549                         getAAIClient().delete(serviceInstanceUri)
550                         logger.debug("${Prefix} Exited deleteServiceInstance")
551                 }catch(Exception e){
552                         logger.debug("Error occured within deleteServiceInstance method: " + e)
553                 }
554         }
555
556 }