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