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