Merge "Fix issues in AN NSSMF activation flow for SDNR interactions"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoActivateAccessNSSI.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 import static org.apache.commons.lang3.StringUtils.isBlank
23
24 import javax.ws.rs.NotFoundException
25
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.delegate.DelegateExecution
28 import org.onap.aai.domain.yang.Relationship
29 import org.onap.aai.domain.yang.ServiceInstance
30 import org.onap.aaiclient.client.aai.AAIObjectType
31 import org.onap.aaiclient.client.aai.AAIResourcesClient
32 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
33 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
34 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
35 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
36 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
37 import org.onap.so.beans.nsmf.ActDeActNssi
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.RequestDBUtil
44 import org.onap.so.bpmn.core.UrnPropertiesReader
45 import org.onap.so.bpmn.core.json.JsonUtils
46 import org.onap.so.db.request.beans.ResourceOperationStatus
47 import org.slf4j.Logger
48 import org.slf4j.LoggerFactory
49
50 import com.fasterxml.jackson.databind.ObjectMapper
51 import com.google.gson.JsonObject
52 import groovy.json.JsonSlurper
53 import com.google.gson.Gson
54
55 /**
56  * Internal AN NSSMF to handle NSSI Activation/Deactivation
57  *
58  */
59 class DoActivateAccessNSSI extends AbstractServiceTaskProcessor {
60         
61         String Prefix="DoActivateAccessNSSI"
62         ExceptionUtil exceptionUtil = new ExceptionUtil()
63         RequestDBUtil requestDBUtil = new RequestDBUtil()
64         JsonUtils jsonUtil = new JsonUtils()
65         ObjectMapper objectMapper = new ObjectMapper()
66         private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
67
68         private static final Logger logger = LoggerFactory.getLogger(DoActivateAccessNSSI.class)
69         private static final String ROLE_SLICE_PROFILE = "slice-profile-instance"
70         private static final String  ROLE_NSSI = "nssi"
71
72         private static final String KEY_SLICE_PROFILE = "SliceProfile"
73         private static final String KEY_NSSI = "NSSI"
74
75         private static final String AN_NF = "AN-NF"
76         private static final String TN_FH = "TN-FH"
77         private static final String TN_MH = "TN-MH"
78
79         private static final String ACTIVATE = "activateInstance"
80         private static final String DEACTIVATE = "deactivateInstance"
81
82         private static final String VENDOR_ONAP = "ONAP_internal"
83
84         def orchStatusMap = [activateInstance:"activated",deactivateInstance:"deactivated"]
85
86         @Override
87         public void preProcessRequest(DelegateExecution execution) {
88                 logger.debug("${Prefix} - Start preProcessRequest")
89
90                 String sliceParams = execution.getVariable("sliceParams")
91                 List<String> sNssaiList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceParams, "snssaiList"))
92                 String anSliceProfileId = jsonUtil.getJsonValue(sliceParams, "sliceProfileId")
93                 String nsiId = execution.getVariable("nsiId")
94                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
95                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
96                 String anNssiId = execution.getVariable("serviceInstanceID")
97                 String operationType = execution.getVariable("operationType")
98
99                 if((sNssaiList.empty) || isBlank(anSliceProfileId) || isBlank(nsiId)) {
100                         String msg = "Input fields cannot be null : Mandatory attributes : [snssaiList, sliceProfileId, nsiId]"
101                         logger.debug(msg)
102                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
103                 }
104
105                 if( isBlank(anNssiId) || isBlank(globalSubscriberId) || isBlank(subscriptionServiceType) || isBlank(operationType)) {
106                         String msg = "Missing Input fields from main process : [serviceInstanceID, globalSubscriberId, subscriptionServiceType, operationType]"
107                         logger.debug(msg)
108                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
109                 }
110
111                 execution.setVariable("sNssaiList", sNssaiList)
112                 execution.setVariable("anSliceProfileId", anSliceProfileId)
113                 execution.setVariable("nsiId", nsiId)
114                 execution.setVariable("anNssiId", anNssiId)
115
116                 logger.debug("${Prefix} - Preprocessing completed with sliceProfileId : ${anSliceProfileId} , nsiId : ${nsiId} , nssiId : ${anNssiId}")
117
118         }
119         
120         /**
121          * Method to fetch AN NSSI Constituents and Slice Profile constituents
122          * @param execution
123          */
124         void getRelatedInstances(DelegateExecution execution) {
125                 logger.debug("${Prefix} - Get Related Instances")
126                 String anSliceProfileId = execution.getVariable("anSliceProfileId")
127                 String anNssiId = execution.getVariable("anNssiId")
128
129                 Map<String,ServiceInstance> relatedSPs = new HashMap<>()
130                 execution.setVariable("relatedSPs", getRelatedInstancesByRole(execution, ROLE_SLICE_PROFILE,KEY_SLICE_PROFILE, anSliceProfileId))
131
132                 Map<String,ServiceInstance> relatedNssis = new HashMap<>()
133                 execution.setVariable("relatedNssis", getRelatedInstancesByRole(execution, ROLE_NSSI,KEY_NSSI, anNssiId))
134                 logger.trace("${Prefix} - Exit Get Related instances")
135         }
136         
137         /**
138          * Method to check Slice profile orchestration status
139          * @param execution
140          */
141         void getSPOrchStatus(DelegateExecution execution) {
142                 logger.debug("${Prefix} - Start getSPOrchStatus")
143                 ServiceInstance sliceProfileInstance = execution.getVariable(KEY_SLICE_PROFILE)
144                 String orchStatus = sliceProfileInstance.getOrchestrationStatus()
145                 String operationType = execution.getVariable("operationType")
146                 if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
147                         execution.setVariable("shouldChangeSPStatus", false)
148                 }else {
149                         execution.setVariable("shouldChangeSPStatus", true)
150                 
151                 }
152                 logger.debug("${Prefix} -  SPOrchStatus  : ${orchStatus}")
153         }
154         
155         /**
156          * Method to check AN NF's  Slice profile instance orchestration status
157          * @param execution
158          */
159         void getAnNfSPOrchStatus(DelegateExecution execution) {
160                 logger.debug("${Prefix} -  getAnNfSPOrchStatus ")
161                 ServiceInstance sliceProfileInstance = getInstanceByWorkloadContext(execution.getVariable("relatedSPs"), AN_NF)
162                 String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
163                 execution.setVariable("anNfNssiId", anNfNssiId)
164                 String anNfSPId = sliceProfileInstance.getServiceInstanceId()
165                 execution.setVariable("anNfSPId", anNfSPId)
166
167                 String orchStatus = sliceProfileInstance.getOrchestrationStatus()
168                 String operationType = execution.getVariable("operationType")
169                 if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
170                         execution.setVariable("shouldChangeAN_NF_SPStatus", false)
171                 }else {
172                         execution.setVariable("shouldChangeAN_NF_SPStatus", true)
173                 }
174                 logger.debug("${Prefix} -  getAnNfSPOrchStatus AN_NF SP ID:${anNfSPId}  : ${orchStatus}")
175         }
176
177         void prepareSdnrActivationRequest(DelegateExecution execution) {
178                 logger.debug("${Prefix} - start prepareSdnrActivationRequest")
179                 String operationType = execution.getVariable("operationType")
180                 String action = operationType.equalsIgnoreCase(ACTIVATE) ? "activate":"deactivate"
181
182                 String anNfNssiId = execution.getVariable("anNfNssiId")
183                 List<String> sNssai = execution.getVariable("sNssaiList")
184                 String reqId = execution.getVariable("msoRequestId")
185                 String messageType = "SDNRActivateResponse"
186                 StringBuilder callbackURL = new StringBuilder(UrnPropertiesReader.getVariable("mso.workflow.message.endpoint", execution))
187                 callbackURL.append("/").append(messageType).append("/").append(reqId)
188
189                 JsonObject input = new JsonObject()
190                 input.addProperty("RANNFNSSIId", anNfNssiId)
191                 input.addProperty("callbackURL", callbackURL.toString())
192                 input.addProperty("s-NSSAI", sNssai.toString())
193
194                 JsonObject Payload = new JsonObject()
195                 Payload.addProperty("version", "1.0")
196                 Payload.addProperty("rpc-name", "activateRANSlice")
197                 Payload.addProperty("correlation-id", reqId)
198                 Payload.addProperty("type", "request")
199
200                 JsonObject wrapinput = new JsonObject()
201                 wrapinput.addProperty("Action", action)
202
203                 JsonObject CommonHeader = new JsonObject()
204                 CommonHeader.addProperty("TimeStamp", new Date(System.currentTimeMillis()).format("yyyy-MM-dd'T'HH:mm:ss.sss", TimeZone.getDefault()))
205                 CommonHeader.addProperty("APIver", "1.0")
206                 CommonHeader.addProperty("RequestID", reqId)
207                 CommonHeader.addProperty("SubRequestID", "1")
208
209                 JsonObject body = new JsonObject()
210                 body.add("input", wrapinput)
211
212                 JsonObject sdnrRequest = new JsonObject()
213                 Payload.addProperty("input", input.toString())
214                 wrapinput.add("Payload", Payload)
215                 wrapinput.add("CommonHeader", CommonHeader)
216                 body.add("input", wrapinput)
217                 sdnrRequest.add("body", body)
218
219                 String json = sdnrRequest.toString()
220                 execution.setVariable("sdnrRequest", json)
221                 execution.setVariable("SDNR_messageType", messageType)
222                 execution.setVariable("SDNR_timeout", "PT10M")
223
224                 logger.debug("${Prefix} -  Exit prepareSdnrActivationRequest ")
225         }
226
227         void processSdnrResponse(DelegateExecution execution) {
228                 logger.debug("${Prefix} processing SdnrResponse")
229                 Map<String, Object> resMap = objectMapper.readValue(execution.getVariable("SDNR_Response"),Map.class)
230                 String status = resMap.get("status")
231                 String reason = resMap.get("reason")
232                 if("success".equalsIgnoreCase(status)) {
233                         execution.setVariable("isANactivationSuccess", true)
234                 }else {
235                         execution.setVariable("isANactivationSuccess", false)
236                         logger.debug("AN NF Activation/Deactivation failed with reason ${reason}")
237                 }
238                 logger.debug("${Prefix} processed SdnrResponse")
239         }
240         
241         /**
242          * Update AN NF - NSSI and SP Instance status
243          * @param execution
244          */
245         void updateAnNfStatus(DelegateExecution execution) {
246                 logger.debug("${Prefix}Start updateAnNfStatus")
247                 String anNfNssiId = execution.getVariable("anNfNssiId")
248                 String anNfSPId =  execution.getVariable("anNfSPId")
249
250                 updateOrchStatus(execution, anNfSPId)
251                 updateOrchStatus(execution, anNfNssiId)
252                 logger.debug("${Prefix}Exit  updateAnNfStatus")
253         }
254         
255         /**
256          * Method to check AN NF's  Slice profile instance orchestration status
257          * @param execution
258          */
259         void getTnFhSPOrchStatus(DelegateExecution execution) {
260                 logger.debug("${Prefix} start getTnFhSPOrchStatus ")
261                 ServiceInstance sliceProfileInstance = getInstanceByWorkloadContext(execution.getVariable("relatedSPs"), TN_FH)
262                 String tnFhNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_FH)
263                 execution.setVariable("tnFhNssiId", tnFhNssiId)
264                 String tnFhSPId = sliceProfileInstance.getServiceInstanceId()
265                 execution.setVariable("tnFhSPId", tnFhSPId)
266
267                 String orchStatus = sliceProfileInstance.getOrchestrationStatus()
268                 String operationType = execution.getVariable("operationType")
269                 if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
270                         execution.setVariable("shouldChangeTN_FH_SPStatus", false)
271                 }else {
272                         execution.setVariable("shouldChangeTN_FH_SPStatus", true)
273                 }
274
275                 logger.debug("${Prefix} Exit getTnFhSPOrchStatus TN_FH SP ID:${tnFhSPId}  : ${orchStatus}")
276         }
277         
278         void doTnFhNssiActivation(DelegateExecution execution){
279                 logger.debug("Start doTnFhNssiActivation in ${Prefix}")
280                 String nssmfRequest = buildTNActivateNssiRequest(execution, TN_FH)
281                 String operationType = execution.getVariable("operationType")
282                 String urlOpType = operationType.equalsIgnoreCase(ACTIVATE) ? "activation":"deactivation"
283
284                 List<String> sNssaiList =  execution.getVariable("sNssaiList")
285                 String snssai = sNssaiList.get(0) 
286                 String urlString = "/api/rest/provMns/v1/NSS/" + snssai + "/" + urlOpType
287                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
288                                 if (nssmfResponse != null) {
289                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
290                                         execution.setVariable("TN_FH_jobId",jobId)
291                                 } else {
292                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
293                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
294                                 }
295                 logger.debug("Exit doTnFhNssiActivation in ${Prefix}")
296         }
297
298         void getTnMhSPOrchStatus(DelegateExecution execution) {
299                 logger.debug("${Prefix} Start getTnMhSPOrchStatus ")
300                 ServiceInstance sliceProfileInstance = getInstanceByWorkloadContext(execution.getVariable("relatedSPs"), TN_MH)
301                 String tnFhNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_MH)
302                 execution.setVariable("tnMhNssiId", tnFhNssiId)
303                 String tnFhSPId = sliceProfileInstance.getServiceInstanceId()
304                 execution.setVariable("tnMhSPId", tnFhSPId)
305
306                 String orchStatus = sliceProfileInstance.getOrchestrationStatus()
307                 String operationType = execution.getVariable("operationType")
308                 if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
309                         execution.setVariable("shouldChangeTN_MH_SPStatus", false)
310                 }else {
311                         execution.setVariable("shouldChangeTN_MH_SPStatus", true)
312                 }
313                         logger.debug("${Prefix} Exit getTnMhSPOrchStatus TN_MH SP ID:${tnFhSPId}  : ${orchStatus}")
314         }
315         
316         void doTnMhNssiActivation(DelegateExecution execution){
317                 logger.debug("Start doTnMhNssiActivation in ${Prefix}")
318                 String nssmfRequest = buildTNActivateNssiRequest(execution, TN_MH)
319                 String operationType = execution.getVariable("operationType")
320                 String urlOpType = operationType.equalsIgnoreCase(ACTIVATE) ? "activation":"deactivation"
321
322                 List<String> sNssaiList =  execution.getVariable("sNssaiList")
323                 String snssai = sNssaiList.get(0) 
324
325                 String urlString = "/api/rest/provMns/v1/NSS/" + snssai + "/"  + urlOpType
326                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
327                                 if (nssmfResponse != null) {
328                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
329                                         execution.setVariable("TN_MH_jobId",jobId)
330                                 } else {
331                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
332                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
333                                 }
334                                 logger.debug("Exit doTnMhNssiActivation in ${Prefix}")
335                 
336         }
337         
338         /**
339          * Update TN FH - NSSI and SP Instance status
340          * @param execution
341          */
342         void updateTNFHStatus(DelegateExecution execution) {
343                 logger.debug("${Prefix} Start updateTNFHStatus")
344
345                 String tnFhNssiId = execution.getVariable("tnFhNssiId")
346                 String tnFhSPId =  execution.getVariable("tnFhSPId")
347                 updateOrchStatus(execution, tnFhSPId)
348                 updateOrchStatus(execution, tnFhNssiId)
349
350                 logger.debug("${Prefix} Exit updateTNFHStatus")
351                 
352         }
353         
354         /**
355          * Update TN MH - NSSI and SP Instance status
356          * @param execution
357          */
358         void updateTNMHStatus(DelegateExecution execution) {
359                 logger.debug("${Prefix} Start updateTNMHStatus")
360
361                 String tnMhNssiId = execution.getVariable("tnMhNssiId")
362                 String tnMhSPId =  execution.getVariable("tnMhSPId")
363                 updateOrchStatus(execution, tnMhSPId)
364                 updateOrchStatus(execution, tnMhNssiId)
365
366                 logger.debug("${Prefix} Exit updateTNMHStatus")
367         }
368         
369         /**
370          * Update AN - NSSI and SP Instance status
371          * @param execution
372          */
373         void updateANStatus(DelegateExecution execution) {
374                 logger.debug("${Prefix} Start updateANStatus")
375                 String anNssiId = execution.getVariable("anNssiId")
376                 String anSliceProfileId =  execution.getVariable("anSliceProfileId")
377                 updateOrchStatus(execution, anNssiId)
378                 updateOrchStatus(execution, anSliceProfileId)
379                 logger.debug("${Prefix} Exit updateANStatus")
380         }
381         
382         void prepareQueryJobStatus(DelegateExecution execution,String jobId,String networkType,String instanceId) {
383                 logger.debug("${Prefix} Start prepareQueryJobStatus : ${jobId}")
384                 String responseId = "1"
385                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
386                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
387
388                 EsrInfo esrInfo = new EsrInfo()
389                 esrInfo.setNetworkType(networkType)
390                 esrInfo.setVendor(VENDOR_ONAP)
391
392                 ServiceInfo serviceInfo = new ServiceInfo()
393                 serviceInfo.setNssiId(instanceId)
394                 serviceInfo.setNsiId(execution.getVariable("nsiId"))
395                 serviceInfo.setGlobalSubscriberId(globalSubscriberId)
396                 serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
397
398                 execution.setVariable("${networkType}_esrInfo", esrInfo)
399                 execution.setVariable("${networkType}_responseId", responseId)
400                 execution.setVariable("${networkType}_serviceInfo", serviceInfo)
401                 
402         }
403         
404         void validateJobStatus(DelegateExecution execution,String responseDescriptor) {
405                 logger.debug("validateJobStatus ${responseDescriptor}")
406                 String status = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.status")
407                 String statusDescription = jsonUtil.getJsonValue(responseDescriptor, "responseDescriptor.statusDescription")
408                 if("finished".equalsIgnoreCase(status)) {
409                         execution.setVariable("isSuccess", true)
410                 }else {
411                         execution.setVariable("isSuccess", false)
412                 }
413         }
414         
415         
416         private void updateOrchStatus(DelegateExecution execution,String serviceId) {
417                 logger.debug("${Prefix} Start updateOrchStatus : ${serviceId}")
418                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
419                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
420                 String operationType = execution.getVariable("operationType")
421
422                 try {
423                         AAIResourcesClient client = new AAIResourcesClient()
424                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceId))
425                         if (!client.exists(uri)) {
426                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
427                         }
428                         AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
429                         Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
430                         if (si.isPresent()) {
431                                 String orchStatus = si.get().getOrchestrationStatus()
432                                 logger.debug("Orchestration status of instance ${serviceId} is ${orchStatus}")
433                                 if (ACTIVATE.equalsIgnoreCase(operationType) && "deactivated".equalsIgnoreCase(orchStatus)) {
434                                                 si.get().setOrchestrationStatus("activated")
435                                                 client.update(uri, si.get())
436                                 } else if(DEACTIVATE.equalsIgnoreCase(operationType) && "activated".equalsIgnoreCase(orchStatus)){
437                                                 si.get().setOrchestrationStatus("deactivated")
438                                                 client.update(uri, si.get())
439                                 }
440                         }
441                 } catch (Exception e) {
442                         logger.info("Service is already in active state")
443                         String msg = "Service is already in active state, " + e.getMessage()
444                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
445                 }
446                 logger.debug("${Prefix} Exit updateOrchStatus : ${serviceId}")
447         }
448         
449         void prepareUpdateJobStatus(DelegateExecution execution,String status,String progress,String statusDescription) {
450                 logger.debug("${Prefix} Start prepareUpdateJobStatus : ${statusDescription}")
451                 String serviceId = execution.getVariable("anNssiId")
452                 String jobId = execution.getVariable("jobId")
453                 String nsiId = execution.getVariable("nsiId")
454                 String operationType = execution.getVariable("operationType")
455
456                 ResourceOperationStatus roStatus = new ResourceOperationStatus()
457                 roStatus.setServiceId(serviceId)
458                 roStatus.setOperationId(jobId)
459                 roStatus.setResourceTemplateUUID(nsiId)
460                 roStatus.setOperType(operationType)
461                 roStatus.setProgress(progress)
462                 roStatus.setStatus(status)
463                 roStatus.setStatusDescription(statusDescription)
464                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, roStatus)
465                 logger.debug("${Prefix} Exit prepareUpdateJobStatus : ${statusDescription}")
466         }
467         
468         
469         
470         /**
471          * Fetches a collection of service instances with the specific role and maps it based on workload context
472          * (AN-NF,TN-FH,TN-MH)
473          * @param execution
474          * @param role                  - nssi/slice profile instance
475          * @param key                   - NSSI/Sliceprofile corresponding to instanceId
476          * @param instanceId    - id to which the related list to be found
477          * @return
478          */
479         private Map<String,ServiceInstance> getRelatedInstancesByRole(DelegateExecution execution,String role,String key, String instanceId) {
480                 logger.debug("${Prefix} - Fetching related ${role} from AAI")
481                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
482                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
483                 
484                 if( isBlank(role) || isBlank(instanceId)) {
485                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Role and instanceId are mandatory")
486                 }
487
488                 Map<String,ServiceInstance> relatedInstances = new HashMap<>()
489                 
490                 AAIResourcesClient client = getAAIClient()
491                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(instanceId))
492                 if (!client.exists(uri)) {
493                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
494                 }
495                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
496                 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
497                 if(si.isPresent()) {
498                 execution.setVariable(key, si.get())
499                 List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
500                 for (Relationship relationship : relationshipList) {
501                         String relatedTo = relationship.getRelatedTo()
502                         if (relatedTo.toLowerCase() == "service-instance") {
503                                 String relatioshipurl = relationship.getRelatedLink()
504                                 String serviceInstanceId =
505                                                 relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
506                                 uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceInstanceId))
507                                 if (!client.exists(uri)) {
508                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
509                                                         "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
510                                 }
511                                 AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
512                                 Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
513                                 if (serviceInstance.isPresent()) {
514                                         ServiceInstance instance = serviceInstance.get()
515                                         if (role.equalsIgnoreCase(instance.getServiceRole())) {
516                                                 relatedInstances.put(instance.getWorkloadContext(),instance)
517                                         }
518                                 }
519                         }
520                 }
521                 }
522                 logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
523                 return relatedInstances
524         }
525         
526         private ServiceInstance getInstanceByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
527                 ServiceInstance instance = instances.get(workloadContext)
528                 if(instance == null) {
529                         throw new BpmnError( 2500, "${workloadContext} Instance ID is not found.")
530                 }
531                 return instance
532         }
533         
534         private String getInstanceIdByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
535                 String instanceId = instances.get(workloadContext).getServiceInstanceId()
536                 if(instanceId == null) {
537                         throw new BpmnError( 2500, "${workloadContext} instance ID is not found.")
538                 }
539                 return instanceId
540         }
541         
542         
543         /**
544          * Method to handle deallocation of RAN NSSI constituents(TN_FH/TN_MH)
545          * @param execution
546          * @param serviceFunction - TN_FH/TN_MH
547          * @return
548          */
549         private String buildTNActivateNssiRequest(DelegateExecution execution,String serviceFunction) {
550                 logger.debug("${Prefix} Exit buildTNActivateNssiRequest : ${serviceFunction}")
551                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
552                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
553                 Map<String, ServiceInstance> relatedNssis = execution.getVariable("relatedNssis")
554
555                 String anNssiId = execution.getVariable("anNssiId")
556                 List<String> sNssaiList =  execution.getVariable("sNssaiList")
557
558                 ServiceInstance tnNssi = relatedNssis.get(serviceFunction)
559                 String nssiId = tnNssi.getServiceInstanceId()
560
561                 Map<String, ServiceInstance> relatedSPs = execution.getVariable("relatedSPs")
562
563                 ActDeActNssi actDeactNssi = new ActDeActNssi()
564                 actDeactNssi.setNssiId(nssiId)
565                 actDeactNssi.setNsiId(anNssiId)
566                 actDeactNssi.setSliceProfileId(relatedSPs.get(serviceFunction).getServiceInstanceId())
567                 actDeactNssi.setSnssaiList(sNssaiList)
568
569                 JsonObject esrInfo = new JsonObject()
570                 esrInfo.addProperty("networkType", "tn")
571                 esrInfo.addProperty("vendor", VENDOR_ONAP)
572
573                 ServiceInfo serviceInfo = new ServiceInfo()
574                 serviceInfo.setServiceInvariantUuid(tnNssi.getModelInvariantId())
575                 serviceInfo.setServiceUuid(tnNssi.getModelVersionId())
576                 serviceInfo.setGlobalSubscriberId(globalSubscriberId)
577                 serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
578
579                 JsonObject json = new JsonObject()
580                 Gson jsonConverter = new Gson()
581                 json.add("actDeActNssi", jsonConverter.toJsonTree(actDeactNssi))
582                 json.add("esrInfo", esrInfo)
583                 json.add("serviceInfo", jsonConverter.toJsonTree(serviceInfo))
584                 return json.toString()
585                 
586         }
587         
588 }