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