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