Fix some attribute issues
[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             //TODO temp solution - service to slice profile mapping
399             e2eInputMap.put("expDataRateDL", dLThptPerSlice)
400             e2eInputMap.put("expDataRateUL", uLThptPerSlice)
401             e2eInputMap.put("maxNumberofPDUSession", maxNumberofConns)
402
403             execution.setVariable("e2eInputMap", e2eInputMap)
404             execution.setVariable("e2eServiceType", e2eServiceDecomposition.getServiceType())
405             execution.setVariable("e2eModelInvariantUuid", e2eServiceDecomposition.getModelInfo().getModelInvariantUuid())
406             execution.setVariable("e2eModelUuid", e2eServiceDecomposition.getModelInfo().getModelUuid())
407             logger.debug(Prefix + "e2eInputMap is = " + e2eInputMap.toString())
408         } catch (BpmnError e) {
409             throw e
410         } catch (Exception ex) {
411             String msg = "Exception in DoCreateE2EServiceInstance.createRelationShipInAAI. " + ex.getMessage()
412             logger.info(msg)
413             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
414         }
415
416         logger.debug(Prefix + "generateE2EServiceProfile Exit")
417     }
418
419     static def getDefaultPropertiesByType(def value, String type) {
420
421         def defaultValue
422         switch (type) {
423             case "string":
424                 defaultValue = ""
425                 break
426             case "integer":
427                 defaultValue = 0
428                 break
429             case "float":
430                 defaultValue = 0.0
431                 break
432             default:
433                 defaultValue = null
434                 break
435         }
436         return StringUtils.isEmpty(value) ? defaultValue : value
437     }
438
439     /**
440      * call createE2EService get operation id,
441      * created/processing
442      */
443     def preRequestSend2NSMF(DelegateExecution execution) {
444         logger.debug(Prefix + "preRequestSend2NSMF Start")
445         try {
446
447             //String NSMF_endpoint = "/onap/so/infra/e2eServiceInstances/v3"
448             def NSMF_endpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
449             def url = NSMF_endpoint + "/e2eServiceInstances/v3"
450             execution.setVariable("NSMF_endpoint", url)
451             //get from model catalog inputs
452             String payload = """
453                 {
454                     "service":{
455                         "name": "${execution.getVariable("csServiceName")}",
456                         "description": "e2eService of ${execution.getVariable("modelUuid")}",
457                         "serviceInvariantUuid": "${execution.getVariable("e2eModelInvariantUuid")}",
458                         "serviceUuid": "${execution.getVariable("e2eModelUuid")}",
459                         "globalSubscriberId": "${execution.getVariable("globalSubscriberId")}",
460                         "serviceType": "${execution.getVariable("subscriptionServiceType")}",
461                         "parameters":{
462                             "requestInputs": ${execution.getVariable("e2eInputMap") as JSONObject}
463                         }
464                     }
465                 }
466             """
467             execution.setVariable("CSMF_NSMFRequest", payload.replaceAll("\\s+", ""))
468             logger.debug(Prefix + "Sent to NSMF Request = " + payload)
469         } catch (BpmnError e) {
470             throw e
471         } catch (Exception ex) {
472             String msg = "Exception in CreateCommunicationService.preRequestSend2NSMF. " + ex.getMessage()
473             logger.error(msg)
474             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
475         }
476
477         logger.debug(Prefix + "preRequestSend2NSMF Exit")
478     }
479
480
481     def processNSMFResponse = { DelegateExecution execution ->
482         logger.debug(Prefix + "processNSMFResponse Start")
483         //oof
484         try {
485             def CSMF_NSMFResponseCode = execution.getVariable("CSMF_NSMFResponseCode") as Integer
486             if (CSMF_NSMFResponseCode >= 200 && CSMF_NSMFResponseCode < 400) {
487                 def CSMF_NSMFResponse = execution.getVariable("CSMF_NSMFResponse") as String
488                 def e2eServiceInstanceId = jsonUtil.getJsonValue(CSMF_NSMFResponse, "service.serviceId")
489                 def e2eOperationId = jsonUtil.getJsonValue(CSMF_NSMFResponse, "service.operationId")
490
491                 execution.setVariable("e2eServiceInstanceId", e2eServiceInstanceId)
492                 execution.setVariable("e2eOperationId", e2eOperationId)
493                 execution.setVariable("ProcessNsmfSuccess", "OK")
494             } else {
495                 execution.setVariable("ProcessNsmfSuccess", "ERROR")
496                 execution.setVariable("operationStatus", "error")
497                 execution.setVariable("operationContent",
498                         "communication service create operation error: nsmf response fail")
499                 execution.setVariable("orchestrationStatus", "error")
500             }
501
502         } catch (BpmnError e) {
503             throw e
504         } catch (Exception ex) {
505             String msg = "Exception in " + Prefix + "processOOFResponse. " + ex.getMessage()
506             logger.info(msg)
507             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
508         }
509         logger.debug(Prefix + "processNSMFResponse Exit")
510     }
511
512
513     /**
514      * create communication service and e2e service relationship
515      *
516      */
517     def createCSAndSSRelationship = { DelegateExecution execution ->
518         logger.debug(Prefix + "createCSAndSSRelationship Start")
519         String msg = ""
520         try {
521             def e2eServiceInstanceId = execution.getVariable("e2eServiceInstanceId")
522             String globalSubscriberId = execution.getVariable("globalSubscriberId")
523             String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
524
525             Relationship relationship = new Relationship()
526             String relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${e2eServiceInstanceId}"
527             relationship.setRelatedLink(relatedLink)
528
529             // create CS and SS relationship in AAI
530             createRelationShipInAAI(execution, relationship)
531
532         } catch (BpmnError e) {
533             throw e
534         } catch (Exception ex) {
535
536             msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage()
537             logger.info(msg)
538             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
539         }
540         logger.debug(Prefix + "createCSAndSSRelationship Exit")
541     }
542
543
544     /**
545      * prepare update operation status to 50% after create relationship in aai
546      * @param execution
547      */
548     def prepareUpdateOperationStatus = { DelegateExecution execution ->
549         logger.debug(Prefix + "prepareUpdateOperationStatus Start")
550         // update status creating
551         OperationStatus status = new OperationStatus()
552         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
553         status.setOperationId(execution.getVariable("operationId") as String)
554         status.setOperation("CREATE")
555         status.setResult("processing")
556         status.setProgress("20")
557         status.setOperationContent("communication service create operation processing: waiting nsmf service create finished")
558         status.setUserId(execution.getVariable("globalSubscriberId") as String)
559
560         requestDBUtil.prepareUpdateOperationStatus(execution, status)
561         logger.debug(Prefix + "prepareUpdateOperationStatus Exit")
562     }
563
564
565     /**
566      * create relationship in AAI
567      */
568     private createRelationShipInAAI = { DelegateExecution execution, final Relationship relationship ->
569         logger.debug(Prefix + "createRelationShipInAAI Start")
570         String msg
571         try {
572             String serviceInstanceId = execution.getVariable("serviceInstanceId")
573             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("subscriptionServiceType")).serviceInstance(serviceInstanceId)).relationshipAPI()
574             client.create(uri, relationship)
575
576         } catch (BpmnError e) {
577             throw e
578         } catch (Exception ex) {
579             msg = "Exception in CreateCommunicationService.createRelationShipInAAI. " + ex.getMessage()
580             logger.info(msg)
581             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
582         }
583         logger.debug(Prefix + "createRelationShipInAAI Exit")
584
585     }
586
587
588     def prepareCallCheckProcessStatus = { DelegateExecution execution ->
589         logger.debug(Prefix + "prepareCallCheckProcessStatus Start")
590
591         def successConditions = new ArrayList<>()
592         successConditions.add("finished")
593         execution.setVariable("successConditions", successConditions)
594
595         def errorConditions = new ArrayList<>()
596         errorConditions.add("error")
597         execution.setVariable("errorConditions", errorConditions)
598
599         execution.setVariable("processServiceType", "communication service")
600
601         execution.setVariable("subOperationType", "CREATE")
602
603         execution.setVariable("timeOut", 3 * 60 * 60 * 1000)
604
605         def successParamMap = new HashMap<String, Object>()
606         successParamMap.put("orchestrationStatus", "deactivated")
607
608         execution.setVariable("successParamMap", successParamMap)
609
610         def errorParamMap = new HashMap<String, Object>()
611         errorParamMap.put("orchestrationStatus", "error")
612
613         execution.setVariable("errorParamMap", errorParamMap)
614
615         def timeOutParamMap = new HashMap<String, Object>()
616         timeOutParamMap.put("orchestrationStatus", "error")
617
618         execution.setVariable("timeOutParamMap", timeOutParamMap)
619
620         execution.setVariable("initProgress", 20)
621         execution.setVariable("endProgress", 90)
622
623         logger.debug(Prefix + "prepareCallCheckProcessStatus Exit")
624     }
625
626
627     /**
628      * prepare update operation status to complete after NSMF process success
629      * @param execution
630      */
631     def prepareCompleteStatus = { DelegateExecution execution ->
632         logger.debug(Prefix + "prepareCompleteStatus Start")
633         OperationStatus status = new OperationStatus()
634         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
635         status.setOperationId(execution.getVariable("operationId") as String)
636         status.setOperation("CREATE")
637         status.setResult(execution.getVariable("operationStatus") as String)
638         status.setProgress("100")
639         status.setOperationContent(execution.getVariable("operationContent") as String)
640         status.setUserId(execution.getVariable("globalSubscriberId") as String)
641
642         requestDBUtil.prepareUpdateOperationStatus(execution, status)
643         logger.debug("prepareCompleteStatus end, serviceInstanceId: " + execution.getVariable("serviceInstanceId")
644                 + ", operationId: " + execution.getVariable("operationId"))
645         logger.debug(Prefix + "prepareCompleteStatus Exit")
646     }
647
648
649     /**
650      * update NSMF complete status to AAI when the NSMF process finished
651      * @param execution
652      */
653     def updateFinishStatusInAAI = { DelegateExecution execution ->
654         logger.debug(Prefix + "updateFinishStatusInAAI Start")
655         String msg
656         try {
657
658             String serviceInstanceId = execution.getVariable("serviceInstanceId")
659             String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
660             String globalSubscriberId = execution.getVariable("globalSubscriberId")
661             String orchestrationStatus = execution.getVariable("orchestrationStatus")
662             // create service
663             ServiceInstance csi = new ServiceInstance()
664             csi.setOrchestrationStatus(orchestrationStatus)
665             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceInstanceId))
666             client.update(uri, csi)
667             logger.debug(Prefix + "updateFinishStatusInAAI update communication service status to deactivated")
668
669         } catch (BpmnError e) {
670             throw e
671         } catch (Exception ex) {
672             msg = "Exception in complete communication service " + ex.getMessage()
673             logger.debug(msg)
674             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
675         }
676         logger.debug(Prefix + "updateFinishStatusInAAI Exit")
677     }
678
679
680     public sendSyncError = { DelegateExecution execution ->
681         logger.debug("sendSyncError Start")
682         try {
683             String errorMessage
684             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
685                 WorkflowException wfe = execution.getVariable("WorkflowException") as WorkflowException
686                 errorMessage = wfe.getErrorMessage()
687             } else {
688                 errorMessage = "Sending Sync Error."
689             }
690
691             String buildWorkflowException =
692                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
693                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
694                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
695                                    </aetgt:WorkflowException>"""
696
697             logger.debug(buildWorkflowException)
698             sendWorkflowResponse(execution, 500, buildWorkflowException)
699
700         } catch (Exception ex) {
701             logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
702         }
703         logger.debug(Prefix + "sendSyncError Exit")
704     }
705
706 }