982771f681c090aea0d4cc707587014837f9ee0f
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoModifyAccessNSSI.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  # Copyright (c) 2020, Wipro Limited.
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 org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
26 import org.onap.so.bpmn.common.scripts.ExceptionUtil
27 import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
28 import org.onap.so.bpmn.common.scripts.OofUtils
29 import org.onap.so.bpmn.common.scripts.RequestDBUtil
30 import org.onap.so.bpmn.core.json.JsonUtils
31 import org.onap.so.db.request.beans.ResourceOperationStatus
32 import org.slf4j.Logger
33 import org.slf4j.LoggerFactory
34 import java.sql.Timestamp
35 import java.util.List
36 import static org.apache.commons.lang3.StringUtils.isBlank
37 import com.google.gson.JsonObject
38 import com.fasterxml.jackson.databind.ObjectMapper
39 import com.google.gson.JsonArray
40 import org.onap.so.beans.nsmf.AllocateTnNssi
41 import org.onap.so.beans.nsmf.EsrInfo
42 import org.onap.so.bpmn.core.UrnPropertiesReader
43 import org.onap.so.bpmn.core.domain.ServiceDecomposition
44 import org.onap.so.bpmn.core.domain.ServiceProxy
45
46 import org.onap.aai.domain.yang.Relationship
47 import org.onap.aai.domain.yang.ServiceInstance
48 import org.onap.aai.domain.yang.SliceProfile
49 import org.onap.aaiclient.client.aai.AAIObjectType
50 import org.onap.aaiclient.client.aai.AAIResourcesClient
51 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
52 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
53 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
54 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
55 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
56 import javax.ws.rs.NotFoundException
57
58 class DoModifyAccessNSSI extends AbstractServiceTaskProcessor {
59
60         String Prefix="MASS_"
61         ExceptionUtil exceptionUtil = new ExceptionUtil()
62         RequestDBUtil requestDBUtil = new RequestDBUtil()
63         JsonUtils jsonUtil = new JsonUtils()
64         OofUtils oofUtils = new OofUtils()
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(DoModifyAccessNSSI.class)
70
71         @Override
72         void preProcessRequest(DelegateExecution execution) {
73                 logger.debug(Prefix + "preProcessRequest Start")
74                 execution.setVariable("prefix", Prefix)
75                 execution.setVariable("startTime", System.currentTimeMillis())
76                 def msg
77                 try {
78
79                         logger.debug("input variables : msoRequestId - "+execution.getVariable("msoRequestId")+
80                                         " globalSubscriberId - "+execution.getVariable("globalSubscriberId")+
81                                         " serviceInstanceID - "+execution.getVariable("serviceInstanceID")+
82                                         " nsiId - "+execution.getVariable("nsiId")+
83                                         " networkType - "+execution.getVariable("networkType")+
84                                         " subscriptionServiceType - "+execution.getVariable("subscriptionServiceType")+
85                                         " jobId - "+execution.getVariable("jobId")+
86                                         " sliceParams - "+execution.getVariable("sliceParams")+
87                                         " servicename - "+ execution.getVariable("servicename"))
88
89                         //validate slice subnet inputs
90
91                         String sliceParams = execution.getVariable("sliceParams")
92                         String modifyAction = jsonUtil.getJsonValue(sliceParams, "modifyAction")
93                         if (isBlank(modifyAction)) {
94                                 msg = "Input modifyAction is null"
95                                 logger.debug(msg)
96                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
97                         } else {
98                                 execution.setVariable("modifyAction", modifyAction)
99                                 switch(modifyAction) {
100                                         case "allocate":
101                                                 execution.setVariable("isModifyallocate", true)
102                                                 break
103                                         case "deallocate":
104                                                 execution.setVariable("isModifydeallocate", true)
105                                                 break
106                                         case "reconfigure":
107                                                 execution.setVariable("isModifyreconfigure", true)
108                                                 String resourceConfig = jsonUtil.getJsonValue(sliceParams, "resourceConfig")
109                                                 execution.setVariable("additionalProperties", resourceConfig)
110                                                 break
111                                         default:
112                                                 logger.debug("Invalid modify Action")
113                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid modify Action : "+modifyAction)
114                                 }
115                         }
116                         List<String> snssaiList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceParams, "snssaiList"))
117                         String sliceProfileId = jsonUtil.getJsonValue(sliceParams, "sliceProfileId")
118                         if (isBlank(sliceProfileId) || (snssaiList.empty)) {
119                                 msg = "Mandatory fields are empty"
120                                 logger.debug(msg)
121                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
122                         } else {
123                                 execution.setVariable("sliceProfileId", sliceProfileId)
124                                 execution.setVariable("snssaiList", snssaiList)
125                         }
126                         String nsiName = jsonUtil.getJsonValue(sliceParams, "nsiInfo.nsiName")
127                         String scriptName = jsonUtil.getJsonValue(sliceParams, "scriptName")
128                         execution.setVariable("nsiName", nsiName)
129                         execution.setVariable("scriptName", scriptName)
130                         execution.setVariable("job_timeout", 10)
131                         execution.setVariable("ranNssiPreferReuse", false)
132                 } catch(BpmnError e) {
133                         throw e
134                 } catch(Exception ex) {
135                         msg = "Exception in DoModifyAccessNSSI.preProcessRequest " + ex.getMessage()
136                         logger.debug(msg)
137                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
138                 }
139                 logger.debug(Prefix + "preProcessRequest Exit")
140         }
141         
142         def getSliceProfile = { DelegateExecution execution ->
143                 logger.debug(Prefix + "getSliceProfiles Start")
144                 String instanceId = execution.getVariable("sliceProfileId")
145                 ServiceInstance sliceProfileInstance = getServiceInstance(execution, instanceId)
146                 SliceProfile ranSliceProfile = sliceProfileInstance.getSliceProfiles().getSliceProfile().get(0)
147                 logger.debug("RAN slice profile : "+ranSliceProfile.toString())
148                 execution.setVariable("RANSliceProfile", ranSliceProfile)
149                 execution.setVariable("ranSliceProfileInstance", sliceProfileInstance)
150         }
151         
152         /*
153          * Function to subnet capabilities from nssmf adapter
154          */
155         def getSubnetCapabilities = { DelegateExecution execution ->
156                 logger.debug(Prefix+"getSubnetCapabilities method start")
157
158                 String tnNssmfRequest = anNssmfUtils.buildCreateTNNSSMFSubnetCapabilityRequest()
159
160                 String urlString = "/api/rest/provMns/v1/NSS/subnetCapabilityQuery"
161
162                 String tnNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, tnNssmfRequest)
163
164                 if (tnNssmfResponse != null) {
165                         String FHCapabilities= jsonUtil.getJsonValue(tnNssmfResponse, "TN_FH")
166                         String MHCapabilities = jsonUtil.getJsonValue(tnNssmfResponse, "TN_MH")
167                         execution.setVariable("FHCapabilities",FHCapabilities)
168                         execution.setVariable("MHCapabilities",MHCapabilities)
169
170                 } else {
171                         logger.error("received error message from NSSMF : "+ tnNssmfResponse)
172                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
173                 }
174                 String anNssmfRequest = anNssmfUtils.buildCreateANNFNSSMFSubnetCapabilityRequest()
175
176                 String anNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, anNssmfRequest)
177
178                 if (anNssmfResponse != null) {
179                         String ANNFCapabilities = jsonUtil.getJsonValue(anNssmfResponse, "AN_NF")
180                         execution.setVariable("ANNFCapabilities",ANNFCapabilities)
181
182                 } else {
183                         logger.error("received error message from NSSMF : "+ anNssmfResponse)
184                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
185                 }
186         }
187
188         
189         /*
190          * prepare OOF request for RAN NSSI selection
191          */
192         def prepareOofRequestForRanNSS = { DelegateExecution execution ->
193                 logger.debug(Prefix+"prepareOofRequestForRanNSS method start")
194
195                 String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
196                 logger.debug( "get NSSI option OOF Url: " + urlString)
197
198                 //build oof request body
199                 boolean ranNssiPreferReuse = execution.getVariable("ranNssiPreferReuse");
200                 String requestId = execution.getVariable("msoRequestId")
201                 String messageType = "NSISelectionResponse"
202                 Map<String, Object> profileInfo = objectMapper.readValue(execution.getVariable("RANSliceProfile"), Map.class)
203                 ServiceInstance ranSliceProfileInstance = objectMapper.readValue(execution.getVariable("ranSliceProfileInstance"), ServiceInstance.class)
204                 String modelUuid = ranSliceProfileInstance.getModelVersionId()
205                 String modelInvariantUuid = ranSliceProfileInstance.getModelInvariantId()
206                 String modelName = execution.getVariable("servicename")
207                 String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
208                 List<String> nsstInfoList =  new ArrayList<>()
209                 JsonArray capabilitiesList = new JsonArray()
210                 String FHCapabilities = execution.getVariable("FHCapabilities")
211                 String MHCapabilities = execution.getVariable("MHCapabilities")
212                 String ANNFCapabilities = execution.getVariable("ANNFCapabilities")
213                 JsonObject FH = new JsonObject()
214                 JsonObject MH = new JsonObject()
215                 JsonObject ANNF = new JsonObject()
216                 FH.addProperty("domainType", "TN_FH")
217                 FH.addProperty("capabilityDetails", FHCapabilities)
218                 MH.addProperty("domainType", "TN_MH")
219                 MH.addProperty("capabilityDetails", MHCapabilities)
220                 ANNF.addProperty("domainType", "AN_NF")
221                 ANNF.addProperty("capabilityDetails", FHCapabilities)
222                 capabilitiesList.add(FH)
223                 capabilitiesList.add(MH)
224                 capabilitiesList.add(ANNF)
225
226                 execution.setVariable("nssiSelection_Url", "/api/oof/selection/nsi/v1")
227                 execution.setVariable("nssiSelection_messageType",messageType)
228                 execution.setVariable("nssiSelection_correlator",requestId)
229                 execution.setVariable("nssiSelection_timeout",timeout)
230                 String oofRequest = anNssmfUtils.buildSelectRANNSSIRequest(requestId, messageType, modelUuid,modelInvariantUuid,
231                                 modelName, profileInfo, nsstInfoList, capabilitiesList, ranNssiPreferReuse)
232
233                 execution.setVariable("nssiSelection_oofRequest",oofRequest)
234                 logger.debug("Sending request to OOF: " + oofRequest)
235         }
236         
237         /*
238          * process OOF response for RAN NSSI selection
239          */
240         def processOofResponseForRanNSS = { DelegateExecution execution ->
241                 logger.debug(Prefix+"processOofResponseForRanNSS method start")
242                 String oofResponse = execution.getVariable("nssiSelection_asyncCallbackResponse")
243                 String requestStatus = jsonUtil.getJsonValue(oofResponse, "requestStatus")
244                 if(requestStatus.equals("completed")) {
245                         List<String> solution = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(oofResponse, "solutions"))
246                         boolean existingNSI = jsonUtil.getJsonValue(solution.get(0), "existingNSI")
247                         if(!existingNSI) {
248                                 def sliceProfiles = jsonUtil.getJsonValue(solution.get(0), "newNSISolution.sliceProfiles")
249                                 execution.setVariable("RanConstituentSliceProfiles", sliceProfiles)
250                                 List<String> ranConstituentSliceProfiles = jsonUtil.StringArrayToList(sliceProfiles)
251                                 anNssmfUtils.createDomainWiseSliceProfiles(ranConstituentSliceProfiles, execution)
252                                 logger.debug("RanConstituentSliceProfiles list from OOF "+sliceProfiles)
253                         }else {
254                                 String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
255                                 logger.error("failed to get slice profiles from oof "+ statusMessage)
256                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"failed to get slice profiles from oof "+statusMessage)
257                         }
258                 }else {
259                         String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
260                         logger.error("received failed status from oof "+ statusMessage)
261                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a failed Async Response from OOF : "+statusMessage)
262                 }
263
264         }
265         def getNssisFromAai = { DelegateExecution execution ->
266                 logger.debug(Prefix+"getNssisFromAai method start")
267                 String instanceId = execution.getVariable("serviceInstanceID")
268                 String role = "nssi"
269                 Map<String,ServiceInstance> ranConstituentNssis = getRelatedInstancesByRole(execution, role, instanceId)
270                 logger.debug("getNssisFromAai ranConstituentNssis : "+ranConstituentNssis.toString())
271                 ranConstituentNssis.each { key, val -> 
272                         switch(key) {
273                                 case "AN-NF":
274                                         execution.setVariable("ANNF_NSSI", val.getServiceInstanceId())
275                                         execution.setVariable("ANNF_nssiName", val.getServiceInstanceName())
276                                         break
277                                 case "TN-FH":
278                                         execution.setVariable("TNFH_NSSI", val.getServiceInstanceId())
279                                         execution.setVariable("TNFH_nssiName", val.getServiceInstanceName())
280                                         break
281                                 case "TN-MH":
282                                         execution.setVariable("TNMH_NSSI", val.getServiceInstanceId())
283                                         execution.setVariable("TNMH_nssiName", val.getServiceInstanceName())
284                                         break
285                                 default:
286                                         logger.error("No expected match found for current domainType "+ key)
287                                         exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current domainType "+ key)
288                         }
289                 }
290                 
291         }
292         def createSliceProfiles = { DelegateExecution execution ->
293                 logger.debug(Prefix+"createSliceProfiles method start")
294                 anNssmfUtils.createSliceProfilesInAai(execution)
295         }
296         def updateRelationshipInAai = { DelegateExecution execution ->
297                 logger.debug(Prefix+"updateRelationshipInAai method start")
298                 String msg = ""
299                 try {
300                         def ANNF_serviceInstanceId = execution.getVariable("ANNF_NSSI")
301                         def TNFH_serviceInstanceId = execution.getVariable("TNFH_NSSI")
302                         def TNMH_serviceInstanceId = execution.getVariable("TNMH_NSSI")
303                         def AN_profileInstanceId = execution.getVariable("sliceProfileId")
304                         def ANNF_profileInstanceId = execution.getVariable("ANNF_sliceProfileInstanceId")
305                         def TNFH_profileInstanceId = execution.getVariable("TNFH_sliceProfileInstanceId")
306                         def TNMH_profileInstanceId = execution.getVariable("TNMH_sliceProfileInstanceId")
307                         String globalSubscriberId = execution.getVariable("globalSubscriberId")
308                         String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
309
310                         Relationship ANNF_relationship = new Relationship()
311                         Relationship TNFH_relationship = new Relationship()
312                         Relationship TNMH_relationship = new Relationship()
313                         
314                         String ANNF_relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${ANNF_profileInstanceId}"
315                         String TNFH_relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNFH_profileInstanceId}"
316                         String TNMH_relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNMH_profileInstanceId}"
317                         
318                         ANNF_relationship.setRelatedLink(ANNF_relatedLink)
319                         ANNF_relationship.setRelatedTo("service-instance")
320                         ANNF_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
321                         TNFH_relationship.setRelatedLink(TNFH_relatedLink)
322                         TNFH_relationship.setRelatedTo("service-instance")
323                         TNFH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
324                         TNMH_relationship.setRelatedLink(TNMH_relatedLink)
325                         TNMH_relationship.setRelatedTo("service-instance")
326                         TNMH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
327                         
328                         // create SliceProfile and NSSI relationship in AAI
329                         anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship,ANNF_serviceInstanceId)
330                         anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship,TNFH_serviceInstanceId)
331                         anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship,TNMH_serviceInstanceId)
332                         anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship,AN_profileInstanceId)
333                         anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship,AN_profileInstanceId)
334                         anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship,AN_profileInstanceId)
335
336                 } catch (BpmnError e) {
337                         throw e
338                 } catch (Exception ex) {
339
340                         msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage()
341                         logger.info(msg)
342                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
343                 }
344         }
345         
346         def processRanNfModifyRsp = { DelegateExecution execution ->
347                 logger.debug(Prefix+"processRanNfModifyRsp method start")
348                 anNssmfUtils.processRanNfModifyRsp(execution)
349         }
350         
351         def prepareTnFhRequest = { DelegateExecution execution ->
352                 logger.debug(Prefix+"prepareTnFhRequest method start")
353
354                 String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_FH", "modify-allocate")
355                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
356                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
357
358                 if (nssmfResponse != null) {
359                         execution.setVariable("nssmfResponse", nssmfResponse)
360                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
361                         execution.setVariable("TNFH_jobId",jobId)
362                 } else {
363                         logger.error("received error message from NSSMF : "+ nssmfResponse)
364                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
365                 }
366                 logger.debug("Exit prepareTnFhRequest")
367
368         }
369         def prepareTnMhRequest = { DelegateExecution execution ->
370                 logger.debug(Prefix+"prepareTnMhRequest method start")
371
372                 String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_MH", "modify-allocate")
373                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
374                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
375
376                 if (nssmfResponse != null) {
377                         execution.setVariable("nssmfResponse", nssmfResponse)
378                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
379                         execution.setVariable("TNMH_jobId",jobId)
380                 } else {
381                         logger.error("received error message from NSSMF : "+ nssmfResponse)
382                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
383                 }
384                 logger.debug("Exit prepareTnMhRequest")
385         }
386         
387         def createFhAllocateNssiJobQuery = { DelegateExecution execution ->
388                 logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
389                 createTnAllocateNssiJobQuery(execution, "TN_FH")
390         }
391         
392         def createMhAllocateNssiJobQuery = { DelegateExecution execution ->
393                 logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
394                 createTnAllocateNssiJobQuery(execution, "TN_MH")
395         }
396         
397         private void createTnAllocateNssiJobQuery(DelegateExecution execution, String domainType) {
398                 EsrInfo esrInfo = new EsrInfo()
399                 esrInfo.setNetworkType("TN")
400                 esrInfo.setVendor("ONAP")
401                 String esrInfoString = objectMapper.writeValueAsString(esrInfo)
402                 execution.setVariable("esrInfo", esrInfoString)
403                 JsonObject serviceInfo = new JsonObject()
404                 
405                 serviceInfo.addProperty("nsiId", execution.getVariable("nsiId"))
406                 String sST = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "sST")
407                 serviceInfo.addProperty("sST", sST)
408                 serviceInfo.addProperty("PLMNIdList", objectMapper.writeValueAsString(execution.getVariable("plmnIdList")))
409                 serviceInfo.addProperty("globalSubscriberId", execution.getVariable("globalSubscriberId"))
410                 serviceInfo.addProperty("subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
411                 serviceInfo.addProperty("serviceInvariantUuid", null)
412                 serviceInfo.addProperty("serviceUuid", null)
413                 if(domainType.equals("TN_FH")) {
414                         serviceInfo.addProperty("nssiId", execution.getVariable("TNFH_NSSI"))
415                         serviceInfo.addProperty("nssiName", execution.getVariable("TNFH_nssiName"))
416                 }else if(domainType.equals("TN_MH")) {
417                         serviceInfo.addProperty("nssiId", execution.getVariable("TNMH_NSSI"))
418                         serviceInfo.addProperty("nssiName", execution.getVariable("TNMH_nssiName"))
419                 }
420                 execution.setVariable("serviceInfo", serviceInfo.toString())
421                 execution.setVariable("responseId", "")
422         }
423         
424         def processFhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
425                 logger.debug(Prefix+"processJobStatusRsp method start")
426                 String jobResponse = execution.getVariable("TNFH_jobResponse")
427                 logger.debug("Job status response "+jobResponse)
428                 String status = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.status")
429                 String nssi = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.nssi")
430                 if(status.equalsIgnoreCase("finished")) {
431                         logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
432                 }
433                 else {
434                         String statusDescription = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.statusDescription")
435                         logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
436                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
437                 }
438         }
439         
440         def processMhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
441                 logger.debug(Prefix+"processJobStatusRsp method start")
442                 String jobResponse = execution.getVariable("TNMH_jobResponse")
443                 logger.debug("Job status response "+jobResponse)
444                 String status = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.status")
445                 String nssi = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.nssi")
446                 if(status.equalsIgnoreCase("finished")) {
447                         logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
448                 }
449                 else {
450                         String statusDescription = jsonUtil.getJsonValue(jobResponse, "responseDescriptor.statusDescription")
451                         logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
452                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
453                 }
454         }
455         
456         def getSliceProfilesFromAai = { DelegateExecution execution ->
457                 logger.debug(Prefix+"getSliceProfilesFromAai method start")
458                 String instanceId = execution.getVariable("sliceProfileId")
459                 String role = "slice-profile-instance"
460                 Map<String,ServiceInstance> ranConstituentSliceProfiles = getRelatedInstancesByRole(execution, role, instanceId)
461                 logger.debug("getSliceProfilesFromAai ranConstituentSliceProfiles : "+ranConstituentSliceProfiles.toString())
462                 ranConstituentSliceProfiles.each { key, val ->
463                         switch(key) {
464                                 case "AN-NF":
465                                         execution.setVariable("ANNF_sliceProfileInstanceId", val.getServiceInstanceId())
466                                         break
467                                 case "TN-FH":
468                                         execution.setVariable("TNFH_sliceProfileInstanceId", val.getServiceInstanceId())
469                                         break
470                                 case "TN-MH":
471                                         execution.setVariable("TNMH_sliceProfileInstanceId", val.getServiceInstanceId())
472                                         break
473                                 default:
474                                         logger.error("No expected match found for current domainType "+ key)
475                                         exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current domainType "+ key)
476                         }
477                 }
478         }
479         
480         def prepareTnFhDeallocateRequest = { DelegateExecution execution ->
481                 logger.debug(Prefix+"prepareTnFhDeallocateRequest method start")
482                 String nssmfRequest = anNssmfUtils.buildDeallocateNssiRequest(execution, "TN_FH")
483                 String nssiId = execution.getVariable("TNFH_NSSI")
484                 execution.setVariable("tnFHNSSIId", nssiId)
485                 String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
486                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
487                                 if (nssmfResponse != null) {
488                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
489                                         execution.setVariable("TN_FH_jobId",jobId)
490                                 } else {
491                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
492                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
493                                 }
494         }
495         
496         def prepareTnMhDeallocateRequest = { DelegateExecution execution ->
497                 logger.debug(Prefix+"prepareTnFhDeallocateRequest method start")
498                 String nssmfRequest = anNssmfUtils.buildDeallocateNssiRequest(execution, "TN_FH")
499                 String nssiId = execution.getVariable("TNFH_NSSI")
500                 execution.setVariable("tnFHNSSIId", nssiId)
501                 String urlString = "/api/rest/provMns/v1/NSS/nssi/" + nssiId
502                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
503                                 if (nssmfResponse != null) {
504                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
505                                         execution.setVariable("TN_MH_jobId",jobId)
506                                 } else {
507                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
508                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
509                                 }
510         }
511         
512         def createFhDeAllocateNssiJobQuery = { DelegateExecution execution ->
513                 logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
514                 createTnAllocateNssiJobQuery(execution, "TN_FH")
515         }
516         
517         def createMhDeAllocateNssiJobQuery = { DelegateExecution execution ->
518                 logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
519                 createTnAllocateNssiJobQuery(execution, "TN_MH")
520         }
521         def deleteFhSliceProfile = { DelegateExecution execution ->
522                 logger.debug(Prefix+"deleteFhSliceProfile method start")
523                 deleteServiceInstanceInAAI(execution,execution.getVariable("TNFH_sliceProfileInstanceId"))
524         }
525         def deleteMhSliceProfile = { DelegateExecution execution ->
526                 logger.debug(Prefix+"deleteMhSliceProfile method start")
527                 deleteServiceInstanceInAAI(execution,execution.getVariable("TNMH_sliceProfileInstanceId"))      
528         }
529         def deleteAnSliceProfile = { DelegateExecution execution ->
530                 logger.debug(Prefix+"deleteAnSliceProfile method start")
531                 deleteServiceInstanceInAAI(execution,execution.getVariable("ANNF_sliceProfileInstanceId"))
532         }
533         /**
534          * update operation status in request db
535          *
536          */
537         def prepareOperationStatusUpdate = { DelegateExecution execution ->
538                 logger.debug(Prefix + "prepareOperationStatusUpdate Start")
539
540                 String serviceId = execution.getVariable("serviceInstanceID")
541                 String jobId = execution.getVariable("jobId")
542                 String nsiId = execution.getVariable("nsiId")
543                 String nssiId = execution.getVariable("serviceInstanceID")
544                 logger.debug("Service Instance serviceId:" + serviceId + " jobId:" + jobId)
545
546                 ResourceOperationStatus updateStatus = new ResourceOperationStatus()
547                 updateStatus.setServiceId(serviceId)
548                 updateStatus.setOperationId(jobId)
549                 updateStatus.setResourceTemplateUUID(nsiId)
550                 updateStatus.setResourceInstanceID(nssiId)
551                 updateStatus.setOperType("Modify")
552                 updateStatus.setProgress("100")
553                 updateStatus.setStatus("finished")
554                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
555
556                 logger.debug(Prefix + "prepareOperationStatusUpdate Exit")
557         }
558
559         def prepareFailedOperationStatusUpdate = { DelegateExecution execution ->
560                 logger.debug(Prefix + "prepareFailedOperationStatusUpdate Start")
561                 
562                 String serviceId = execution.getVariable("serviceInstanceID")
563                 String jobId = execution.getVariable("jobId")
564                 String nsiId = execution.getVariable("nsiId")
565                 String nssiId = execution.getVariable("serviceInstanceID")
566                 logger.debug("Service Instance serviceId:" + serviceId + " jobId:" + jobId)
567
568                 ResourceOperationStatus updateStatus = new ResourceOperationStatus()
569                 updateStatus.setServiceId(serviceId)
570                 updateStatus.setOperationId(jobId)
571                 updateStatus.setResourceTemplateUUID(nsiId)
572                 updateStatus.setResourceInstanceID(nssiId)
573                 updateStatus.setOperType("Modify")
574                 updateStatus.setProgress("0")
575                 updateStatus.setStatus("failed")
576                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
577         }
578         
579         /**
580          * @param execution
581          * @param role            - nssi/slice profile instance
582          * @param instanceId    - id to which the related list to be found
583          * @return
584          */
585         private Map<String,ServiceInstance> getRelatedInstancesByRole(DelegateExecution execution,String role,String instanceId) {
586                 logger.debug("${Prefix} - Fetching related ${role} from AAI")
587                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
588                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
589                 
590                 Map<String,ServiceInstance> relatedInstances = new HashMap<>()
591                 
592                 AAIResourcesClient client = new AAIResourcesClient()
593                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(instanceId))
594                 if (!client.exists(uri)) {
595                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
596                 }
597                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
598                 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
599                 if(si.isPresent()) {
600                 List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
601                 for (Relationship relationship : relationshipList) {
602                         String relatedTo = relationship.getRelatedTo()
603                         if (relatedTo.toLowerCase() == "service-instance") {
604                                 String relatioshipurl = relationship.getRelatedLink()
605                                 String serviceInstanceId =
606                                                 relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
607
608                                 AAIResourcesClient client01 = new AAIResourcesClient()
609                                 AAIResourceUri uri01 = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceInstanceId))
610                                 if (!client.exists(uri01)) {
611                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
612                                                         "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
613                                 }
614                                 AAIResultWrapper wrapper01 = client01.get(uri01, NotFoundException.class)
615                                 Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
616                                 if (serviceInstance.isPresent()) {
617                                         ServiceInstance instance = serviceInstance.get()
618                                         if (role.equalsIgnoreCase(instance.getServiceRole())) {
619                                                 relatedInstances.put(instance.getWorkloadContext(),instance)
620                                         }
621                                 }
622                         }
623                 }
624                 }
625                 logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
626                 return relatedInstances
627         }
628         
629         private ServiceInstance getServiceInstance(DelegateExecution execution, String instanceId) {
630                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
631                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
632                 ServiceInstance serviceInstance = new ServiceInstance()
633                 AAIResourcesClient client = new AAIResourcesClient()
634                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(instanceId))
635                 if (!client.exists(uri)) {
636                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
637                 }
638                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
639                 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
640                 
641                 if(si.isPresent()) {
642                         serviceInstance = si
643                 }
644                 return serviceInstance
645         }
646         private void deleteServiceInstanceInAAI(DelegateExecution execution,String instanceId) {
647                 try {
648                         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("serviceType")).serviceInstance(instanceId))
649                         getAAIClient().delete(serviceInstanceUri)
650                         logger.debug("${Prefix} Exited deleteServiceInstance")
651                 }catch(Exception e){
652                         logger.debug("Error occured within deleteServiceInstance method: " + e)
653                 }
654         }
655 }