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