Fix bugs found in TN Slicing integration involving OOF
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoAllocateAccessNSSI.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.util.List
35 import static org.apache.commons.lang3.StringUtils.isBlank
36 import com.google.gson.JsonObject
37 import com.google.gson.Gson
38 import com.fasterxml.jackson.databind.ObjectMapper
39 import com.google.gson.JsonArray
40 import com.google.gson.JsonParser
41 import org.onap.aai.domain.yang.Relationship
42 import org.onap.aaiclient.client.aai.AAIResourcesClient
43 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
44 import org.onap.so.beans.nsmf.AllocateTnNssi
45 import org.onap.so.bpmn.core.UrnPropertiesReader
46 import org.onap.so.bpmn.core.domain.ServiceDecomposition
47 import org.onap.so.bpmn.core.domain.ServiceInstance
48 import org.onap.so.bpmn.core.domain.ServiceProxy
49 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
50 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
51 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
52 import org.onap.aaiclient.client.aai.AAINamespaceConstants
53 import org.onap.aaiclient.client.aai.AAIObjectType
54 import org.onap.aai.domain.yang.NetworkPolicy
55 import org.onap.aai.domain.yang.NetworkRoute
56 import org.json.JSONArray
57
58 class DoAllocateAccessNSSI extends AbstractServiceTaskProcessor {
59
60         String Prefix="AASS_"
61         ExceptionUtil exceptionUtil = new ExceptionUtil()
62         RequestDBUtil requestDBUtil = new RequestDBUtil()
63         JsonUtils jsonUtil = new JsonUtils()
64         OofUtils oofUtils = new OofUtils()
65         AnNssmfUtils anNssmfUtils = new AnNssmfUtils()
66         ObjectMapper objectMapper = new ObjectMapper();
67         private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
68
69         private static final Logger logger = LoggerFactory.getLogger(DoAllocateAccessNSSI.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                                         +" modelInvariantUuid - "+execution.getVariable("modelInvariantUuid")+
81                                         " modelUuid - "+execution.getVariable("modelUuid")+
82                                         " globalSubscriberId - "+execution.getVariable("globalSubscriberId")+
83                                         " dummyServiceId - "+ execution.getVariable("dummyServiceId")+
84                                         " nsiId - "+execution.getVariable("nsiId")+
85                                         " networkType - "+execution.getVariable("networkType")+
86                                         " subscriptionServiceType - "+execution.getVariable("subscriptionServiceType")+
87                                         " jobId - "+execution.getVariable("jobId")+
88                                         " sliceParams - "+execution.getVariable("sliceParams")+
89                                         " servicename - "+ execution.getVariable("servicename")+
90                                         " sst - "+ execution.getVariable("sst"))
91
92                         //validate slice subnet inputs
93
94                         String sliceParams = execution.getVariable("sliceParams")
95                         String sliceProfile = jsonUtil.getJsonValue(sliceParams, "sliceProfile")
96                         if (isBlank(sliceProfile)) {
97                                 msg = "Input sliceProfile is null"
98                                 logger.debug(msg)
99                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
100                         } else {
101                                 execution.setVariable("sliceProfile", sliceProfile)
102                         }
103                         String sliceProfileId = jsonUtil.getJsonValue(sliceProfile, "sliceProfileId")
104                         def snssaiList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceProfile, "snssaiList"))
105                         def plmnIdList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceProfile, "pLMNIdList"))
106                         String jsonArray = jsonUtil.getJsonValue(sliceProfile, "coverageAreaTAList")
107                         List<Integer> list = new ArrayList<>();
108                         JSONArray arr = new JSONArray(jsonArray);
109                         for (int i = 0; i < arr.length(); i++) {
110                                  int s = (int) arr.get(i);
111                                  list.add(s);
112                         }
113                         def coverageAreaTAList = list;
114
115                         if (isBlank(sliceProfileId) || (snssaiList.empty) || (plmnIdList.empty)
116                         || (coverageAreaTAList.empty)) {
117
118                                 msg = "Mandatory slice profile fields are empty"
119                                 logger.debug(msg)
120                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
121                         } else {
122                                 execution.setVariable("sliceProfileId", sliceProfileId)
123                                 execution.setVariable("snssaiList", snssaiList)
124                                 execution.setVariable("pLMNIdList", plmnIdList)
125                                 execution.setVariable("coverageAreaTAList", coverageAreaTAList)
126                         }
127                         String nsiName = jsonUtil.getJsonValue(sliceParams, "nsiInfo.nsiName")
128                         String scriptName = jsonUtil.getJsonValue(sliceParams, "scriptName")
129                         execution.setVariable("nsiName", nsiName)
130                         execution.setVariable("scriptName", scriptName)
131                         //generate RAN,RAN NF NSSIs - will be re assigned if oof returns existing NSSI
132                         String RANServiceInstanceId = UUID.randomUUID().toString()
133                         String RANNFServiceInstanceId = UUID.randomUUID().toString()
134                         logger.debug("RAN serviceInstance Id "+RANServiceInstanceId)
135                         logger.debug("RAN NF serviceInstance Id "+RANNFServiceInstanceId)                       
136                         execution.setVariable("RANServiceInstanceId", RANServiceInstanceId)
137                         execution.setVariable("RANNFServiceInstanceId", RANNFServiceInstanceId)
138                         execution.setVariable("ranNssiPreferReuse", true)
139                         execution.setVariable("ranNfNssiPreferReuse", true)
140                         execution.setVariable("job_timeout", 10)
141                         
142                         //set BH end point
143                         def BH_endPoints = jsonUtil.getJsonValue(sliceParams, "endPoint")
144                         logger.debug("BH end points list : "+BH_endPoints)
145                         if(isBlank(BH_endPoints)) {
146                                 msg = "End point info is empty"
147                                 logger.debug(msg)
148                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
149                         }else {
150                                 execution.setVariable("bh_endpoint", BH_endPoints)
151                         }
152
153                 } catch(BpmnError e) {
154                         throw e
155                 } catch(Exception ex) {
156                         msg = "Exception in DoAllocateAccessNSSI.preProcessRequest " + ex.getMessage()
157                         logger.debug(msg)
158                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
159                 }
160                 logger.debug(Prefix + "preProcessRequest Exit")
161         }
162
163         /*
164          * Prepare request params for decomposing RAN NSST
165          */
166
167         def prepareDecomposeService = { DelegateExecution execution ->
168                 logger.debug(Prefix+"prepareDecomposeService method start")
169                 String RANServiceInstanceId = execution.getVariable("RANServiceInstanceId")
170                 String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
171                 String modelUuid = execution.getVariable("modelUuid")
172                 String serviceModelInfo = """{
173             "modelInvariantUuid":"${modelInvariantUuid}",
174             "modelUuid":"${modelUuid}",
175             "modelVersion":""
176              }"""
177                 execution.setVariable("serviceModelInfo", serviceModelInfo)
178                 execution.setVariable("serviceInstanceId", RANServiceInstanceId)
179                 logger.debug("serviceModelInfo : "+serviceModelInfo)
180                 logger.debug("Finish RAN NSST prepareDecomposeService")
181         }
182
183         /* process the decompose service(RAN NSST) response
184          * 
185          */
186         def processDecomposition = { DelegateExecution execution ->
187                 logger.debug(Prefix+"processDecomposition method start")
188                 ServiceDecomposition ranNsstServiceDecomposition = execution.getVariable("ranNsstServiceDecomposition")
189                 logger.debug("ranNsstServiceDecomposition : "+ranNsstServiceDecomposition.toString())
190                 //RAN NSST decomposition
191                 String ranModelVersion = ranNsstServiceDecomposition.getModelInfo().getModelVersion()
192                 String ranModelName = ranNsstServiceDecomposition.getModelInfo().getModelName()
193                 String serviceCategory=ranNsstServiceDecomposition.getServiceCategory()
194                 logger.debug("serviceCategory : "+serviceCategory)
195                 List<ServiceProxy> serviceProxyList = ranNsstServiceDecomposition.getServiceProxy()
196                 List<String> nsstInfoList = new ArrayList<>()
197                 for(ServiceProxy serviceProxy : serviceProxyList)
198                 {
199                         String nsstModelUuid = serviceProxy.getSourceModelUuid()
200                         String nsstModelInvariantUuid = serviceProxy.getModelInfo().getModelInvariantUuid()
201                         String name = serviceProxy.getModelInfo().getModelName()
202                         String nsstServiceModelInfo = """{
203                                "UUID":"${nsstModelUuid}",
204                                "invariantUUID":"${nsstModelInvariantUuid}",
205                                "name":"${name}"
206                         }"""
207                         nsstInfoList.add(nsstServiceModelInfo)
208                 }
209                 int currentIndex=0
210                 int maxIndex=nsstInfoList.size()
211                 if(maxIndex < 1)
212                 {
213                         String msg = "Exception in RAN NSST processDecomposition. There is no NSST associated with RAN NSST "
214                         logger.info(msg)
215                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
216                 }
217                 if(maxIndex == 1) {
218                         logger.info("RAN NSST have only RAN NF NSST")
219                         execution.setVariable("ranNfSliceProfile", execution.getVariable("sliceProfile"))
220                         execution.setVariable("IsRANNfAlonePresent", true)
221                 }
222                 execution.setVariable("ranNsstInfoList", objectMapper.writeValueAsString(nsstInfoList))
223                 execution.setVariable("currentIndex",currentIndex)
224                 execution.setVariable("maxIndex",maxIndex)
225                 execution.setVariable("ranModelVersion", ranModelVersion)
226                 execution.setVariable("ranModelName", ranModelName)
227                 logger.debug(Prefix+"processDecomposition maxIndex value - "+maxIndex)
228
229                 execution.setVariable("serviceCategory",serviceCategory)
230         }
231
232         /*
233          * Function to subnet capabilities from nssmf adapter
234          */
235         def getSubnetCapabilities = { DelegateExecution execution ->
236                 logger.debug(Prefix+"getSubnetCapabilities method start")
237
238                 String tnNssmfRequest = anNssmfUtils.buildCreateTNNSSMFSubnetCapabilityRequest()
239
240                 String urlString = "/api/rest/provMns/v1/NSS/subnetCapabilityQuery"
241
242                 String tnNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, tnNssmfRequest)
243
244                 if (tnNssmfResponse != null) {
245                         String FHCapabilities= jsonUtil.getJsonValue(tnNssmfResponse, "TN_FH")
246                         String MHCapabilities = jsonUtil.getJsonValue(tnNssmfResponse, "TN_MH")
247                         execution.setVariable("FHCapabilities",FHCapabilities)
248                         execution.setVariable("MHCapabilities",MHCapabilities)
249
250                 } else {
251                         logger.error("received error message from NSSMF : "+ tnNssmfResponse)
252                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
253                 }
254                 String anNssmfRequest = anNssmfUtils.buildCreateANNFNSSMFSubnetCapabilityRequest()
255
256                 String anNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, anNssmfRequest)
257
258                 if (anNssmfResponse != null) {
259                         String ANNFCapabilities = jsonUtil.getJsonValue(anNssmfResponse, "AN_NF")
260                         execution.setVariable("ANNFCapabilities",ANNFCapabilities)
261
262                 } else {
263                         logger.error("received error message from NSSMF : "+ anNssmfResponse)
264                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
265                 }
266         }
267
268         /*
269          * prepare OOF request for RAN NSSI selection
270          */
271         def prepareOofRequestForRanNSS = { DelegateExecution execution ->
272                 logger.debug(Prefix+"prepareOofRequestForRanNSS method start")
273
274                 String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
275                 logger.debug( "get NSSI option OOF Url: " + urlString)
276                 JsonParser parser = new JsonParser()
277                 //build oof request body
278                 boolean ranNssiPreferReuse = execution.getVariable("ranNssiPreferReuse");
279                 String requestId = execution.getVariable("msoRequestId")
280                 String messageType = "NSISelectionResponse"
281                 Map<String, Object> profileInfo = objectMapper.readValue(execution.getVariable("sliceProfile"), Map.class)
282                 profileInfo.put("sST",execution.getVariable("sst"))
283                 String modelUuid = execution.getVariable("modelUuid")
284                 String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
285                 String modelName = execution.getVariable("ranModelName")
286                 String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
287                 List<String> nsstInfoList =  objectMapper.readValue(execution.getVariable("ranNsstInfoList"), List.class)
288                 JsonArray capabilitiesList = new JsonArray()
289                 String FHCapabilities = execution.getVariable("FHCapabilities")
290                 String MHCapabilities = execution.getVariable("MHCapabilities")
291                 String ANNFCapabilities = execution.getVariable("ANNFCapabilities")
292                 JsonObject FH = new JsonObject()
293                 JsonObject MH = new JsonObject()
294                 JsonObject ANNF = new JsonObject()
295                 FH.addProperty("domainType", "TN_FH")
296                 FH.add("capabilityDetails", (JsonObject) parser.parse(FHCapabilities))
297                 MH.addProperty("domainType", "TN_MH")
298                 MH.add("capabilityDetails", (JsonObject) parser.parse(MHCapabilities))
299                 ANNF.addProperty("domainType", "AN_NF")
300                 ANNF.add("capabilityDetails", (JsonObject) parser.parse(ANNFCapabilities))
301                 capabilitiesList.add(FH)
302                 capabilitiesList.add(MH)
303                 capabilitiesList.add(ANNF)
304
305                 execution.setVariable("nssiSelection_Url", "/api/oof/selection/nsi/v1")
306                 execution.setVariable("nssiSelection_messageType",messageType)
307                 execution.setVariable("nssiSelection_correlator",requestId)
308                 execution.setVariable("nssiSelection_timeout",timeout)
309
310                 String oofRequest = anNssmfUtils.buildSelectRANNSSIRequest(requestId, messageType, modelUuid,modelInvariantUuid,
311                                 modelName, profileInfo, nsstInfoList, capabilitiesList, ranNssiPreferReuse)
312
313                 execution.setVariable("nssiSelection_oofRequest",oofRequest)
314                 logger.debug("Sending request to OOF: " + oofRequest)
315         }
316         /*
317          * process OOF response for RAN NSSI selection
318          */
319         def processOofResponseForRanNSS = { DelegateExecution execution ->
320                 logger.debug(Prefix+"processOofResponseForRanNSS method start")
321                 String oofResponse = execution.getVariable("nssiSelection_asyncCallbackResponse")
322                 String requestStatus = jsonUtil.getJsonValue(oofResponse, "requestStatus")
323                 if(requestStatus.equals("completed")) {
324                         String solutions = jsonUtil.getJsonValue(oofResponse, "solutions")
325                         logger.debug("solutions value : "+solutions)
326                         JsonParser parser = new JsonParser()
327                         JsonArray solution = parser.parse(solutions)
328                         JsonObject sol = solution.get(0)
329                         boolean existingNSI = sol.get("existingNSI").getAsBoolean()
330                         logger.debug("existingNSI value : "+existingNSI)
331                         if(existingNSI) {
332                                 JsonObject sharedNSISolution = sol.get("sharedNSISolution").getAsJsonObject()
333                                 execution.setVariable("sharedRanNSSISolution", sharedNSISolution.toString())
334                                 logger.debug("sharedRanNSSISolution from OOF "+sharedNSISolution)
335                                 String RANServiceInstanceId = sharedNSISolution.get("NSIId").getAsString()
336                                 execution.setVariable("RANServiceInstanceId", RANServiceInstanceId)
337                                 ServiceInstance serviceInstance = new ServiceInstance();
338                                 serviceInstance.setInstanceId(RANServiceInstanceId);
339                                 ServiceDecomposition serviceDecomposition = execution.getVariable("ranNsstServiceDecomposition")
340                                 serviceDecomposition.setServiceInstance(serviceInstance);
341                                 execution.setVariable("ranNsstServiceDecomposition", serviceDecomposition)
342                                 execution.setVariable("isRspRanNssi", true)
343                         }else {
344                                 JsonObject newNSISolution = sol.get("newNSISolution").getAsJsonObject()
345                                 JsonArray sliceProfiles = newNSISolution.get("sliceProfiles").getAsJsonArray()
346                                 logger.debug("RanConstituentSliceProfiles list from OOF "+sliceProfiles)
347                                 execution.setVariable("RanConstituentSliceProfiles", sliceProfiles.toString())
348                         }
349                 }else {
350                         String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
351                         logger.error("received failed status from oof "+ statusMessage)
352                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a failed Async Response from OOF : "+statusMessage)
353                 }
354
355         }
356
357         def prepareModifyAccessNssiInputs = { DelegateExecution execution ->
358                 logger.debug(Prefix+"prepareModifyAccessNssiInputs method start")
359                 String jobId = UUID.randomUUID().toString()
360                 execution.setVariable("modifyRanNssiJobId", jobId)              
361                 String snssaiList = execution.getVariable("snssaiList")
362                 String sliceParams = execution.getVariable("sliceParams")
363                 String sliceProfileId = execution.getVariable("sliceProfileId")
364                 String nsiInfo = jsonUtil.getJsonValue(sliceParams, "nsiInfo")
365                 String scriptName = execution.getVariable("scriptName")
366                 
367                 JsonObject modifySliceParams = new JsonObject()
368                 modifySliceParams.addProperty("modifyAction", "allocate")
369                 modifySliceParams.addProperty("snssaiList", snssaiList)
370                 modifySliceParams.addProperty("sliceProfileId", sliceProfileId)
371                 modifySliceParams.addProperty("nsiInfo", nsiInfo)
372                 
373                 execution.setVariable("modifySliceParams", modifySliceParams.toString())
374                 //create operation status in request db
375                 String nsiId = execution.getVariable("nsiId")
376                 String modelUuid = execution.getVariable("modelUuid")
377                 logger.debug("Generated new job for Service Instance serviceId:" + nsiId + "jobId:" + jobId)
378
379                 ResourceOperationStatus initStatus = new ResourceOperationStatus()
380                 initStatus.setServiceId(nsiId)
381                 initStatus.setOperationId(jobId)
382                 initStatus.setResourceTemplateUUID(modelUuid)
383                 initStatus.setOperType("Modify")
384                 requestDBUtil.prepareInitResourceOperationStatus(execution, initStatus)
385         }
386         
387         def createModifyNssiQueryJobStatus = { DelegateExecution execution ->
388                 logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
389                 JsonObject esrInfo = new JsonObject()
390             esrInfo.addProperty("networkType", "tn")
391             esrInfo.addProperty("vendor", "ONAP_internal")
392
393                 execution.setVariable("esrInfo", esrInfo.toString())
394                 JsonObject serviceInfo = new JsonObject()
395                 serviceInfo.addProperty("nssiId", execution.getVariable("RANServiceInstanceId"))
396                 serviceInfo.addProperty("nsiId", execution.getVariable("nsiId"))
397                 serviceInfo.addProperty("nssiName", execution.getVariable("servicename"))
398                 serviceInfo.addProperty("sST", execution.getVariable("sst"))
399                 serviceInfo.addProperty("PLMNIdList", objectMapper.writeValueAsString(execution.getVariable("pLMNIdList")))
400                 serviceInfo.addProperty("globalSubscriberId", execution.getVariable("globalSubscriberId"))
401                 serviceInfo.addProperty("subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
402                 serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("modelInvariantUuid"))
403                 serviceInfo.addProperty("serviceUuid", execution.getVariable("modelUuid"))
404                 execution.setVariable("serviceInfo", serviceInfo.toString())
405                 execution.setVariable("responseId", "")
406         }
407         def prepareNsstDecomposeService = { DelegateExecution execution ->
408                 logger.debug(Prefix+"prepareNsstDecomposeService method start")
409                 List<String> nsstInfoList = objectMapper.readValue(execution.getVariable("ranNsstInfoList"), List.class)
410                 int currentIndex = execution.getVariable("currentIndex")
411                 int maxIndex = execution.getVariable("maxIndex")
412                 logger.debug(Prefix+"prepareNsstDecomposeService : currentIndex value - "+currentIndex+" maxIndex : "+maxIndex)
413                 if(currentIndex<maxIndex) {
414                         String nsstInfo = nsstInfoList.get(currentIndex)
415                         String modelInvariantUuid = jsonUtil.getJsonValue(nsstInfo, "invariantUUID")
416                         String modelUuid = jsonUtil.getJsonValue(nsstInfo, "UUID")
417                         
418                         String serviceModelInfo = """{
419             "modelInvariantUuid":"${modelInvariantUuid}",
420             "modelUuid":"${modelUuid}",
421             "modelVersion":""
422              }"""
423                         execution.setVariable("serviceModelInfo", serviceModelInfo)
424                         execution.setVariable("serviceInstanceId", "")
425                         logger.debug("serviceModelInfo : "+serviceModelInfo)
426                         currentIndex++
427                         execution.setVariable("currentIndex", currentIndex)
428                 }else {
429                         logger.error("nsstList decomposition error ")
430                         exceptionUtil.buildAndThrowWorkflowException(execution, 1000, "nsstList decomposition error ")
431                 }
432                 
433         }
434         def processNsstDecomposition = { DelegateExecution execution ->
435                 logger.debug(Prefix+"processNsstDecomposition method start")
436                 ServiceDecomposition decomposedNsst = execution.getVariable("nsstServiceDecomposition")
437                 logger.debug("decomposedNsst : "+decomposedNsst.toString())
438                 
439                 String nsstType = decomposedNsst.getServiceCategory() //domainType
440                 String modelVersion = decomposedNsst.getModelInfo().getModelVersion()
441                 String modelName = decomposedNsst.getModelInfo().getModelName()
442                 String modelUuid = decomposedNsst.getModelInfo().getModelUuid()
443                 String modelInvariantUuid = decomposedNsst.getModelInfo().getModelInvariantUuid()
444                 
445                 switch(nsstType) {
446                         case "AN NF NSST":
447                                 execution.setVariable("ANNF_modelInvariantUuid", modelInvariantUuid)
448                                 execution.setVariable("ANNF_modelUuid", modelUuid)
449                                 execution.setVariable("ANNF_modelVersion", modelVersion)
450                                 execution.setVariable("ANNF_modelName", modelName)
451                                 execution.setVariable("ANNF_ServiceDecomposition", decomposedNsst)
452                                 break
453                         case "TN FH NSST":
454                                 execution.setVariable("TNFH_modelInvariantUuid", modelInvariantUuid)
455                                 execution.setVariable("TNFH_modelUuid", modelUuid)
456                                 execution.setVariable("TNFH_modelVersion", modelVersion)
457                                 execution.setVariable("TNFH_modelName", modelName)
458                                 execution.setVariable("TNFH_ServiceDecomposition", decomposedNsst)
459                                 break
460                         case "TN MH NSST":
461                                 execution.setVariable("TNMH_modelInvariantUuid", modelInvariantUuid)
462                                 execution.setVariable("TNMH_modelUuid", modelUuid)
463                                 execution.setVariable("TNMH_modelVersion", modelVersion)
464                                 execution.setVariable("TNMH_modelName", modelName)
465                                 execution.setVariable("TNMH_ServiceDecomposition", decomposedNsst)
466                                 break
467                         default:
468                                 logger.debug("No expected match found for current nsstType")
469                                 logger.error("No expected match found for current nsstType "+ nsstType)
470                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current nsstType "+ nsstType)
471                 }
472                 boolean isAllNsstsDecomposed = false
473                 int currentIndex = execution.getVariable("currentIndex")
474                 int maxIndex = execution.getVariable("maxIndex")
475                 if(currentIndex == maxIndex) {
476                         isAllNsstsDecomposed = true
477                 }
478                 execution.setVariable("isAllNsstsDecomposed", isAllNsstsDecomposed)
479         }
480         /*
481          * prepare OOF request for NF RAN NSSI selection
482          */
483         def prepareOofRequestForRanNfNSS = { DelegateExecution execution ->
484                 logger.debug(Prefix+"prepareOofRequestForRanNfNSS method start")
485                 String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
486                 logger.debug( "get NSSI option OOF Url: " + urlString)
487
488                 //build oof request body
489                 boolean ranNfNssiPreferReuse = execution.getVariable("ranNfNssiPreferReuse");
490                 String requestId = execution.getVariable("msoRequestId")
491                 String serviceCategory = execution.getVariable("serviceCategory")
492                 String messageType = "NSSISelectionResponse"
493                 if(execution.getVariable("maxIndex") > 1) {
494                     List<String> ranConstituentSliceProfiles = jsonUtil.StringArrayToList(execution.getVariable("RanConstituentSliceProfiles") as String)
495                     anNssmfUtils.createDomainWiseSliceProfiles(ranConstituentSliceProfiles, execution)
496                 }
497                 Map<String, Object> profileInfo = objectMapper.readValue(execution.getVariable("ranNfSliceProfile"), Map.class)
498                 profileInfo.put("sST",execution.getVariable("sst"))
499                 String modelUuid = execution.getVariable("ANNF_modelUuid")
500                 String modelInvariantUuid = execution.getVariable("ANNF_modelInvariantUuid")
501                 String modelName = execution.getVariable("ANNF_modelName")
502                 String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
503
504                 execution.setVariable("nssiSelection_Url", "/api/oof/selection/nssi/v1")
505                 execution.setVariable("nssiSelection_messageType",messageType)
506                 execution.setVariable("nssiSelection_correlator",requestId)
507                 execution.setVariable("nssiSelection_timeout",timeout)
508
509                 String oofRequest = oofUtils.buildSelectNSSIRequest(requestId, messageType, modelUuid, modelInvariantUuid, modelName, profileInfo)
510
511                 execution.setVariable("nssiSelection_oofRequest",oofRequest)
512         }
513         /*
514          * process OOF response for RAN NF NSSI selection
515          */
516         def processOofResponseForRanNfNSS = { DelegateExecution execution ->
517                 logger.debug(Prefix+"processOofResponseForRanNfNSS method start")
518                 String oofResponse = execution.getVariable("nfNssiSelection_asyncCallbackResponse")
519                 String requestStatus = jsonUtil.getJsonValue(oofResponse, "requestStatus")
520                 if(requestStatus.equals("completed")) {
521                         String solutions = jsonUtil.getJsonValue(oofResponse, "solutions")
522                         logger.debug("nssi solutions value : "+solutions)
523                         JsonParser parser = new JsonParser()
524                         JsonArray solution = parser.parse(solutions)            
525                         if(solution.size()>=1) {
526                                 JsonObject sol = solution.get(0)
527                                 String ranNfNssiId = sol.get("NSSIId").getAsString()
528                                 String invariantUuid = sol.get("invariantUUID").getAsString()
529                                 String uuid = sol.get("UUID").getAsString()
530                                 String nssiName = sol.get("NSSIName").getAsString()
531                                 execution.setVariable("RANNFServiceInstanceId", ranNfNssiId)
532                                 execution.setVariable("RANNFInvariantUUID", invariantUuid)
533                                 execution.setVariable("RANNFUUID", uuid)
534                                 execution.setVariable("RANNFNssiName", nssiName)
535                                 logger.debug("RANNFServiceInstanceId from OOF "+ranNfNssiId)
536                                 
537                                 ServiceInstance serviceInstance = new ServiceInstance();
538                                 serviceInstance.setInstanceId(ranNfNssiId);
539                                 ServiceDecomposition serviceDecomposition = execution.getVariable("ANNF_ServiceDecomposition")
540                                 serviceDecomposition.setServiceInstance(serviceInstance);
541                                 execution.setVariable("ANNF_ServiceDecomposition", serviceDecomposition)
542                                 execution.setVariable("modifyAction","allocate")
543                                 execution.setVariable("isRspRanNfNssi", true)
544                         }else {
545                                 logger.debug("No solutions returned from OOF .. Create new RAN NF NSSI")
546                         }
547                 }else {
548                         String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
549                         logger.error("received failed status from oof "+ statusMessage)
550                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a failed Async Response from OOF : "+statusMessage)
551                 }
552         }
553
554         def createSliceProfilesInAai = { DelegateExecution execution ->
555                 logger.debug(Prefix+"createSliceProfilesInAai method start")
556                 anNssmfUtils.createSliceProfilesInAai(execution)
557         }
558
559         def processRanNfModifyRsp = { DelegateExecution execution ->
560                 logger.debug(Prefix+"processRanNfModifyRsp method start")
561                 anNssmfUtils.processRanNfModifyRsp(execution)
562                 //create RAN NSSI 
563                 org.onap.aai.domain.yang.ServiceInstance ANServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
564                 //AN instance creation
565                 ANServiceInstance.setServiceInstanceId(execution.getVariable("RANServiceInstanceId"))
566                 String sliceInstanceName = execution.getVariable("servicename")
567                 ANServiceInstance.setServiceInstanceName(sliceInstanceName)
568                 String serviceType = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "sST")
569                 ANServiceInstance.setServiceType(execution.getVariable("sst"))
570                 String serviceStatus = "deactivated"
571                 ANServiceInstance.setOrchestrationStatus(serviceStatus)
572                 String serviceInstanceLocationid = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "pLMNIdList")
573                 ANServiceInstance.setServiceInstanceLocationId(jsonUtil.StringArrayToList(serviceInstanceLocationid).get(0))
574                 String serviceRole = "nssi"
575                 ANServiceInstance.setServiceRole(serviceRole)
576                 List<String> snssaiList = execution.getVariable("snssaiList")
577                 String snssai = snssaiList.get(0)
578                 //ANServiceInstance.setEnvironmentContext(snssai)
579                 String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
580                 String modelUuid = execution.getVariable("modelUuid") as String
581                 ANServiceInstance.setModelInvariantId(modelInvariantUuid)
582                 ANServiceInstance.setModelVersionId(modelUuid)
583                 ANServiceInstance.setEnvironmentContext(execution.getVariable("networkType")) //Network Type
584                 ANServiceInstance.setWorkloadContext("AN") //domain Type
585                 
586                 logger.debug("completed AN service instance build "+ ANServiceInstance.toString())
587                 String msg = ""
588                 try {
589         
590                         AAIResourcesClient client = new AAIResourcesClient()
591                         AAIResourceUri nssiServiceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("subscriptionServiceType")).serviceInstance(execution.getVariable("RANServiceInstanceId")))
592                         client.create(nssiServiceUri, ANServiceInstance)
593         
594                 } catch (BpmnError e) {
595                         throw e
596                 } catch (Exception ex) {
597                         msg = "Exception in AnNssmfUtils.createSliceProfilesInAai " + ex.getMessage()
598                         logger.info(msg)
599                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
600                 }
601                 //end point update
602                 createEndPointsInAai(execution)
603         }
604         
605         def createSdnrRequest = { DelegateExecution execution ->
606                 logger.debug(Prefix+"createSdnrRequest method start")
607                 String callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.message.endpoint") + "/AsyncSdnrResponse/"+execution.getVariable("msoRequestId")
608                 String sdnrRequest = buildSdnrAllocateRequest(execution, "allocate", "instantiateRANSlice", callbackUrl)
609                 execution.setVariable("createNSSI_sdnrRequest", sdnrRequest)
610                 execution.setVariable("createNSSI_timeout", "PT10M")
611                 execution.setVariable("createNSSI_correlator", execution.getVariable("msoRequestId"))
612                 execution.setVariable("createNSSI_messageType", "AsyncSdnrResponse");
613         }
614
615         def processSdnrResponse = { DelegateExecution execution ->
616                 logger.debug(Prefix+"processSdnrResponse method start")
617                 String SDNRResponse = execution.getVariable("SDNR_asyncCallbackResponse")
618                 String status = jsonUtil.getJsonValue(SDNRResponse, "status")
619                 if(status.equalsIgnoreCase("success")) {
620                         String nfIds = jsonUtil.getJsonValue(SDNRResponse, "nfIds")
621                         execution.setVariable("ranNfIdsJson", nfIds)
622                 }else {
623                         String reason = jsonUtil.getJsonValue(SDNRResponse, "reason")
624                         logger.error("received failed status from SDNR "+ reason)
625                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from SDNR "+ reason)
626                 }
627                 logger.debug("response from SDNR "+SDNRResponse)
628         }
629
630         def updateAaiWithRANInstances = { DelegateExecution execution ->
631                 logger.debug(Prefix+"updateAaiWithRANInstances method start")
632                 //create RAN NSSI 
633                 org.onap.aai.domain.yang.ServiceInstance ANServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
634                 org.onap.aai.domain.yang.ServiceInstance ANNFServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
635                 String serviceCategory = execution.getVariable("serviceCategory")
636                 String serviceStatus = "deactivated"
637                 String serviceRole = "nssi"
638                 //AN instance creation
639                 ANServiceInstance.setServiceInstanceId(execution.getVariable("RANServiceInstanceId") as String)
640                 String sliceInstanceName = execution.getVariable("servicename")
641                 ANServiceInstance.setServiceInstanceName(sliceInstanceName)
642                 ANServiceInstance.setServiceType(execution.getVariable("sst") as String)
643                 ANServiceInstance.setOrchestrationStatus(serviceStatus)
644                 String serviceInstanceLocationid = jsonUtil.getJsonValue(execution.getVariable("sliceProfile"), "pLMNIdList") as String
645                 ANServiceInstance.setServiceInstanceLocationId(jsonUtil.StringArrayToList(serviceInstanceLocationid).get(0))            
646                 ANServiceInstance.setServiceRole(serviceRole)
647                 List<String> snssaiList = jsonUtil.StringArrayToList(execution.getVariable("snssaiList") as String)
648                 String snssai = snssaiList.get(0)
649                 String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
650                 String modelUuid = execution.getVariable("modelUuid") as String
651                 ANServiceInstance.setModelInvariantId(modelInvariantUuid)
652                 ANServiceInstance.setModelVersionId(modelUuid)
653                 ANServiceInstance.setEnvironmentContext(execution.getVariable("networkType")) //Network Type
654                 ANServiceInstance.setWorkloadContext("AN")
655                 String serviceFunctionAn = jsonUtil.getJsonValue(execution.getVariable("sliceProfile") as String, "resourceSharingLevel")
656                 ANServiceInstance.setServiceFunction(serviceFunctionAn)
657                 logger.debug("completed AN service instance build " + ANServiceInstance.toString())
658                 //create RAN NF NSSI
659                 ANNFServiceInstance.setServiceInstanceId(execution.getVariable("RANNFServiceInstanceId") as String)
660                 String ANNF_nssiInstanceId = UUID.randomUUID().toString()
661                 sliceInstanceName = "nssi_an_nf_" + ANNF_nssiInstanceId
662                 ANNFServiceInstance.setServiceInstanceName(sliceInstanceName)
663                 ANNFServiceInstance.setServiceType(execution.getVariable("sst") as String)
664                 ANNFServiceInstance.setOrchestrationStatus(serviceStatus)
665                 serviceInstanceLocationid = jsonUtil.getJsonValue(execution.getVariable("ranNfSliceProfile") as String, "pLMNIdList")
666                 ANNFServiceInstance.setServiceInstanceLocationId(jsonUtil.StringArrayToList(serviceInstanceLocationid).get(0))
667                 ANNFServiceInstance.setServiceRole(serviceRole)
668                 snssaiList = jsonUtil.StringArrayToList(execution.getVariable("snssaiList") as String)
669                 snssai = snssaiList.get(0)
670                 ANNFServiceInstance.setEnvironmentContext(execution.getVariable("networkType") as String)
671                 ANNFServiceInstance.setModelInvariantId(execution.getVariable("ANNF_modelInvariantUuid"))
672                 ANNFServiceInstance.setModelVersionId(execution.getVariable("ANNF_modelUuid"))
673                 ANNFServiceInstance.setWorkloadContext("AN_NF")
674                 String serviceFunctionAnnf = jsonUtil.getJsonValue(execution.getVariable("ranNfSliceProfile") as String, "resourceSharingLevel")
675                 ANNFServiceInstance.setServiceFunction(serviceFunctionAnnf)
676                 logger.debug("completed AN service instance build "+ ANNFServiceInstance.toString())
677                 
678                 String msg = ""
679                 try {
680         
681                         AAIResourcesClient client = new AAIResourcesClient()
682                         AAIResourceUri nssiServiceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId") as String).serviceSubscription(execution.getVariable("subscriptionServiceType") as String).serviceInstance(execution.getVariable("RANServiceInstanceId") as String))
683                         client.create(nssiServiceUri, ANServiceInstance)
684         
685                         AAIResourceUri nssiServiceUri1 = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId") as String).serviceSubscription(execution.getVariable("subscriptionServiceType") as String).serviceInstance(execution.getVariable("RANNFServiceInstanceId") as String))
686                         client.create(nssiServiceUri1, ANNFServiceInstance)
687         
688                 } catch (BpmnError e) {
689                         throw e
690                 } catch (Exception ex) {
691                         msg = "Exception in AnNssmfUtils.createSliceProfilesInAai " + ex.getMessage()
692                         logger.info(msg)
693                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
694                 }
695                 //end point update
696                 if (!execution.getVariable("IsRANNfAlonePresent")) {
697                         createEndPointsInAai(execution)
698                 }
699         }
700         def prepareTnFhRequest = { DelegateExecution execution ->
701                 logger.debug(Prefix+"prepareTnFhRequest method start")
702
703                 String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_FH", "allocate")
704                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
705                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
706
707                 if (nssmfResponse != null) {
708                         execution.setVariable("nssmfResponse", nssmfResponse)
709                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
710                         execution.setVariable("TNFH_jobId",jobId)
711                 } else {
712                         logger.error("received error message from NSSMF : "+ nssmfResponse)
713                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
714                 }
715                 logger.debug("Exit prepareTnFhRequest")
716
717         }
718         def prepareTnMhRequest = { DelegateExecution execution ->
719                 logger.debug(Prefix+"prepareTnMhRequest method start")
720
721                 String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_MH", "allocate")
722                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
723                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
724
725                 if (nssmfResponse != null) {
726                         execution.setVariable("nssmfResponse", nssmfResponse)
727                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
728                         execution.setVariable("TNMH_jobId",jobId)
729                 } else {
730                         logger.error("received error message from NSSMF : "+ nssmfResponse)
731                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
732                 }
733                 logger.debug("Exit prepareTnMhRequest")
734         }
735         
736         def createFhAllocateNssiJobQuery = { DelegateExecution execution ->
737                 logger.debug(Prefix+"createFhAllocateNssiJobQuery method start")
738                 createTnAllocateNssiJobQuery(execution, "TN_FH")                
739         }
740         
741         def createMhAllocateNssiJobQuery = { DelegateExecution execution ->
742                 logger.debug(Prefix+"createMhAllocateNssiJobQuery method start")
743                 createTnAllocateNssiJobQuery(execution, "TN_MH")
744         }
745         
746         private void createTnAllocateNssiJobQuery(DelegateExecution execution, String domainType) {
747                 JsonObject esrInfo = new JsonObject()
748             esrInfo.addProperty("networkType", "tn")
749             esrInfo.addProperty("vendor", "ONAP_internal")
750                 execution.setVariable("esrInfo", esrInfo.toString())
751                 JsonObject serviceInfo = new JsonObject()
752                 serviceInfo.addProperty("nsiId", execution.getVariable("nsiId"))
753                 serviceInfo.addProperty("sST", execution.getVariable("sst"))
754                 serviceInfo.addProperty("PLMNIdList", objectMapper.writeValueAsString(execution.getVariable("pLMNIdList")))
755                 serviceInfo.addProperty("globalSubscriberId", execution.getVariable("globalSubscriberId"))
756                 serviceInfo.addProperty("subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
757                 if(domainType.equals("TN_FH")) {
758                         serviceInfo.addProperty("nssiName", execution.getVariable("TNFH_modelName"))
759                         serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("TNFH_modelInvariantUuid"))
760                         serviceInfo.addProperty("serviceUuid", execution.getVariable("TNFH_modelUuid"))
761                 }else if(domainType.equals("TN_MH")) {
762                         serviceInfo.addProperty("nssiName", execution.getVariable("TNMH_modelName"))
763                         serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("TNMH_modelInvariantUuid"))
764                         serviceInfo.addProperty("serviceUuid", execution.getVariable("TNMH_modelUuid"))
765                 }
766                 execution.setVariable("serviceInfo", serviceInfo.toString())
767                 execution.setVariable("responseId", "")
768         }
769         
770         def processFhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
771                 logger.debug(Prefix+"processJobStatusRsp method start")
772                 String jobResponse = execution.getVariable("TNFH_jobResponse")
773                 logger.debug("Job status response "+jobResponse)
774                 String status = jsonUtil.getJsonValue(jobResponse, "status")
775                 String nssi = jsonUtil.getJsonValue(jobResponse, "nssiId")
776                 if(status.equalsIgnoreCase("finished")) {
777                         execution.setVariable("TNFH_NSSI", nssi)
778                         logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
779                 }
780                 else {
781                         String statusDescription = jsonUtil.getJsonValue(jobResponse, "statusDescription")
782                         logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
783                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
784                 }
785         }
786         
787         def processMhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
788                 logger.debug(Prefix+"processJobStatusRsp method start")
789                 String jobResponse = execution.getVariable("TNMH_jobResponse")
790                 logger.debug("Job status response "+jobResponse)
791                 String status = jsonUtil.getJsonValue(jobResponse, "status")
792                 String nssi = jsonUtil.getJsonValue(jobResponse, "nssiId")
793                 if(status.equalsIgnoreCase("finished")) {
794                         execution.setVariable("TNMH_NSSI", nssi)
795                         logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
796                 }
797                 else {
798                         String statusDescription = jsonUtil.getJsonValue(jobResponse, "statusDescription")
799                         logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
800                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
801                 }
802         }
803         
804         def processModifyJobStatusRsp = { DelegateExecution execution ->
805                 logger.debug(Prefix+"processJobStatusRsp method start")
806                 String jobResponse = execution.getVariable("jobResponse")
807                 logger.debug("Job status response "+jobResponse)
808                 String status = jsonUtil.getJsonValue(jobResponse, "status")
809                 String nssi = jsonUtil.getJsonValue(jobResponse, "nssiId")
810                 if(status.equalsIgnoreCase("finished")) {
811                         logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
812                 }
813                 else {
814                         String statusDescription = jsonUtil.getJsonValue(jobResponse, "statusDescription")
815                         logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
816                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
817                 }
818         }
819
820         def updateAairelationships = { DelegateExecution execution ->
821                 logger.debug(Prefix + "updateAairelationships Start")
822                 String serviceCategory = execution.getVariable("serviceCategory")
823                 String msg = ""
824                 if (execution.getVariable("IsRANNfAlonePresent")) {
825                         try {
826                                 def ANNF_serviceInstanceId = execution.getVariable("RANNFServiceInstanceId")
827                                 def AN_profileInstanceId = execution.getVariable("sliceProfileId")
828                                 def AN_NSSI = execution.getVariable("RANServiceInstanceId")
829                                 def ANNF_profileInstanceId = execution.getVariable("ANNF_sliceProfileInstanceId")
830                                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
831                                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
832
833                                 Relationship ANNF_relationship = new Relationship()
834                                 String ANNF_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${ANNF_profileInstanceId}"
835                                 String ANNF_NSSI_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${ANNF_serviceInstanceId}"
836                                 ANNF_relationship.setRelatedLink(ANNF_relatedLink)
837                                 ANNF_relationship.setRelatedTo("service-instance")
838                                 ANNF_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
839                                 anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship, ANNF_serviceInstanceId)
840                                 anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship, AN_profileInstanceId)
841                                 ANNF_relationship.setRelatedLink(ANNF_NSSI_relatedLink)
842                                 anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship, AN_NSSI)
843
844                         } catch (BpmnError e) {
845                                 throw e
846                         } catch (Exception ex) {
847
848                                 msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage()
849                                 logger.info(msg)
850                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
851                         }
852                 }
853                 else {
854                         try {
855                                 def ANNF_serviceInstanceId = execution.getVariable("RANNFServiceInstanceId")
856                                 def TNFH_serviceInstanceId = execution.getVariable("TNFH_NSSI")
857                                 def TNMH_serviceInstanceId = execution.getVariable("TNMH_NSSI")
858                                 def AN_profileInstanceId = execution.getVariable("sliceProfileId")
859                                 def AN_NSSI = execution.getVariable("RANServiceInstanceId")
860                                 def ANNF_profileInstanceId = execution.getVariable("ANNF_sliceProfileInstanceId")
861                                 def TNFH_profileInstanceId = execution.getVariable("TNFH_sliceProfileInstanceId")
862                                 def TNMH_profileInstanceId = execution.getVariable("TNMH_sliceProfileInstanceId")
863                                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
864                                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
865
866                                 Relationship ANNF_relationship = new Relationship()
867                                 Relationship TNFH_relationship = new Relationship()
868                                 Relationship TNMH_relationship = new Relationship()
869
870                                 String ANNF_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${ANNF_profileInstanceId}"
871                                 String TNFH_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNFH_profileInstanceId}"
872                                 String TNMH_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNMH_profileInstanceId}"
873
874                                 String ANNF_NSSI_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${ANNF_serviceInstanceId}"
875                                 String TNFH_NSSI_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNFH_serviceInstanceId}"
876                                 String TNMH_NSSI_relatedLink = "aai/v21/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNMH_serviceInstanceId}"
877
878                                 ANNF_relationship.setRelatedLink(ANNF_relatedLink)
879                                 ANNF_relationship.setRelatedTo("service-instance")
880                                 ANNF_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
881                                 TNFH_relationship.setRelatedLink(TNFH_relatedLink)
882                                 TNFH_relationship.setRelatedTo("service-instance")
883                                 TNFH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
884                                 TNMH_relationship.setRelatedLink(TNMH_relatedLink)
885                                 TNMH_relationship.setRelatedTo("service-instance")
886                                 TNMH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
887
888                                 // create SliceProfile and NSSI relationship in AAI
889                                 anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship, ANNF_serviceInstanceId)
890                                 anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship, TNFH_serviceInstanceId)
891                                 anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship, TNMH_serviceInstanceId)
892                                 anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship, AN_profileInstanceId)
893                                 anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship, AN_profileInstanceId)
894                                 anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship, AN_profileInstanceId)
895
896                                 //create AN NSSI and ANNF,TNFH,TNMH relationship in AAI
897                                 ANNF_relationship.setRelatedLink(ANNF_NSSI_relatedLink)
898                                 TNFH_relationship.setRelatedLink(TNFH_NSSI_relatedLink)
899                                 TNMH_relationship.setRelatedLink(TNMH_NSSI_relatedLink)
900                                 anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship, AN_NSSI)
901                                 anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship, AN_NSSI)
902                                 anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship, AN_NSSI)
903
904                         } catch (BpmnError e) {
905                                 throw e
906                         } catch (Exception ex) {
907
908                                 msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage()
909                                 logger.info(msg)
910                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
911                         }
912                 }
913         }
914         
915         /**
916          * update operation status in request db
917          *
918          */
919         def prepareOperationStatusUpdate = { DelegateExecution execution ->
920                 logger.debug(Prefix + "prepareOperationStatusUpdate Start")
921
922                 String jobId = execution.getVariable("jobId")
923                 String nsiId = execution.getVariable("nsiId")
924                 String modelUuid = execution.getVariable("modelUuid")
925                 String nssiId = execution.getVariable("RANServiceInstanceId")
926                 logger.debug("Service Instance serviceId:" + nsiId + " jobId:" + jobId)
927
928                 ResourceOperationStatus updateStatus = new ResourceOperationStatus()
929                 updateStatus.setServiceId(nsiId)
930                 updateStatus.setOperationId(jobId)
931                 updateStatus.setResourceTemplateUUID(modelUuid)
932                 updateStatus.setResourceInstanceID(nssiId)
933                 updateStatus.setOperType("Allocate")
934                 updateStatus.setProgress("100")
935                 updateStatus.setStatus("finished")
936                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
937
938                 logger.debug(Prefix + "prepareOperationStatusUpdate Exit")
939         }
940
941         def prepareFailedOperationStatusUpdate = { DelegateExecution execution ->
942                 logger.debug(Prefix + "prepareFailedOperationStatusUpdate Start")
943                 
944                 String jobId = execution.getVariable("jobId")
945                 String nsiId = execution.getVariable("nsiId")
946                 String modelUuid = execution.getVariable("modelUuid")
947                 String nssiId = execution.getVariable("RANServiceInstanceId")
948                 logger.debug("Service Instance serviceId:" + nsiId + " jobId:" + jobId)
949
950                 ResourceOperationStatus updateStatus = new ResourceOperationStatus()
951                 updateStatus.setServiceId(nsiId)
952                 updateStatus.setOperationId(jobId)
953                 updateStatus.setResourceTemplateUUID(modelUuid)
954                 updateStatus.setResourceInstanceID(nssiId)
955                 updateStatus.setOperType("Allocate")
956                 updateStatus.setProgress("0")
957                 updateStatus.setStatus("failed")
958                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
959         }
960         
961         private String buildSdnrAllocateRequest(DelegateExecution execution, String action, String rpcName, String callbackUrl) {
962                 
963                 String requestId = execution.getVariable("msoRequestId")
964                 Map<String,Object> sliceProfile = objectMapper.readValue(execution.getVariable("ranNfSliceProfile"), Map.class)
965                 sliceProfile.put("sliceProfileId", execution.getVariable("ANNF_sliceProfileInstanceId"))
966                 sliceProfile.put("maxNumberofConns", sliceProfile.get("maxNumberofPDUSession"))
967                 sliceProfile.put("uLThptPerSlice", sliceProfile.get("expDataRateUL"))
968                 sliceProfile.put("dLThptPerSlice", sliceProfile.get("expDataRateDL"))
969
970                 JsonObject response = new JsonObject()
971                 JsonObject body = new JsonObject()
972                 JsonObject input = new JsonObject()
973                 JsonObject commonHeader = new JsonObject()
974                 JsonObject payload = new JsonObject()
975                 JsonObject payloadInput = new JsonObject()
976                 commonHeader.addProperty("timestamp",new Date(System.currentTimeMillis()).format("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", TimeZone.getDefault()))
977                 commonHeader.addProperty("api-ver", "1.0")
978                 commonHeader.addProperty("originator-id", "testing")
979                 commonHeader.addProperty("request-id", requestId)
980                 commonHeader.addProperty("sub-request-id", "1")
981                 commonHeader.add("flags", new JsonObject())
982                 Gson jsonConverter = new Gson() 
983                 payloadInput.add("sliceProfile", jsonConverter.toJsonTree(sliceProfile))
984                 payloadInput.addProperty("RANNSSIId", execution.getVariable("RANServiceInstanceId"))
985                 payloadInput.addProperty("NSIID", execution.getVariable("nsiId"))
986                 payloadInput.addProperty("RANNFNSSIId", execution.getVariable("RANNFServiceInstanceId"))
987                 payloadInput.addProperty("callbackURL", callbackUrl)
988                 payloadInput.addProperty("globalSubscriberId", execution.getVariable("globalSubscriberId"))
989                 payloadInput.addProperty("subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
990                 payloadInput.add("additionalproperties", new JsonObject())
991                 payload.add("input", payloadInput)
992                 input.add("common-header", commonHeader)
993                 input.addProperty("action", action)
994                 input.addProperty("payload", payload.toString())
995                 body.add("input", input)
996                 response.add("body", body)
997                 response.addProperty("version", "1.0")
998                 response.addProperty("rpc-name", rpcName)
999                 response.addProperty("correlation-id", (requestId+"-1"))
1000                 response.addProperty("type", "request")
1001                 return response.toString()
1002         }
1003         
1004         private void createEndPointsInAai(DelegateExecution execution) {
1005                 String type = "endpoint"
1006                 String function = "transport_EP"
1007                 int prefixLength = 24
1008                 String addressFamily = "ipv4"
1009                 //BH RAN end point update
1010                 String bh_endpoint = execution.getVariable("bh_endpoint")
1011                 String bh_routeId = UUID.randomUUID().toString()
1012                 execution.setVariable("tranportEp_ID_bh", bh_routeId)
1013                 String role = "CU"
1014                 String CU_IpAddress = jsonUtil.getJsonValue(bh_endpoint, "ipAddress")
1015                 String LogicalLinkId = jsonUtil.getJsonValue(bh_endpoint, "logicInterfaceId")
1016                 String nextHopInfo = jsonUtil.getJsonValue(bh_endpoint, "nextHopInfo")
1017                 NetworkRoute bh_ep = new NetworkRoute()
1018                 bh_ep.setRouteId(bh_routeId)
1019                 bh_ep.setFunction(function)
1020                 bh_ep.setRole(role)
1021                 bh_ep.setType(type)
1022                 bh_ep.setIpAddress(CU_IpAddress)
1023                 bh_ep.setLogicalInterfaceId(LogicalLinkId)
1024                 bh_ep.setNextHop(nextHopInfo)
1025                 bh_ep.setPrefixLength(prefixLength)
1026                 bh_ep.setAddressFamily(addressFamily)
1027                 //FH RAN end points update
1028                 //RU
1029                 String RU_routeId = UUID.randomUUID().toString()
1030                 execution.setVariable("tranportEp_ID_RU", RU_routeId)
1031                 role = "RU"
1032                 NetworkRoute RU_ep = new NetworkRoute()
1033                 RU_ep.setRouteId(RU_routeId)
1034                 RU_ep.setFunction(function)
1035                 RU_ep.setRole(role)
1036                 RU_ep.setType(type)
1037                 RU_ep.setIpAddress("192.168.100.4")
1038                 RU_ep.setLogicalInterfaceId("1234")
1039                 RU_ep.setNextHop("networkId-providerId-10-clientId-0-topologyId-2-nodeId-10.1.1.1-ltpId-512")
1040                 RU_ep.setPrefixLength(prefixLength)
1041                 RU_ep.setAddressFamily(addressFamily)
1042                 //DU Ingress
1043                 String DUIN_routeId = UUID.randomUUID().toString()
1044                 execution.setVariable("tranportEp_ID_DUIN", DUIN_routeId)
1045                 role = "DU"
1046                 NetworkRoute DU_ep = new NetworkRoute()
1047                 DU_ep.setRouteId(DUIN_routeId)
1048                 DU_ep.setFunction(function)
1049                 DU_ep.setRole(role)
1050                 DU_ep.setType(type)
1051                 DU_ep.setIpAddress("192.168.100.5")
1052                 DU_ep.setLogicalInterfaceId("1234")
1053                 DU_ep.setNextHop("networkId-providerId-20-clientId-0-topologyId-2-nodeId-10.2.1.2-ltpId-512")
1054                 DU_ep.setPrefixLength(prefixLength)
1055                 DU_ep.setAddressFamily(addressFamily)
1056                 //MH RAN end point update
1057                 //DUEG
1058                 String DUEG_routeId = UUID.randomUUID().toString()
1059                 execution.setVariable("tranportEp_ID_DUEG", DUEG_routeId)
1060                 NetworkRoute DUEG_ep = new NetworkRoute()
1061                 DUEG_ep.setRouteId(DUEG_routeId)
1062                 DUEG_ep.setFunction(function)
1063                 DUEG_ep.setRole(role)
1064                 DUEG_ep.setType(type)
1065                 DUEG_ep.setIpAddress("192.168.100.5")
1066                 DUEG_ep.setLogicalInterfaceId("1234")
1067                 DUEG_ep.setPrefixLength(prefixLength)
1068                 DUEG_ep.setAddressFamily(addressFamily)
1069                 DUEG_ep.setNextHop("networkId-providerId-10-clientId-0-topologyId-2-nodeId-10.1.1.1-ltpId-512")
1070                 //CUIN
1071                 String CUIN_routeId = UUID.randomUUID().toString()
1072                 execution.setVariable("tranportEp_ID_CUIN", CUIN_routeId)
1073                 NetworkRoute CUIN_ep = new NetworkRoute()
1074                 CUIN_ep.setRouteId(CUIN_routeId)
1075                 CUIN_ep.setFunction(function)
1076                 CUIN_ep.setRole(role)
1077                 CUIN_ep.setType(type)
1078                 CUIN_ep.setIpAddress("192.168.100.6")
1079                 CUIN_ep.setLogicalInterfaceId("1234")
1080                 CUIN_ep.setNextHop("networkId-providerId-20-clientId-0-topologyId-2-nodeId-10.2.1.2-ltpId-512")
1081                 CUIN_ep.setPrefixLength(prefixLength)
1082                 CUIN_ep.setAddressFamily(addressFamily)
1083                 try {
1084                         AAIResourcesClient client = new AAIResourcesClient()
1085                         logger.debug("creating bh endpoint . ID : "+bh_routeId+" node details : "+bh_ep.toString())
1086                         AAIResourceUri networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), bh_routeId)
1087                         client.create(networkRouteUri, bh_ep)
1088                         logger.debug("creating RU endpoint . ID : "+RU_routeId+" node details : "+RU_ep.toString())
1089                         networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), RU_routeId)
1090                         client.create(networkRouteUri, RU_ep)
1091                         logger.debug("creating DUIN endpoint . ID : "+DUIN_routeId+" node details : "+DU_ep.toString())
1092                         networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), DUIN_routeId)
1093                         client.create(networkRouteUri, DU_ep)
1094                         logger.debug("creating DUEG endpoint . ID : "+DUEG_routeId+" node details : "+DUEG_ep.toString())
1095                         networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), DUEG_routeId)
1096                         client.create(networkRouteUri, DUEG_ep)
1097                         logger.debug("creating CUIN endpoint . ID : "+CUIN_routeId+" node details : "+CUIN_ep.toString())
1098                         networkRouteUri = AAIUriFactory.createResourceUri( new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkRoute.class), CUIN_routeId)
1099                         client.create(networkRouteUri, CUIN_ep)
1100                         //relationship b/w bh_ep and RAN NSSI
1101                         def AN_NSSI = execution.getVariable("RANServiceInstanceId")
1102                         Relationship relationship = new Relationship()
1103                         String relatedLink = "aai/v21/network/network-routes/network-route/${bh_routeId}"               
1104                         relationship.setRelatedLink(relatedLink)
1105                         relationship.setRelatedTo("network-route")
1106                         relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
1107                         anNssmfUtils.createRelationShipInAAI(execution, relationship, AN_NSSI)
1108                         def ANNF_serviceInstanceId = execution.getVariable("RANNFServiceInstanceId")
1109                         relatedLink = "aai/v21/network/network-routes/network-route/${RU_routeId}"
1110                         relationship.setRelatedLink(relatedLink)
1111                         anNssmfUtils.createRelationShipInAAI(execution, relationship, ANNF_serviceInstanceId)
1112                         relatedLink = "aai/v21/network/network-routes/network-route/${DUIN_routeId}"
1113                         relationship.setRelatedLink(relatedLink)
1114                         anNssmfUtils.createRelationShipInAAI(execution, relationship, ANNF_serviceInstanceId)
1115                         relatedLink = "aai/v21/network/network-routes/network-route/${DUEG_routeId}"
1116                         relationship.setRelatedLink(relatedLink)
1117                         anNssmfUtils.createRelationShipInAAI(execution, relationship, ANNF_serviceInstanceId)
1118                         relatedLink = "aai/v21/network/network-routes/network-route/${CUIN_routeId}"
1119                         relationship.setRelatedLink(relatedLink)
1120                         anNssmfUtils.createRelationShipInAAI(execution, relationship, ANNF_serviceInstanceId)
1121                 } catch (BpmnError e) {
1122                 throw e
1123         } catch (Exception ex) {
1124                 String msg = "Exception in createEndPointsInAai " + ex.getMessage()
1125                 logger.info(msg)
1126                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
1127         }
1128         }
1129 }
1130