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