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