67845910ebbdf7091c85142a279468fb48ed1913
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateCommunicationService.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  # Copyright (c) 2019, CMCC Technologies Co., Ltd.
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 groovy.json.JsonSlurper
24 import org.camunda.bpm.engine.delegate.BpmnError
25 import org.camunda.bpm.engine.delegate.DelegateExecution
26 import org.json.JSONObject
27 import org.onap.aai.domain.yang.Relationship
28 import org.onap.aai.domain.yang.ServiceInstance
29 import org.onap.aaiclient.client.aai.AAIResourcesClient
30 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
31 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
32 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
33 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
34 import org.onap.so.bpmn.common.scripts.ExceptionUtil
35 import org.onap.so.bpmn.common.scripts.MsoUtils
36 import org.onap.so.bpmn.common.scripts.RequestDBUtil
37 import org.onap.so.bpmn.core.UrnPropertiesReader
38 import org.onap.so.bpmn.core.WorkflowException
39 import org.onap.so.bpmn.core.domain.ServiceDecomposition
40 import org.onap.so.bpmn.core.domain.ServiceInfo
41 import org.onap.so.bpmn.core.domain.ServiceProxy
42 import org.onap.so.bpmn.core.json.JsonUtils
43 import org.onap.so.db.request.beans.OperationStatus
44 import org.slf4j.Logger
45 import org.slf4j.LoggerFactory
46 import org.springframework.web.util.UriUtils
47
48 import static org.apache.commons.lang3.StringUtils.isBlank
49
50 /**
51  * This groovy class supports the <class>DoCreateCommunicationService.bpmn</class> process.
52  * AlaCarte flow for 1702 ServiceInstance Create
53  *
54  */
55 class CreateCommunicationService extends AbstractServiceTaskProcessor {
56
57     String Prefix="CCS_"
58
59     ExceptionUtil exceptionUtil = new ExceptionUtil()
60
61     RequestDBUtil requestDBUtil = new RequestDBUtil()
62
63     JsonUtils jsonUtil = new JsonUtils()
64
65     AAIResourcesClient client = getAAIClient()
66
67     private static final Logger logger = LoggerFactory.getLogger(CreateCommunicationService.class)
68
69     @Override
70     void preProcessRequest(DelegateExecution execution) {
71         logger.debug(Prefix + "preProcessRequest Start")
72         execution.setVariable("prefix", Prefix)
73         execution.setVariable("startTime", System.currentTimeMillis())
74         def msg
75         //execution.setVariable("bpmnRequest", InputString)
76         try {
77             // get request input
78             String siRequest = execution.getVariable("bpmnRequest")
79             logger.debug(siRequest)
80
81             //String requestId = execution.getVariable("mso-request-id")
82             String requestId = execution.getVariable("mso-request-id")
83             execution.setVariable("msoRequestId", requestId)
84             logger.debug("Input Request:" + siRequest + " reqId:" + requestId)
85
86             String serviceInstanceId = execution.getVariable("serviceInstanceId")
87             if (isBlank(serviceInstanceId)) {
88                 serviceInstanceId = UUID.randomUUID().toString()
89             }
90             logger.debug("Generated new Service Instance:" + serviceInstanceId)
91             serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8")
92             execution.setVariable("serviceInstanceId", serviceInstanceId)
93
94             //subscriberInfo
95             String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId")
96             if (isBlank(globalSubscriberId)) {
97                 msg = "Input globalSubscriberId' is null"
98                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
99             } else {
100                 execution.setVariable("globalSubscriberId", globalSubscriberId)
101             }
102
103             //requestInfo
104             execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source"))
105             execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName"))
106             execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback"))
107             String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
108             if (isBlank(productFamilyId))
109             {
110                 msg = "Input productFamilyId is null"
111                 logger.debug(msg)
112                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
113             } else {
114                 execution.setVariable("productFamilyId", productFamilyId)
115             }
116
117             //modelInfo
118             String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
119             if (isBlank(serviceModelInfo)) {
120                 msg = "Input serviceModelInfo is null"
121                 logger.debug(msg)
122                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
123             } else
124             {
125                 execution.setVariable("csServiceModelInfo", serviceModelInfo)
126             }
127
128             logger.debug("modelInfo: " + serviceModelInfo)
129
130             //requestParameters, subscriptionServiceType is 5G
131             String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType")
132             if (isBlank(subscriptionServiceType)) {
133                 msg = "Input subscriptionServiceType is null"
134                 logger.debug(msg)
135                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
136             } else {
137                 // todo: in create e2e interface, this value is write "MOG", so write it as "5G"
138                 execution.setVariable("subscriptionServiceType", "5G")
139             }
140
141
142             /*
143              * Extracting User Parameters from incoming Request and converting into a Map
144              */
145             def jsonSlurper = new JsonSlurper()
146
147             Map reqMap = jsonSlurper.parseText(siRequest) as Map
148
149             //InputParams
150             def userParamsList = reqMap.requestDetails?.requestParameters?.userParams
151
152             Map<String, String> inputMap = [:]
153             if (userParamsList) {
154                 for (def i=0; i<userParamsList.size(); i++) {
155                     def userParams1 = userParamsList.get(i)
156                     userParams1.each { param -> inputMap.put(param.key, param.value)}
157                 }
158             }
159
160             logger.debug("User Input Parameters map: " + inputMap.toString())
161             execution.setVariable("serviceInputParams", inputMap)
162             execution.setVariable("uuiRequest", inputMap.get("UUIRequest"))
163             execution.setVariable("isAllNSMFFinished", "false")
164             String operationId = UUID.randomUUID().toString()
165             execution.setVariable("operationId", operationId)
166
167         } catch(BpmnError e) {
168             throw e
169         } catch(Exception ex) {
170             msg = "Exception in CreateCommunicationService.preProcessRequest " + ex.getMessage()
171             logger.debug(msg)
172             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
173         }
174         logger.debug(Prefix + "preProcessRequest Exit")
175     }
176
177
178     /**
179      * create operation status in request db
180      *
181      * Init the Operation Status
182      */
183     def prepareInitOperationStatus = { DelegateExecution execution ->
184         logger.debug(Prefix + "prepareInitOperationStatus Start")
185
186         String serviceId = execution.getVariable("serviceInstanceId")
187         //operationId is generated
188         String operationId = execution.getVariable("operationId")
189         logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId)
190
191         OperationStatus initStatus = new OperationStatus()
192         initStatus.setServiceId(serviceId)
193         initStatus.setOperationId(operationId)
194         initStatus.setOperation("CREATE")
195         initStatus.setUserId(execution.getVariable("globalSubscriberId") as String)
196         initStatus.setResult("processing")
197         initStatus.setProgress("0")
198         initStatus.setReason("")
199         initStatus.setOperationContent("communication service create operation start")
200
201         requestDBUtil.prepareUpdateOperationStatus(execution, initStatus)
202
203         logger.debug(Prefix + "prepareInitOperationStatus Exit")
204     }
205
206
207     /**
208      * return sync response
209      */
210     def sendSyncResponse = { DelegateExecution execution ->
211         logger.debug(Prefix + "sendSyncResponse Start")
212         try {
213             String operationId = execution.getVariable("operationId")
214             String serviceInstanceId = execution.getVariable("serviceInstanceId")
215             String createServiceRestRequest = """
216                     {
217                         "service": {
218                             "serviceId":"${serviceInstanceId}",
219                             "operationId":"${operationId}"
220                         }
221                     }
222                     """.trim().replaceAll(" ", "")
223
224             logger.debug("sendSyncResponse to APIH:" + "\n" + createServiceRestRequest)
225             sendWorkflowResponse(execution, 202, createServiceRestRequest)
226
227             execution.setVariable("sentSyncResponse", true)
228         } catch (Exception ex) {
229             String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
230             logger.debug(msg)
231             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
232         }
233         logger.debug(Prefix + "sendSyncResponse Exit")
234     }
235
236
237     /**
238      * query e2e service
239      * @param execution
240      */
241     def prepareDoComposeE2E = { DelegateExecution execution ->
242         logger.debug(Prefix + "prepareDoComposeE2E Start")
243         try {
244             ServiceDecomposition serviceDecomposition = execution.getVariable(
245                     "csServiceDecomposition") as ServiceDecomposition
246
247             logger.debug("serviceDecomposition is:" + serviceDecomposition.toJsonString())
248
249             List<ServiceProxy> serviceProxies = serviceDecomposition.getServiceProxy()
250             String sourceModelUuid = serviceProxies.get(0).getSourceModelUuid()
251
252             JSONObject queryJson = new JSONObject()
253             queryJson.put("modelUuid", sourceModelUuid)
254
255             execution.setVariable("e2eServiceModelInfo", queryJson.toString())
256         } catch (BpmnError e) {
257             throw e
258         } catch (Exception ex) {
259             String msg = "Exception in CreateCommunicationService.prepareDoComposeE2E. " + ex.getMessage()
260             logger.info(msg)
261             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
262         }
263
264         logger.debug(Prefix + "prepareDoComposeE2E Exit")
265     }
266
267
268     /**
269      * parse communication service params from request
270      * @param execution
271      */
272     def parseCSParamsFromReq = { DelegateExecution execution ->
273         logger.debug(Prefix + "parseCSParamsFromReq Start")
274         try {
275             //1. CMS info
276
277             String modelInfo = execution.getVariable("csServiceModelInfo")
278             String modelInvariantUuid = jsonUtil.getJsonValue(modelInfo, "modelInvariantUuid")
279             String modelUuid = jsonUtil.getJsonValue(modelInfo, "modelUuid")
280
281             //String modelInvariantUuid = execution.getVariable("modelInvariantId")
282             //String modelUuid = execution.getVariable("modelUuid")
283             String uuiRequest = execution.getVariable("uuiRequest")
284             String useInterval = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.useInterval")
285             String csServiceName = jsonUtil.getJsonValue(uuiRequest, "service.name")
286             String csServiceDescription = jsonUtil.getJsonValue(uuiRequest, "service.description")
287
288             execution.setVariable("modelInvariantUuid", modelInvariantUuid)
289             execution.setVariable("modelUuid", modelUuid)
290             execution.setVariable("useInterval", useInterval)
291             execution.setVariable("csServiceName", csServiceName)
292             execution.setVariable("csServiceDescription", csServiceDescription)
293
294
295             //2. profile info
296             Integer expDataRateDL = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.expDataRateDL") as Integer
297             Integer expDataRateUL = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.expDataRateUL") as Integer
298             Integer latency = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.latency") as Integer
299             Integer maxNumberOfUEs = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.maxNumberofUEs") as Integer
300             String uEMobilityLevel = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.uEMobilityLevel")
301             String resourceSharingLevel = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.resourceSharingLevel")
302             String coverageArea = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.coverageAreaList")
303
304             // from template construct input map
305             //String cstTemplate = execution.getVariable("cstTemplate")
306             ServiceDecomposition csServiceDecomposition = execution.getVariable(
307                     "csServiceDecomposition") as ServiceDecomposition
308             //String csServiceType = jsonUtil.getJsonValue(cstTemplate, "serviceResources.serviceType")
309             String csServiceType = csServiceDecomposition.getServiceType()
310             execution.setVariable("csServiceType", csServiceType)
311
312             //String cstTemplateInfo = jsonUtil.getJsonValue(cstTemplate, "serviceResources.serviceInfo.serviceInput")
313             ServiceInfo csServiceInfo = csServiceDecomposition.getServiceInfo()
314             String cstTemplateInfo = csServiceInfo.getServiceProperties()
315
316             List<String> csInputs = jsonUtil.StringArrayToList(cstTemplateInfo)
317
318             Map<String, ?> csInputMap = new HashMap<>()
319             for (String csInput : csInputs) {
320                 def value
321                 if (jsonUtil.getJsonValue(csInput, "type") == "integer") {
322                     value = jsonUtil.getJsonValue(csInput, "default")
323                     csInputMap.put(jsonUtil.getJsonValue(csInput, "name"), isBlank(value) ? 0 : (value as Integer))
324                 } else if (jsonUtil.getJsonValue(csInput, "type") == "string") {
325                     csInputMap.put(jsonUtil.getJsonValue(csInput, "name"),
326                             jsonUtil.getJsonValue(csInput, "default"))
327                 }
328             }
329             csInputMap.put("expDataRateDL", expDataRateDL)
330             csInputMap.put("expDataRateUL", expDataRateUL)
331             csInputMap.put("latency", latency)
332             csInputMap.put("maxNumberofUEs", maxNumberOfUEs)
333             csInputMap.put("uEMobilityLevel", uEMobilityLevel)
334             csInputMap.put("resourceSharingLevel", resourceSharingLevel)
335             csInputMap.put("coverageAreaTAList", coverageArea)
336             csInputMap.put("useInterval", useInterval)
337
338             execution.setVariable("csInputMap", csInputMap)
339         } catch (BpmnError e) {
340             throw e
341         } catch (Exception ex) {
342             String msg = "Exception in CreateCommunicationService.parseCSParamsFromReq. " + ex.getMessage()
343             logger.info(msg)
344             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
345         }
346         logger.debug(Prefix + "parseCSParamsFromReq Exit")
347     }
348
349
350     /**
351      * get E2EST id through CST id and change communication profile to E2E service profile
352      * 1. get E2EST id from cst
353      * 1.1 source service id
354      * 1.2 source service
355      * 1.3 source service input, init e2e profile
356      */
357     def generateE2EServiceProfile = { DelegateExecution execution ->
358         logger.debug(Prefix + "generateE2EServiceProfile Start")
359         try {
360             ServiceDecomposition e2eServiceDecomposition = execution.getVariable(
361                     "e2eServiceDecomposition") as ServiceDecomposition
362             String e2estTemplateInfo = e2eServiceDecomposition.getServiceInfo().getServiceProperties()
363
364             List<String> e2eInputs = jsonUtil.StringArrayToList(e2estTemplateInfo)
365
366             Map<String, ?> csInputMap = execution.getVariable("csInputMap") as Map
367             Map<String, ?> e2eInputMap = new HashMap<>()
368             String key
369             def value
370
371
372             for (String e2eInput in e2eInputs) {
373                 key = jsonUtil.getJsonValue(e2eInput, "name")
374                 String type = jsonUtil.getJsonValue(e2eInput, "type")
375                 if (type == "integer") {
376                     def temp
377                     value = csInputMap.containsKey(key) ? csInputMap.getOrDefault(key, 0) : (isBlank(temp = jsonUtil.getJsonValue(e2eInput, "default")) ? 0 : temp)
378
379                     e2eInputMap.put(key, value as Integer)
380                 } else if(type == "string") {
381                     e2eInputMap.put(key, csInputMap.containsKey(key)
382                             ? csInputMap.getOrDefault(key, null) : (jsonUtil.getJsonValue(e2eInput, "default")))
383
384                 }
385             }
386
387             //TODO temp solution
388             e2eInputMap.put("sNSSAI", execution.getVariable("sNSSAI_id"))
389                 e2eInputMap.put("sST", execution.getVariable("csServiceType"))
390
391             Integer activityFactor = 60
392             Integer random = new Random().nextInt(5) + 2
393             Integer dLThptPerUE = Integer.parseInt(csInputMap.get("expDataRateDL").toString())
394             Integer uLThptPerUE = Integer.parseInt(csInputMap.get("expDataRateUL").toString())
395             Integer maxNumberofUEs = Integer.parseInt(csInputMap.get("maxNumberofUEs").toString())
396             Integer dLThptPerSlice = dLThptPerUE * maxNumberofUEs * activityFactor * random
397             Integer uLThptPerSlice = uLThptPerUE * maxNumberofUEs * activityFactor * random
398             Integer maxNumberofConns = maxNumberofUEs * activityFactor * 3
399
400             e2eInputMap.put("jitter", 10)
401             e2eInputMap.put("activityFactor", activityFactor)
402             e2eInputMap.put("maxNumberofUEs", maxNumberofUEs)
403             e2eInputMap.put("dLThptPerUE", dLThptPerUE)
404             e2eInputMap.put("uLThptPerUE", uLThptPerUE)
405             e2eInputMap.put("dLThptPerSlice", dLThptPerSlice)
406             e2eInputMap.put("uLThptPerSlice", uLThptPerSlice)
407             e2eInputMap.put("maxNumberofConns", maxNumberofConns)
408             e2eInputMap.put("coverageAreaTAList", csInputMap.get("coverageAreaList"))
409
410             execution.setVariable("e2eInputMap", e2eInputMap)
411             execution.setVariable("e2eServiceType", e2eServiceDecomposition.getServiceType())
412             execution.setVariable("e2eModelInvariantUuid", e2eServiceDecomposition.getModelInfo().getModelInvariantUuid())
413             execution.setVariable("e2eModelUuid", e2eServiceDecomposition.getModelInfo().getModelUuid())
414
415         } catch (BpmnError e) {
416             throw e
417         } catch (Exception ex) {
418             String msg = "Exception in DoCreateE2EServiceInstance.createRelationShipInAAI. " + ex.getMessage()
419             logger.info(msg)
420             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
421         }
422
423         logger.debug(Prefix + "generateE2EServiceProfile Exit")
424     }
425
426
427     /**
428      * call createE2EService get operation id,
429      * created/processing
430      */
431     def preRequestSend2NSMF(DelegateExecution execution) {
432         logger.debug(Prefix + "preRequestSend2NSMF Start")
433         try {
434
435             //String NSMF_endpoint = "/onap/so/infra/e2eServiceInstances/v3"
436             def NSMF_endpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
437             def url = NSMF_endpoint + "/e2eServiceInstances/v3"
438             execution.setVariable("NSMF_endpoint", url)
439             //get from model catalog inputs
440             String payload = """
441                 {
442                     "service":{
443                         "name": "${execution.getVariable("csServiceName")}",
444                         "description": "e2eService of ${execution.getVariable("modelUuid")}",
445                         "serviceInvariantUuid": "${execution.getVariable("e2eModelInvariantUuid")}",
446                         "serviceUuid": "${execution.getVariable("e2eModelUuid")}",
447                         "globalSubscriberId": "${execution.getVariable("globalSubscriberId")}",
448                         "serviceType": "${execution.getVariable("subscriptionServiceType")}",
449                         "parameters":{
450                             "requestInputs": ${execution.getVariable("e2eInputMap") as JSONObject}
451                         }
452                     }
453                 }
454             """
455             execution.setVariable("CSMF_NSMFRequest", payload.replaceAll("\\s+", ""))
456
457         } catch (BpmnError e) {
458             throw e
459         } catch (Exception ex) {
460             String msg = "Exception in CreateCommunicationService.preRequestSend2NSMF. " + ex.getMessage()
461             logger.error(msg)
462             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
463         }
464
465         logger.debug(Prefix + "preRequestSend2NSMF Exit")
466     }
467
468
469     def processNSMFResponse = { DelegateExecution execution ->
470         logger.debug(Prefix + "processNSMFResponse Start")
471         //oof
472         try {
473             def CSMF_NSMFResponseCode = execution.getVariable("CSMF_NSMFResponseCode") as Integer
474             if (CSMF_NSMFResponseCode >= 200 && CSMF_NSMFResponseCode < 400) {
475                 def CSMF_NSMFResponse = execution.getVariable("CSMF_NSMFResponse") as String
476                 def e2eServiceInstanceId = jsonUtil.getJsonValue(CSMF_NSMFResponse, "service.serviceId")
477                 def e2eOperationId = jsonUtil.getJsonValue(CSMF_NSMFResponse, "service.operationId")
478
479                 execution.setVariable("e2eServiceInstanceId", e2eServiceInstanceId)
480                 execution.setVariable("e2eOperationId", e2eOperationId)
481                 execution.setVariable("ProcessNsmfSuccess", "OK")
482             } else {
483                 execution.setVariable("ProcessNsmfSuccess", "ERROR")
484                 execution.setVariable("operationStatus", "error")
485                 execution.setVariable("operationContent",
486                         "communication service create operation error: nsmf response fail")
487                 execution.setVariable("orchestrationStatus", "error")
488             }
489
490         } catch (BpmnError e) {
491             throw e
492         } catch (Exception ex) {
493             String msg = "Exception in " + Prefix + "processOOFResponse. " + ex.getMessage()
494             logger.info(msg)
495             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
496         }
497         logger.debug(Prefix + "processNSMFResponse Exit")
498     }
499
500
501     /**
502      * create communication service and e2e service relationship
503      *
504      */
505     def createCSAndSSRelationship = { DelegateExecution execution ->
506         logger.debug(Prefix + "createCSAndSSRelationship Start")
507         String msg = ""
508         try {
509             def e2eServiceInstanceId = execution.getVariable("e2eServiceInstanceId")
510             String globalSubscriberId = execution.getVariable("globalSubscriberId")
511             String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
512
513             Relationship relationship = new Relationship()
514             String relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${e2eServiceInstanceId}"
515             relationship.setRelatedLink(relatedLink)
516
517             // create CS and SS relationship in AAI
518             createRelationShipInAAI(execution, relationship)
519
520         } catch (BpmnError e) {
521             throw e
522         } catch (Exception ex) {
523
524             msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage()
525             logger.info(msg)
526             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
527         }
528         logger.debug(Prefix + "createCSAndSSRelationship Exit")
529     }
530
531
532     /**
533      * prepare update operation status to 50% after create relationship in aai
534      * @param execution
535      */
536     def prepareUpdateOperationStatus = { DelegateExecution execution ->
537         logger.debug(Prefix + "prepareUpdateOperationStatus Start")
538         // update status creating
539         OperationStatus status = new OperationStatus()
540         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
541         status.setOperationId(execution.getVariable("operationId") as String)
542         status.setOperation("CREATE")
543         status.setResult("processing")
544         status.setProgress("20")
545         status.setOperationContent("communication service create operation processing: waiting nsmf service create finished")
546         status.setUserId(execution.getVariable("globalSubscriberId") as String)
547
548         requestDBUtil.prepareUpdateOperationStatus(execution, status)
549         logger.debug(Prefix + "prepareUpdateOperationStatus Exit")
550     }
551
552
553     /**
554      * create relationship in AAI
555      */
556     private createRelationShipInAAI = { DelegateExecution execution, final Relationship relationship ->
557         logger.debug(Prefix + "createRelationShipInAAI Start")
558         String msg
559         try {
560             String serviceInstanceId = execution.getVariable("serviceInstanceId")
561             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("subscriptionServiceType")).serviceInstance(serviceInstanceId)).relationshipAPI()
562             client.create(uri, relationship)
563
564         } catch (BpmnError e) {
565             throw e
566         } catch (Exception ex) {
567             msg = "Exception in CreateCommunicationService.createRelationShipInAAI. " + ex.getMessage()
568             logger.info(msg)
569             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
570         }
571         logger.debug(Prefix + "createRelationShipInAAI Exit")
572
573     }
574
575
576     def prepareCallCheckProcessStatus = { DelegateExecution execution ->
577         logger.debug(Prefix + "prepareCallCheckProcessStatus Start")
578
579         def successConditions = new ArrayList<>()
580         successConditions.add("finished")
581         execution.setVariable("successConditions", successConditions)
582
583         def errorConditions = new ArrayList<>()
584         errorConditions.add("error")
585         execution.setVariable("errorConditions", errorConditions)
586
587         execution.setVariable("processServiceType", "communication service")
588
589         execution.setVariable("subOperationType", "CREATE")
590
591         execution.setVariable("timeOut", 3 * 60 * 60 * 1000)
592
593         def successParamMap = new HashMap<String, Object>()
594         successParamMap.put("orchestrationStatus", "deactivated")
595
596         execution.setVariable("successParamMap", successParamMap)
597
598         def errorParamMap = new HashMap<String, Object>()
599         errorParamMap.put("orchestrationStatus", "error")
600
601         execution.setVariable("errorParamMap", errorParamMap)
602
603         def timeOutParamMap = new HashMap<String, Object>()
604         timeOutParamMap.put("orchestrationStatus", "error")
605
606         execution.setVariable("timeOutParamMap", timeOutParamMap)
607
608         execution.setVariable("initProgress", 20)
609         execution.setVariable("endProgress", 90)
610
611         logger.debug(Prefix + "prepareCallCheckProcessStatus Exit")
612     }
613
614
615     /**
616      * prepare update operation status to complete after NSMF process success
617      * @param execution
618      */
619     def prepareCompleteStatus = { DelegateExecution execution ->
620         logger.debug(Prefix + "prepareCompleteStatus Start")
621         OperationStatus status = new OperationStatus()
622         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
623         status.setOperationId(execution.getVariable("operationId") as String)
624         status.setOperation("CREATE")
625         status.setResult(execution.getVariable("operationStatus") as String)
626         status.setProgress("100")
627         status.setOperationContent(execution.getVariable("operationContent") as String)
628         status.setUserId(execution.getVariable("globalSubscriberId") as String)
629
630         requestDBUtil.prepareUpdateOperationStatus(execution, status)
631         logger.debug("prepareCompleteStatus end, serviceInstanceId: " + execution.getVariable("serviceInstanceId")
632                 + ", operationId: " + execution.getVariable("operationId"))
633         logger.debug(Prefix + "prepareCompleteStatus Exit")
634     }
635
636
637     /**
638      * update NSMF complete status to AAI when the NSMF process finished
639      * @param execution
640      */
641     def updateFinishStatusInAAI = { DelegateExecution execution ->
642         logger.debug(Prefix + "updateFinishStatusInAAI Start")
643         String msg
644         try {
645
646             String serviceInstanceId = execution.getVariable("serviceInstanceId")
647             String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
648             String globalSubscriberId = execution.getVariable("globalSubscriberId")
649             String orchestrationStatus = execution.getVariable("orchestrationStatus")
650             // create service
651             ServiceInstance csi = new ServiceInstance()
652             csi.setOrchestrationStatus(orchestrationStatus)
653             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceInstanceId))
654             client.update(uri, csi)
655             logger.debug(Prefix + "updateFinishStatusInAAI update communication service status to deactivated")
656
657         } catch (BpmnError e) {
658             throw e
659         } catch (Exception ex) {
660             msg = "Exception in complete communication service " + ex.getMessage()
661             logger.debug(msg)
662             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
663         }
664         logger.debug(Prefix + "updateFinishStatusInAAI Exit")
665     }
666
667
668     public sendSyncError = { DelegateExecution execution ->
669         logger.debug("sendSyncError Start")
670         try {
671             String errorMessage
672             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
673                 WorkflowException wfe = execution.getVariable("WorkflowException") as WorkflowException
674                 errorMessage = wfe.getErrorMessage()
675             } else {
676                 errorMessage = "Sending Sync Error."
677             }
678
679             String buildWorkflowException =
680                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
681                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
682                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
683                                    </aetgt:WorkflowException>"""
684
685             logger.debug(buildWorkflowException)
686             sendWorkflowResponse(execution, 500, buildWorkflowException)
687
688         } catch (Exception ex) {
689             logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
690         }
691         logger.debug(Prefix + "sendSyncError Exit")
692     }
693
694 }