Merge "Addition of Dockerfile/logback for SO-Monitoring"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / Create3rdONAPE2EServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License")
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import org.json.JSONArray
24 import org.json.JSONObject
25 import org.json.XML
26
27 import static org.apache.commons.lang3.StringUtils.*
28 import groovy.xml.XmlUtil
29 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
30 import org.onap.so.bpmn.common.scripts.ExceptionUtil
31 import org.onap.so.bpmn.common.scripts.ExternalAPIUtil
32 import org.onap.so.bpmn.common.scripts.AaiUtil
33 import org.onap.so.bpmn.common.scripts.MsoUtils
34 import org.onap.so.bpmn.common.recipe.ResourceInput
35 import org.onap.so.bpmn.common.resource.ResourceRequestBuilder
36 import org.onap.so.bpmn.core.WorkflowException
37 import org.onap.so.bpmn.core.json.JsonUtils
38 import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder
39 import org.onap.so.rest.APIResponse
40 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
41 import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory
42 import java.util.Map
43 import java.util.UUID
44 import org.onap.so.logger.MsoLogger
45
46 import org.camunda.bpm.engine.runtime.Execution
47 import org.camunda.bpm.engine.delegate.BpmnError
48 import org.camunda.bpm.engine.delegate.DelegateExecution
49 import org.apache.commons.lang3.*
50 import org.apache.commons.codec.binary.Base64
51 import org.springframework.web.util.UriUtils
52 import org.onap.so.rest.RESTClient
53 import org.onap.so.rest.RESTConfig
54
55 /**
56  * This groovy class supports the <class>Create3rdONAPE2EServiceInstance.bpmn</class> process.
57  * flow for Create E2EServiceInstance in 3rdONAP 
58  */
59 public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcessor {
60
61         String Prefix = "CRE3rdONAPESI_"
62
63         ExceptionUtil exceptionUtil = new ExceptionUtil()
64
65         JsonUtils jsonUtil = new JsonUtils()
66
67         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, Create3rdONAPE2EServiceInstance.class)
68
69         public void checkSPPartnerInfo (DelegateExecution execution) {
70                 msoLogger.info(" ***** Started checkSPPartnerInfo *****")
71                 try {
72                         //get bpmn inputs from resource request.
73                         String requestId = execution.getVariable("mso-request-id")
74                         String requestAction = execution.getVariable("requestAction")
75                         msoLogger.info("The requestAction is: " + requestAction)
76                         String recipeParamsFromRequest = execution.getVariable("recipeParams")
77                         msoLogger.info("The recipeParams is: " + recipeParamsFromRequest)
78                         String resourceInput = execution.getVariable("resourceInput")
79                         msoLogger.info("The resourceInput is: " + resourceInput)
80                         //Get ResourceInput Object
81                         ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class)
82                         String resourceInputPrameters = resourceInputObj.getResourceParameters()
83                         String inputParametersJson = JsonUtils.getJsonValue(resourceInputPrameters, "requestInputs")
84                         JSONObject inputParameters = new JSONObject(inputParametersJson)
85                         
86                         // set local resourceInput
87                         execution.setVariable(Prefix + "ResourceInput", resourceInputObj)
88                         
89                         boolean is3rdONAPExist = false
90
91                         if(inputParameters.has("sppartner_url"))
92                         {
93                                 String sppartnerUrl = inputParameters.get("sppartner_url")
94                                 if(!isBlank(sppartnerUrl)) {
95                                         execution.setVariable(Prefix + "SppartnerUrl", sppartnerUrl)
96                                         is3rdONAPExist = true
97                                 }
98                                 else {
99                                         is3rdONAPExist = false
100                                         String msg = "sppartner Url is blank."
101                                         msoLogger.debug(msg)
102                                 }
103                         }
104                         if(inputParameters.has("sppartner_providingServiceUuid"))
105                         {
106                                 String sppartnerUUID= inputParameters.get("sppartner_providingServiceUuid")
107                                 execution.setVariable(Prefix + "SppartnerUUID", sppartnerUUID)
108                                 is3rdONAPExist = true
109                         }
110                         else {
111                                 is3rdONAPExist = false
112                                 String msg = "sppartner providingServiceUuid is blank."
113                                 msoLogger.debug(msg)
114                         }
115                         if(inputParameters.has("sppartner_providingServiceInvariantUuid"))
116                         {
117                                 String sppartnerInvarianteUUID  = inputParameters.get("sppartner_providingServiceInvariantUuid")
118                                 execution.setVariable(Prefix + "SppartnerInvarianteUUID", sppartnerInvarianteUUID)
119                                 is3rdONAPExist = true
120                         }
121                         else {
122                                 is3rdONAPExist = false
123                                 String msg = "sppartner providingServiceInvarianteUuid is blank."
124                                 msoLogger.debug(msg)
125                         }
126                         
127                         if(inputParameters.has("sppartner_handoverMode"))
128                         {
129                                 String handoverMode = inputParameters.get("sppartner_handoverMode")
130                                 execution.setVariable(Prefix + "HandoverMode", handoverMode)
131                             is3rdONAPExist = true
132                         }
133                         else {
134                                 is3rdONAPExist = false
135                                 String msg = "sppartner handoverMode is blank."
136                                 msoLogger.debug(msg)
137                         }
138
139                         execution.setVariable("Is3rdONAPExist", is3rdONAPExist)
140                         execution.setVariable(Prefix + "ServiceInstanceId", resourceInputObj.getServiceInstanceId())
141                         execution.setVariable("mso-request-id", requestId)
142                         execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId())
143
144                 } catch (BpmnError e) {
145                         throw e
146                 } catch (Exception ex){
147                         String msg = "Exception in checkSPPartnerInfo " + ex.getMessage()
148                         msoLogger.debug(msg)
149                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
150                 }
151         }
152
153         public void checkLocallCall (DelegateExecution execution) {
154                 msoLogger.info(" ***** Started checkLocallCall *****")
155                 try {
156                                         
157                         //Get ResourceInput Object
158                         ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput")                        
159
160                         //uuiRequest
161                         String incomingRequest = resourceInputObj.getRequestsInputs()
162                         String serviceParameters = JsonUtils.getJsonValue(incomingRequest, "service.parameters")
163                         String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs")
164                         JSONObject inputParameters = new JSONObject(requestInputs)
165                         execution.setVariable(Prefix + "ServiceParameters", inputParameters)
166                         
167                         // CallSource is added only when ONAP SO calling 3rdONAP(External API) SO(Remote call)
168                         boolean isLocalCall = true
169                         String callSource = "UUI"
170                         if(inputParameters.has("CallSource"))
171                         {
172                                 callSource = inputParameters.get("CallSource")
173                                 if("ExternalAPI".equalsIgnoreCase(callSource)) {
174                                         String sppartnerId = inputParameters.get("SppartnerServiceId")
175                                         execution.setVariable(Prefix + "SppartnerServiceId", sppartnerId)
176                                         isLocalCall = false
177                                 }                                                       
178                         }
179                         execution.setVariable(Prefix + "CallSource", callSource)
180                         msoLogger.debug("callSource is: " + callSource )
181                         
182                         execution.setVariable("IsLocalCall", isLocalCall)
183
184                 } catch (Exception ex){
185                         String msg = "Exception in checkLocallCall " + ex.getMessage()
186                         msoLogger.debug(msg)
187                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
188                 }
189         }
190
191         public void preProcessRequest(DelegateExecution execution){
192                 msoLogger.info(" ***** Started preProcessRequest *****")
193                 String msg = ""
194
195                 try {
196                         ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput")
197
198                         String globalSubscriberId = resourceInputObj.getGlobalSubscriberId()
199                         if (isBlank(globalSubscriberId)) {
200                                 msg = "Input globalSubscriberId is null"
201                                 msoLogger.error(msg)
202                         }
203                         //set local variable
204                         execution.setVariable("globalSubscriberId", globalSubscriberId)
205                         msoLogger.info("globalSubscriberId:" + globalSubscriberId)
206
207                         String serviceType = resourceInputObj.getServiceType()
208                         if (isBlank(serviceType)) {
209                                 msg = "Input serviceType is null"
210                                 msoLogger.error(msg)
211                         }
212                         execution.setVariable("serviceType", serviceType)
213                         msoLogger.info("serviceType:" + serviceType)
214                         
215                         String resourceName = resourceInputObj.getResourceInstanceName()
216                         if (isBlank(resourceName)) {
217                                 msg = "Input resourceName is null"
218                                 msoLogger.error(msg)
219                         }
220                         execution.setVariable("resourceName", resourceName)
221                         msoLogger.info("resourceName:" + resourceName)
222                         
223                         int beginIndex = resourceName.indexOf("_") + 1
224                         String serviceInstanceName = resourceName.substring(beginIndex)
225                         execution.setVariable("serviceInstanceName", serviceInstanceName)
226                         
227                         String serviceInstanceId = resourceInputObj.getServiceInstanceId()
228                         if (isBlank(serviceInstanceId)) {
229                                 msg = "Input serviceInstanceId is null"
230                                 msoLogger.error(msg)
231                         }
232                         execution.setVariable(Prefix + "ServiceInstanceId", serviceInstanceId)
233                         msoLogger.info("serviceInstanceId:" + serviceInstanceId)
234
235                         String resourceModelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid()
236                         if (isBlank(resourceModelInvariantUuid)) {
237                                 msg = "Input resourceModelInvariantUuid is null"
238                                 msoLogger.error(msg)
239                         }
240                         execution.setVariable(Prefix + "ResourceModelInvariantUuid", resourceModelInvariantUuid)
241                         msoLogger.info("resourceModelInvariantUuid:" + resourceModelInvariantUuid)
242                                 
243                         String resourceModelUuid = resourceInputObj.getResourceModelInfo().getModelUuid()
244                         if (isBlank(resourceModelUuid)) {
245                                 msg = "Input resourceModelUuid is null"
246                                 msoLogger.error(msg)
247                         }
248                         execution.setVariable(Prefix + "ResourceModelUuid", resourceModelUuid)
249                         msoLogger.info("resourceModelUuid:" + resourceModelUuid)
250                         
251                         String resourceModelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
252                         if (isBlank(resourceModelCustomizationUuid)) {
253                                 msg = "Input resourceModelCustomizationUuid is null"
254                                 msoLogger.error(msg)
255                         }
256                         execution.setVariable(Prefix + "ResourceModelCustomizationUuid", resourceModelCustomizationUuid)
257                         msoLogger.info("resourceModelCustomizationUuid:" + resourceModelCustomizationUuid)
258
259                 } catch (BpmnError e) {
260                         throw e
261                 } catch (Exception ex){
262                         msg = "Exception in preProcessRequest " + ex.getMessage()
263                         msoLogger.debug(msg)
264                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
265                 }
266         }
267
268         public void prepareUpdateProgress(DelegateExecution execution) {
269                 msoLogger.info(" ***** Started prepareUpdateProgress *****")
270                 ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput")
271                 String operType = resourceInputObj.getOperationType()
272                 String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
273                 String ServiceInstanceId = resourceInputObj.getServiceInstanceId()
274                 String modelName = resourceInputObj.getResourceModelInfo().getModelName()
275                 String operationId = resourceInputObj.getOperationId()
276                 String progress = execution.getVariable("progress")
277                 String status = execution.getVariable("status")
278                 String statusDescription = execution.getVariable("statusDescription")
279
280                 String body = """
281                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
282                         xmlns:ns="http://org.openecomp.mso/requestsdb">
283                         <soapenv:Header/>
284                 <soapenv:Body>
285                     <ns:updateResourceOperationStatus>
286                                <operType>${operType}</operType>
287                                <operationId>${operationId}</operationId>
288                                <progress>${progress}</progress>
289                                <resourceTemplateUUID>${resourceCustomizationUuid}</resourceTemplateUUID>
290                                <serviceId>${ServiceInstanceId}</serviceId>
291                                <status>${status}</status>
292                                <statusDescription>${statusDescription}</statusDescription>
293                     </ns:updateResourceOperationStatus>
294                 </soapenv:Body>
295                 </soapenv:Envelope>"""
296
297                 setProgressUpdateVariables(execution, body)
298                 msoLogger.info(" ***** Exit prepareUpdateProgress *****")
299         }
300
301         public void allocateCrossONAPResource(DelegateExecution execution) {
302                 msoLogger.info(" ***** Started allocateCrossONAPResource *****")
303                 
304                 //get TP links from AAI for SOTN handoverMode only
305                 String handoverMode = execution.getVariable(Prefix + "HandoverMode")
306                 if("SOTN".equalsIgnoreCase(handoverMode)) {
307                         // Put TP Link info into serviceParameters
308                         JSONObject inputParameters = execution.getVariable(Prefix + "ServiceParameters")
309                         if(inputParameters.has("remote-access-provider-id")) {
310                                 Map<String, Object> crossTPs = new HashMap<String, Object>();
311                                 crossTPs.put("local-access-provider-id", inputParameters.get("remote-access-provider-id"));
312                                 crossTPs.put("local-access-client-id", inputParameters.get("remote-access-client-id"));
313                                 crossTPs.put("local-access-topology-id", inputParameters.get("remote-access-topology-id"));
314                                 crossTPs.put("local-access-node-id", inputParameters.get("remote-access-node-id"));
315                                 crossTPs.put("local-access-ltp-id", inputParameters.get("remote-access-ltp-id"));
316                                 crossTPs.put("remote-access-provider-id", inputParameters.get("local-access-provider-id"));
317                                 crossTPs.put("remote-access-client-id", inputParameters.get("local-access-client-id"));
318                                 crossTPs.put("remote-access-topology-id", inputParameters.get("local-access-topology-id"));
319                                 crossTPs.put("remote-access-node-id", inputParameters.get("local-access-node-id"));
320                                 crossTPs.put("remote-access-ltp-id", inputParameters.get("local-access-ltp-id"));
321         
322                                 inputParameters.put("local-access-provider-id", crossTPs.get("local-access-provider-id"));
323                                 inputParameters.put("local-access-client-id", crossTPs.get("local-access-client-id"));
324                                 inputParameters.put("local-access-topology-id", crossTPs.get("local-access-topology-id"));
325                                 inputParameters.put("local-access-node-id", crossTPs.get("local-access-node-id"));
326                                 inputParameters.put("local-access-ltp-id", crossTPs.get("local-access-ltp-id"));
327                                 inputParameters.put("remote-access-provider-id", crossTPs.get("remote-access-provider-id"));
328                                 inputParameters.put("remote-access-client-id", crossTPs.get("remote-access-client-id"));
329                                 inputParameters.put("remote-access-topology-id", crossTPs.get("remote-access-topology-id"));
330                                 inputParameters.put("remote-access-node-id", crossTPs.get("remote-access-node-id"));
331                                 inputParameters.put("remote-access-ltp-id", crossTPs.get("remote-access-ltp-id"));
332
333                                 execution.setVariable(Prefix + "ServiceParameters", inputParameters)
334                         }
335                         else {
336                                         msoLogger.error("No allocated CrossONAPResource found in ServiceParameters")
337                         }
338                 }
339                 
340                 msoLogger.info("Exit " + allocateCrossONAPResource)
341         }
342
343         public void prepare3rdONAPRequest(DelegateExecution execution) {
344                 msoLogger.info(" ***** Started prepare3rdONAPRequest *****")
345                 
346                 String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl")
347                 String extAPIPath = sppartnerUrl + '/serviceOrder'
348                 execution.setVariable("ExternalAPIURL", extAPIPath)
349                 
350                 // ExternalAPI message format
351                 String externalId = execution.getVariable("resourceName")
352                 String category = "E2E Service"
353                 String description = "Service Order from SPPartner"
354                 String requestedStartDate = utils.generateCurrentTimeInUtc()
355                 String requestedCompletionDate = utils.generateCurrentTimeInUtc()
356                 String priority = "1" // 0-4 0:highest
357                 String subscriberId = execution.getVariable("globalSubscriberId")
358                 String customerRole = "ONAPcustomer"
359                 String subscriberName = subscriberId
360                 String referredType = "Consumer"
361                 String orderItemId = "1"
362                 String action = "add" //for create
363                 String serviceState = "active"
364                 String serviceName = execution.getVariable("serviceInstanceName")
365                 String serviceUuId = execution.getVariable(Prefix + "SppartnerUUID")
366                 
367                 Map<String, String> valueMap = new HashMap<>()
368                 valueMap.put("externalId", '"' + externalId + '"')
369                 valueMap.put("category", '"' + category + '"')
370                 valueMap.put("description", '"' + description + '"')
371                 valueMap.put("requestedStartDate", '"' + requestedStartDate + '"')
372                 valueMap.put("requestedCompletionDate", '"' + requestedCompletionDate + '"')
373                 valueMap.put("priority", '"'+ priority + '"')
374                 valueMap.put("subscriberId", '"' + subscriberId + '"')
375                 valueMap.put("customerRole", '"' + customerRole + '"')
376                 valueMap.put("subscriberName", '"' + subscriberName + '"')
377                 valueMap.put("referredType", '"' + referredType + '"')
378                 valueMap.put("orderItemId", '"' + orderItemId + '"')
379                 valueMap.put("action", '"' + action + '"')
380                 valueMap.put("serviceState", '"' + serviceState + '"')
381                 valueMap.put("serviceId", "null") //null for add
382                 valueMap.put("serviceName", '"' + serviceName + '"')
383                 valueMap.put("serviceUuId", '"' + serviceUuId + '"')
384                 
385                 ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil()
386                 
387                 // insert CallSource='ExternalAPI' to uuiRequest                
388                 Map<String, String> requestInputsMap = new HashMap<>()
389                 requestInputsMap.put("inputName",  '"CallSource"')
390                 requestInputsMap.put("inputValue", '"ExternalAPI"')
391                 String _requestInputs_ = externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap)
392                 
393                 requestInputsMap.clear()
394                 String serviceInstanceId = execution.getVariable(Prefix + "ServiceInstanceId")
395                 requestInputsMap.put("inputName", '"SppartnerServiceId"')
396                 requestInputsMap.put("inputValue", '"' + serviceInstanceId + '"')
397                 _requestInputs_ +=  ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap)
398                 
399                 requestInputsMap.clear()
400                 String serviceType = execution.getVariable("serviceType")
401                 requestInputsMap.put("inputName", '"serviceType"')
402                 requestInputsMap.put("inputValue", '"' + serviceType + '"')
403                 _requestInputs_ +=  ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap)
404                 
405                 // Transfer all uuiRequest incomeParameters to ExternalAPI format
406                 JSONObject inputParameters = execution.getVariable(Prefix + "ServiceParameters")
407                 for(String key : inputParameters.keySet()) {                    
408                         String inputName = key
409                         String inputValue = inputParameters.opt(key)
410                         requestInputsMap.clear()
411                         requestInputsMap.put("inputName", '"' + inputName+ '"')
412                         requestInputsMap.put("inputValue", '"' + inputValue + '"')
413                         _requestInputs_ += ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap)
414                 }
415                 valueMap.put("_requestInputs_",  _requestInputs_)
416                 
417                 String payload = externalAPIUtil.setTemplate(ExternalAPIUtil.PostServiceOrderRequestsTemplate, valueMap)
418                 execution.setVariable(Prefix + "Payload", payload)
419                 msoLogger.info("Exit " + prepare3rdONAPRequest)
420         }
421
422         public void doCreateE2ESIin3rdONAP(DelegateExecution execution) {
423                 msoLogger.info(" ***** Started doCreateE2ESIin3rdONAP *****")
424                 
425                 String extAPIPath = execution.getVariable("ExternalAPIURL")
426                 String payload = execution.getVariable(Prefix + "Payload")
427                 msoLogger.debug("doCreateE2ESIin3rdONAP externalAPIURL is: " + extAPIPath)
428                 msoLogger.debug("doCreateE2ESIin3rdONAP payload is: " + payload)
429                 
430                 ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil()
431
432                 APIResponse response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload)
433
434                 int responseCode = response.getStatusCode()
435                 execution.setVariable(Prefix + "PostServiceOrderResponseCode", responseCode)
436                 msoLogger.debug("Post ServiceOrder response code is: " + responseCode)
437
438                 String extApiResponse = response.getResponseBodyAsString()
439                 JSONObject responseObj = new JSONObject(extApiResponse)
440                 execution.setVariable(Prefix + "PostServiceOrderResponse", extApiResponse)
441                 
442                 msoLogger.debug("doCreateE2ESIin3rdONAP response body is: " + extApiResponse)
443                 
444                 //Process Response
445                 if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
446                         //200 OK 201 CREATED 202 ACCEPTED
447                 {
448                         msoLogger.debug("Post ServiceOrder Received a Good Response")
449                         String serviceOrderId = responseObj.get("id")
450                         execution.setVariable(Prefix + "SuccessIndicator", true)
451                         execution.setVariable("ServiceOrderId", serviceOrderId)
452                         msoLogger.info("Post ServiceOrderid is: " + serviceOrderId)
453                 }
454                 else{
455                         msoLogger.error("Post ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode)
456 //                      exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Post ServiceOrder Received a bad response from 3rdONAP External API")
457                 }
458                 
459                 msoLogger.info("Exit " + doCreateE2ESIin3rdONAP)
460         }
461         
462
463         public void getE2ESIProgressin3rdONAP(DelegateExecution execution) {
464                 msoLogger.info(" ***** Started getE2ESIProgressin3rdONAP *****")
465                 
466                 String extAPIPath = execution.getVariable("ExternalAPIURL")
467                 extAPIPath += "/" + execution.getVariable("ServiceOrderId")
468                 utils.log("DEBUG", "getE2ESIProgressin3rdONAP create externalAPIURL is: " + extAPIPath, isDebugEnabled)
469                 
470                 ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil()
471
472                 APIResponse response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath)
473
474                 int responseCode = response.getStatusCode()
475                 execution.setVariable(Prefix + "GetServiceOrderResponseCode", responseCode)
476                 msoLogger.debug("Get ServiceOrder response code is: " + responseCode)
477
478                 String extApiResponse = response.getResponseBodyAsString()
479                 JSONObject responseObj = new JSONObject(extApiResponse)
480                 execution.setVariable(Prefix + "GetServiceOrderResponse", extApiResponse)
481                 
482                 msoLogger.debug("getE2ESIProgressin3rdONAP create response body is: " + extApiResponse)
483                 
484                 //Process Response //200 OK 201 CREATED 202 ACCEPTED
485                 if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
486                 {
487                         msoLogger.debug("Get Create ServiceOrder Received a Good Response")
488
489                         String orderState = responseObj.get("state")
490                         if("REJECTED".equalsIgnoreCase(orderState)) {
491                                 execution.setVariable("progress", 100)
492                                 execution.setVariable("status", "error")
493                                 execution.setVariable("statusDescription", "Create Service Order Status is REJECTED")
494                                 return
495                         }
496
497                         JSONArray items = responseObj.getJSONArray("orderItem")
498                         JSONObject item = items[0]
499                         JSONObject service = item.get("service")
500                         String sppartnerServiceId = service.get("id")
501                         if(sppartnerServiceId == null || sppartnerServiceId.equals("null")) {
502                                 execution.setVariable("progress", 100)
503                                 execution.setVariable("status", "error")
504                                 execution.setVariable("statusDescription", "Create Service Order Status get null sppartnerServiceId")
505                                 msoLogger.error("null sppartnerServiceId while getting progress from externalAPI")
506                                 return
507                         }
508
509                         execution.setVariable(Prefix + "SppartnerServiceId", sppartnerServiceId)
510
511                         String serviceOrderState = item.get("state")
512                         execution.setVariable(Prefix + "SuccessIndicator", true)
513                         execution.setVariable("ServiceOrderState", serviceOrderState)
514                         
515                         // Get serviceOrder State and process progress
516                         if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) {
517                                 execution.setVariable("progress", 15)
518                                 execution.setVariable("status", "processing")
519                                 execution.setVariable("statusDescription", "Create Service Order Status is " + serviceOrderState)
520                         }
521                         else if("INPROGRESS".equalsIgnoreCase(serviceOrderState)) {
522                                 execution.setVariable("progress", 40)
523                                 execution.setVariable("status", "processing")
524                                 execution.setVariable("statusDescription", "Create Service Order Status is " + serviceOrderState)
525                         }
526                         else if("COMPLETED".equalsIgnoreCase(serviceOrderState)) {
527                                 execution.setVariable("progress", 100)
528                                 execution.setVariable("status", "finished")
529                                 execution.setVariable("statusDescription", "Create Service Order Status is " + serviceOrderState)
530                         }
531                         else if("FAILED".equalsIgnoreCase(serviceOrderState)) {
532                                 execution.setVariable("progress", 100)
533                                 execution.setVariable("status", "error")
534                                 execution.setVariable("statusDescription", "Create Service Order Status is " + serviceOrderState)
535                         }
536                         else {
537                                 execution.setVariable("progress", 100)
538                                 execution.setVariable("status", "error")
539                                 execution.setVariable("statusDescription", "Create Service Order Status is unknown")
540                         }
541                 }
542                 else{                   
543                         msoLogger.debug("Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode)
544                         execution.setVariable("progress", 100)
545                         execution.setVariable("status", "error")
546                         execution.setVariable("statusDescription", "Get Create ServiceOrder Received a bad response")
547                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Get Create ServiceOrder Received a bad response from 3rdONAP External API")
548                 }               
549                 
550                 msoLogger.info("Exit " + getE2ESIProgressin3rdONAP)
551         }
552         
553         /**
554          * delay 5 sec
555          */
556         public void timeDelay(DelegateExecution execution) {
557                 try {
558                         Thread.sleep(5000)
559                 } catch(InterruptedException e) {
560                         msoLogger.error("Time Delay exception" + e)
561                 }
562         }
563
564         public void saveSPPartnerInAAI(DelegateExecution execution) {
565                 msoLogger.info(" ***** Started saveSPPartnerInAAI *****")       
566                 
567                 String sppartnerId = execution.getVariable(Prefix + "SppartnerServiceId")
568                 String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl")
569                 String callSource = execution.getVariable(Prefix + "CallSource")
570                 String serviceInstanceId = execution.getVariable(Prefix + "ServiceInstanceId")
571                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
572                 String serviceType = execution.getVariable("serviceType")
573                 String resourceModelInvariantUuid = execution.getVariable(Prefix + "ResourceModelInvariantUuid")
574                 String resourceModelUuid = execution.getVariable(Prefix + "ResourceModelUuid")
575                 String resourceModelCustomizationUuid = execution.getVariable(Prefix + "ResourceModelCustomizationUuid")
576                 
577                 AaiUtil aaiUriUtil = new AaiUtil()
578                 String aai_uri = aaiUriUtil.getBusinessSPPartnerUri(execution)
579                 String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri)
580                 
581                 String payload =
582                                 """<sp-partner xmlns=\"${namespace}\">
583                                 <id>${sppartnerId}</id>
584                                 <url>${sppartnerUrl}</url>
585                                 <callsource>${callSource}</callsource>
586                                 <model-invariant-id>${resourceModelInvariantUuid}</model-invariant-id>
587                                 <model-version-id>${resourceModelUuid}</model-version-id>
588                                 <model-customization-id>${resourceModelCustomizationUuid}</model-customization-id>
589                                 <relationship-list>
590                                   <relationship>
591                                     <related-to>service-instance</related-to>
592                                     <related-link>/aai/v14/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${serviceInstanceId}</related-link>
593                                     <relationship-data>
594                                         <relationship-key>service-instance.service-instance-id</relationship-key>
595                                         <relationship-value>${serviceInstanceId}</relationship-value>
596                                     </relationship-data> 
597                                   </relationship>
598                                 </relationship-list>
599                                 </sp-partner>""".trim()
600                 utils.logAudit(payload)
601                 
602                 String aai_endpoint = execution.getVariable("URN_aai_endpoint")
603                 String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(sppartnerId,"UTF-8")
604                 
605                 APIResponse response = aaiUriUtil.executeAAIPutCall(execution, serviceAaiPath, payload)
606                 int responseCode = response.getStatusCode()
607                 execution.setVariable(Prefix + "PutSppartnerResponseCode", responseCode)
608                 msoLogger.debug("Put sppartner response code is: " + responseCode)
609
610                 String aaiResponse = response.getResponseBodyAsString()
611                 aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse)
612                 execution.setVariable(Prefix + "PutSppartnerResponse", aaiResponse)
613
614                 //Process Response
615                 if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
616                         //200 OK 201 CREATED 202 ACCEPTED
617                 {
618                         msoLogger.debug("PUT sppartner Received a Good Response")
619                         execution.setVariable(Prefix + "SuccessIndicator", true)
620                 }
621                 else
622                 {
623                         msoLogger.debug("Put sppartner Received a Bad Response Code. Response Code is: " + responseCode)
624                         exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
625                         throw new BpmnError("MSOWorkflowException")
626                 }
627                 
628                 msoLogger.info("Exit " + saveSPPartnerInAAI)
629         }
630
631         private void setProgressUpdateVariables(DelegateExecution execution, String body) {
632                 def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint")
633                 execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
634                 execution.setVariable("CVFMI_updateResOperStatusRequest", body)
635         }       
636
637         public void postProcess(DelegateExecution execution){
638                 msoLogger.info(" ***** Started postProcess *****")
639                 String responseCode = execution.getVariable(Prefix + "PutSppartnerResponseCode")
640                 String responseObj = execution.getVariable(Prefix + "PutSppartnerResponse")
641
642                 msoLogger.info("response from AAI for put sppartner, response code :" + responseCode + "  response object :" + responseObj)
643                 msoLogger.info(" ***** Exit postProcess *****")
644         }
645
646         public void sendSyncResponse (DelegateExecution execution) {
647                 msoLogger.debug(" *** sendSyncResponse *** ")
648
649                 try {
650                         String operationStatus = "finished"
651                         // RESTResponse for main flow
652                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
653                         msoLogger.debug(" sendSyncResponse to APIH:" + "\n" + resourceOperationResp)
654                         sendWorkflowResponse(execution, 202, resourceOperationResp)
655                         execution.setVariable("sentSyncResponse", true)
656
657                 } catch (Exception ex) {
658                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
659                         msoLogger.debug(msg)
660                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
661                 }
662                 msoLogger.debug(" ***** Exit sendSyncResopnse *****")
663         }
664 }