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