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