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