Merge "Update of developer info for bb"
[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
23 import static org.apache.commons.lang3.StringUtils.isBlank
24
25 import javax.ws.rs.NotFoundException
26
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.delegate.DelegateExecution
29 import org.onap.aai.domain.yang.Relationship
30 import org.onap.aai.domain.yang.ServiceInstance
31 import org.onap.aaiclient.client.aai.AAIObjectType
32 import org.onap.aaiclient.client.aai.AAIResourcesClient
33 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
34 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
35 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
36 import org.onap.so.beans.nsmf.ActDeActNssi
37 import org.onap.so.beans.nsmf.EsrInfo
38 import org.onap.so.beans.nsmf.ServiceInfo
39 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
40 import org.onap.so.bpmn.common.scripts.ExceptionUtil
41 import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
42 import org.onap.so.bpmn.common.scripts.RequestDBUtil
43 import org.onap.so.bpmn.core.UrnPropertiesReader
44 import org.onap.so.bpmn.core.json.JsonUtils
45 import org.onap.so.db.request.beans.ResourceOperationStatus
46 import org.slf4j.Logger
47 import org.slf4j.LoggerFactory
48
49 import com.fasterxml.jackson.databind.ObjectMapper
50 import com.google.gson.JsonObject
51
52 /**
53  * Internal AN NSSMF to handle NSSI Activation/Deactivation
54  *
55  */
56 class DoActivateAccessNSSI extends AbstractServiceTaskProcessor {
57         
58         String Prefix="DoActivateAccessNSSI"
59         ExceptionUtil exceptionUtil = new ExceptionUtil()
60         RequestDBUtil requestDBUtil = new RequestDBUtil()
61         JsonUtils jsonUtil = new JsonUtils()
62         ObjectMapper objectMapper = new ObjectMapper()
63         private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
64
65         private static final Logger logger = LoggerFactory.getLogger(DoActivateAccessNSSI.class)
66         private static final String ROLE_SLICE_PROFILE = "slice-profile-instance"
67         private static final String  ROLE_NSSI = "nssi"
68
69         private static final String KEY_SLICE_PROFILE = "SliceProfile"
70         private static final String KEY_NSSI = "NSSI"
71
72         private static final String AN_NF = "AN-NF"
73         private static final String TN_FH = "TN-FH"
74         private static final String TN_MH = "TN-MH"
75
76         private static final String ACTIVATE = "activateInstance"
77         private static final String DEACTIVATE = "deactivateInstance"
78
79         private static final String VENDOR_ONAP = "ONAP"
80
81         Map<String,String> orchStatusMap = new HashMap<>()
82
83         @Override
84         public void preProcessRequest(DelegateExecution execution) {
85                 logger.debug("${Prefix} - Start preProcessRequest")
86
87                 String sliceParams = execution.getVariable("sliceParams")
88                 String sNssaiList = jsonUtil.getJsonValue(sliceParams, "snssaiList")
89                 String anSliceProfileId = jsonUtil.getJsonValue(sliceParams, "sliceProfileId")
90                 String nsiId = execution.getVariable("nsiId")
91                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
92                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
93                 String anNssiId = execution.getVariable("serviceInstanceID")
94                 String operationType = execution.getVariable("operationType")
95
96                 if(isBlank(sNssaiList) || isBlank(anSliceProfileId) || isBlank(nsiId)) {
97                         String msg = "Input fields cannot be null : Mandatory attributes : [snssaiList, sliceProfileId, nsiId]"
98                         logger.debug(msg)
99                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
100                 }
101
102                 if( isBlank(anNssiId) || isBlank(globalSubscriberId) || isBlank(subscriptionServiceType) || isBlank(operationType)) {
103                         String msg = "Missing Input fields from main process : [serviceInstanceID, globalSubscriberId, subscriptionServiceType, operationType]"
104                         logger.debug(msg)
105                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
106                 }
107
108                 execution.setVariable("sNssaiList", sNssaiList)
109                 execution.setVariable("anSliceProfileId", anSliceProfileId)
110                 execution.setVariable("nsiId", nsiId)
111                 execution.setVariable("anNssiId", anNssiId)
112
113                 orchStatusMap.put(ACTIVATE, "activated")
114                 orchStatusMap.put(DEACTIVATE, "deactivated")
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", true)
148                 }else {
149                         execution.setVariable("shouldChangeSPStatus", false)
150                 }
151                 logger.debug("${Prefix} -  SPOrchStatus  : ${orchStatus}")
152         }
153         
154         /**
155          * Method to check AN NF's  Slice profile instance orchestration status
156          * @param execution
157          */
158         void getAnNfSPOrchStatus(DelegateExecution execution) {
159                 logger.debug("${Prefix} -  getAnNfSPOrchStatus ")
160                 ServiceInstance sliceProfileInstance = getInstanceByWorkloadContext(execution.getVariable("relatedSPs"), AN_NF)
161                 String anNfNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), AN_NF)
162                 execution.setVariable("anNfNssiId", anNfNssiId)
163                 String anNfSPId = sliceProfileInstance.getServiceInstanceId()
164                 execution.setVariable("anNfSPId", anNfSPId)
165
166                 String orchStatus = sliceProfileInstance.getOrchestrationStatus()
167                 String operationType = execution.getVariable("operationType")
168                 if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
169                         execution.setVariable("shouldChangeAN_NF_SPStatus", true)
170                 }else {
171                         execution.setVariable("shouldChangeAN_NF_SPStatus", false)
172                 }
173                 logger.debug("${Prefix} -  getAnNfSPOrchStatus AN_NF SP ID:${anNfSPId}  : ${orchStatus}")
174         }
175
176         void prepareSdnrActivationRequest(DelegateExecution execution) {
177                 logger.debug("${Prefix} - start prepareSdnrActivationRequest")
178                 String operationType = execution.getVariable("operationType")
179                 String action = operationType.equalsIgnoreCase(ACTIVATE) ? "activate":"deactivate"
180
181                 String anNfNssiId = execution.getVariable("anNfNssiId")
182                 String sNssai = execution.getVariable("sNssaiList")
183                 String reqId = execution.getVariable("msoRequestId")
184                 String messageType = "SDNRActivateResponse"
185                 StringBuilder callbackURL = new StringBuilder(UrnPropertiesReader.getVariable("mso.workflow.message.endpoint", execution))
186                 callbackURL.append("/").append(messageType).append("/").append(reqId)
187
188                 JsonObject input = new JsonObject()
189                 input.addProperty("RANNFNSSIId", anNfNssiId)
190                 input.addProperty("callbackURL", callbackURL.toString())
191                 input.addProperty("s-NSSAI", sNssai)
192
193                 JsonObject Payload = new JsonObject()
194                 Payload.addProperty("version", "1.0")
195                 Payload.addProperty("rpc-name", "activateRANSlice")
196                 Payload.addProperty("correlation-id", reqId)
197                 Payload.addProperty("type", "request")
198
199                 JsonObject wrapinput = new JsonObject()
200                 wrapinput.addProperty("Action", action)
201
202                 JsonObject CommonHeader = new JsonObject()
203                 CommonHeader.addProperty("TimeStamp", new Date(System.currentTimeMillis()).format("yyyy-MM-ddTHH:mm:ss.sss", TimeZone.getDefault()))
204                 CommonHeader.addProperty("APIver", "1.0")
205                 CommonHeader.addProperty("RequestID", reqId)
206                 CommonHeader.addProperty("SubRequestID", "1")
207
208                 JsonObject body = new JsonObject()
209                 body.add("input", wrapinput)
210
211                 JsonObject sdnrRequest = new JsonObject()
212                 Payload.add("input", input)
213                 wrapinput.add("Payload", Payload)
214                 wrapinput.add("CommonHeader", CommonHeader)
215                 body.add("input", wrapinput)
216                 sdnrRequest.add("body", body)
217
218                 String json = sdnrRequest.toString()
219                 execution.setVariable("sdnrRequest", sdnrRequest)
220                 execution.setVariable("SDNR_messageType", messageType)
221                 execution.setVariable("SDNR_timeout", "PT10M")
222
223                 logger.debug("${Prefix} -  prepareSdnrActivationRequest : SDNR Request : ${json}")
224         }
225
226         void processSdnrResponse(DelegateExecution execution) {
227                 logger.debug("${Prefix} processing SdnrResponse")
228                 Map<String, Object> resMap = objectMapper.readValue(execution.getVariable("SDNR_Response"),Map.class)
229                 String status = resMap.get("status")
230                 String reason = resMap.get("reason")
231                 if("success".equalsIgnoreCase(status)) {
232                         execution.setVariable("isANactivationSuccess", true)
233                 }else {
234                         execution.setVariable("isANactivationSuccess", false)
235                         logger.debug("AN NF Activation/Deactivation failed with reason ${reason}")
236                 }
237                 logger.debug("${Prefix} processed SdnrResponse")
238         }
239         
240         /**
241          * Update AN NF - NSSI and SP Instance status
242          * @param execution
243          */
244         void updateAnNfStatus(DelegateExecution execution) {
245                 logger.debug("${Prefix}Start updateAnNfStatus")
246                 String anNfNssiId = execution.getVariable("anNfNssiId")
247                 String anNfSPId =  execution.getVariable("anNfSPId")
248
249                 updateOrchStatus(execution, anNfSPId)
250                 updateOrchStatus(execution, anNfNssiId)
251                 logger.debug("${Prefix}Exit  updateAnNfStatus")
252         }
253         
254         /**
255          * Method to check AN NF's  Slice profile instance orchestration status
256          * @param execution
257          */
258         void getTnFhSPOrchStatus(DelegateExecution execution) {
259                 logger.debug("${Prefix} start getTnFhSPOrchStatus ")
260                 ServiceInstance sliceProfileInstance = getInstanceByWorkloadContext(execution.getVariable("relatedSPs"), TN_FH)
261                 String tnFhNssiId = getInstanceIdByWorkloadContext(execution.getVariable("relatedNssis"), TN_FH)
262                 execution.setVariable("tnFhNssiId", tnFhNssiId)
263                 String tnFhSPId = sliceProfileInstance.getServiceInstanceId()
264                 execution.setVariable("tnFhSPId", tnFhSPId)
265
266                 String orchStatus = sliceProfileInstance.getOrchestrationStatus()
267                 String operationType = execution.getVariable("operationType")
268                 if(orchStatusMap.get(operationType).equalsIgnoreCase(orchStatus)) {
269                         execution.setVariable("shouldChangeTN_FH_SPStatus", true)
270                 }else {
271                         execution.setVariable("shouldChangeTN_FH_SPStatus", false)
272                 }
273
274                 logger.debug("${Prefix} Exit getTnFhSPOrchStatus TN_FH SP ID:${tnFhSPId}  : ${orchStatus}")
275         }
276         
277         void doTnFhNssiActivation(DelegateExecution execution){
278                 logger.debug("Start doTnFhNssiActivation in ${Prefix}")
279                 String nssmfRequest = buildTNActivateNssiRequest(execution, TN_FH)
280                 String operationType = execution.getVariable("operationType")
281                 String urlOpType = operationType.equalsIgnoreCase(ACTIVATE) ? "activation":"deactivation"
282
283                 List<String> sNssaiList =  execution.getVariable("sNssaiList")
284                 String snssai = sNssaiList != null ? sNssaiList.get(0) : ""
285
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", true)
310                 }else {
311                         execution.setVariable("shouldChangeTN_MH_SPStatus", false)
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 != null ? 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} Start 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(AAIObjectType.SERVICE_INSTANCE,
425                                         globalSubscriberId, subscriptionServiceType, serviceId)
426                         if (!client.exists(uri)) {
427                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
428                         }
429                         AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
430                         Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
431                         if (si.isPresent()) {
432                                 String orchStatus = si.get().getOrchestrationStatus()
433                                 logger.debug("Orchestration status of instance ${serviceId} is ${orchStatus}")
434                                 if (ACTIVATE.equalsIgnoreCase(operationType) && "deactivated".equalsIgnoreCase(orchStatus)) {
435                                                 si.get().setOrchestrationStatus("activated")
436                                                 client.update(uri, si.get())
437                                 } else if(DEACTIVATE.equalsIgnoreCase(operationType) && "activated".equalsIgnoreCase(orchStatus)){
438                                                 si.get().setOrchestrationStatus("deactivated")
439                                                 client.update(uri, si.get())
440                                 }
441                         }
442                 } catch (Exception e) {
443                         logger.info("Service is already in active state")
444                         String msg = "Service is already in active state, " + e.getMessage()
445                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
446                 }
447                 logger.debug("${Prefix} Exit updateOrchStatus : ${serviceId}")
448         }
449         
450         void prepareUpdateJobStatus(DelegateExecution execution,String status,String progress,String statusDescription) {
451                 logger.debug("${Prefix} Start prepareUpdateJobStatus : ${statusDescription}")
452                 String serviceId = execution.getVariable("anNssiId")
453                 String jobId = execution.getVariable("jobId")
454                 String nsiId = execution.getVariable("nsiId")
455                 String operationType = execution.getVariable("operationType")
456
457                 ResourceOperationStatus roStatus = new ResourceOperationStatus()
458                 roStatus.setServiceId(serviceId)
459                 roStatus.setOperationId(jobId)
460                 roStatus.setResourceTemplateUUID(nsiId)
461                 roStatus.setOperType(operationType)
462                 roStatus.setProgress(progress)
463                 roStatus.setStatus(status)
464                 roStatus.setStatusDescription(statusDescription)
465                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, status)
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(AAIObjectType.SERVICE_INSTANCE,
492                                 globalSubscriberId, subscriptionServiceType, instanceId)
493                 if (!client.exists(uri)) {
494                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
495                 }
496                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
497                 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
498                 if(si.isPresent()) {
499                 execution.setVariable(key, si.get())
500                 List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
501                 for (Relationship relationship : relationshipList) {
502                         String relatedTo = relationship.getRelatedTo()
503                         if (relatedTo.toLowerCase() == "service-instance") {
504                                 String relatioshipurl = relationship.getRelatedLink()
505                                 String serviceInstanceId =
506                                                 relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
507                                 uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
508                                                 globalSubscriberId, subscriptionServiceType, serviceInstanceId)
509                                 if (!client.exists(uri)) {
510                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
511                                                         "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
512                                 }
513                                 AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
514                                 Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
515                                 if (serviceInstance.isPresent()) {
516                                         ServiceInstance instance = serviceInstance.get()
517                                         if (role.equalsIgnoreCase(instance.getServiceRole())) {
518                                                 relatedInstances.put(instance.getWorkloadContext(),instance)
519                                         }
520                                 }
521                         }
522                 }
523                 }
524                 logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
525                 return relatedInstances
526         }
527         
528         private ServiceInstance getInstanceByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
529                 ServiceInstance instance = instances.get(workloadContext)
530                 if(instance == null) {
531                         throw new BpmnError( 2500, "${workloadContext} Instance ID is not found.")
532                 }
533                 return instance
534         }
535         
536         private String getInstanceIdByWorkloadContext(Map<String,ServiceInstance> instances,String workloadContext ) {
537                 String instanceId = instances.get(workloadContext).getServiceInstanceId()
538                 if(instanceId == null) {
539                         throw new BpmnError( 2500, "${workloadContext} instance ID is not found.")
540                 }
541                 return instanceId
542         }
543         
544         
545         /**
546          * Method to handle deallocation of RAN NSSI constituents(TN_FH/TN_MH)
547          * @param execution
548          * @param serviceFunction - TN_FH/TN_MH
549          * @return
550          */
551         private String buildTNActivateNssiRequest(DelegateExecution execution,String serviceFunction) {
552                 logger.debug("${Prefix} Exit buildTNActivateNssiRequest : ${serviceFunction}")
553                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
554                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
555                 Map<String, ServiceInstance> relatedNssis = execution.getVariable("relatedNssis")
556
557                 String anNssiId = execution.getVariable("anNssiId")
558                 List<String> sNssaiList =  execution.getVariable("sNssaiList")
559
560                 ServiceInstance tnNssi = relatedNssis.get(serviceFunction)
561                 String nssiId = tnNssi.getServiceInstanceId()
562
563                 Map<String, ServiceInstance> relatedSPs = execution.getVariable("relatedSPs")
564
565                 ActDeActNssi actDeactNssi = new ActDeActNssi()
566                 actDeactNssi.setNssiId(nssiId)
567                 actDeactNssi.setNsiId(anNssiId)
568                 actDeactNssi.setSliceProfileId(relatedSPs.get(serviceFunction).getServiceInstanceId())
569                 actDeactNssi.setSnssaiList(sNssaiList)
570
571                 EsrInfo esrInfo = new EsrInfo()
572                 esrInfo.setVendor(VENDOR_ONAP)
573                 esrInfo.setNetworkType("TN")
574
575                 ServiceInfo serviceInfo = new ServiceInfo()
576                 serviceInfo.setServiceInvariantUuid(tnNssi.getModelInvariantId())
577                 serviceInfo.setServiceUuid(tnNssi.getModelVersionId())
578                 serviceInfo.setGlobalSubscriberId(globalSubscriberId)
579                 serviceInfo.setSubscriptionServiceType(subscriptionServiceType)
580
581                 JsonObject json = new JsonObject()
582                 json.addProperty("actDeActNssi", objectMapper.writeValueAsString(actDeactNssi))
583                 json.addProperty("esrInfo", objectMapper.writeValueAsString(esrInfo))
584                 json.addProperty("serviceInfo", objectMapper.writeValueAsString(serviceInfo))
585                 return json.toString()
586                 
587         }
588         
589 }