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