Removed MsoLogger class
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateGenericALaCarteServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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 org.onap.so.bpmn.core.domain.ModelInfo
26 import org.onap.so.bpmn.core.domain.VnfResource;
27
28 import static org.apache.commons.lang3.StringUtils.*;
29
30 import org.apache.commons.lang3.*
31 import org.camunda.bpm.engine.delegate.BpmnError
32 import org.camunda.bpm.engine.delegate.DelegateExecution
33 import org.json.JSONException;
34 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
35 import org.onap.so.bpmn.common.scripts.ExceptionUtil
36 import org.onap.so.bpmn.common.scripts.MsoUtils
37 import org.onap.so.bpmn.core.WorkflowException
38 import org.onap.so.bpmn.core.domain.ServiceDecomposition
39 import org.onap.so.bpmn.core.json.JsonUtils
40 import org.slf4j.Logger
41 import org.slf4j.LoggerFactory
42 import org.springframework.web.util.UriUtils
43
44 import groovy.json.*
45
46 /**
47  * This groovy class supports the <class>CreateGenericALaCarteServiceInstance.bpmn</class> process.
48  * AlaCarte flow for 1702 ServiceInstance Create
49  *
50  */
51 public class CreateGenericALaCarteServiceInstance extends AbstractServiceTaskProcessor {
52     String Prefix="CRESI_"
53     ExceptionUtil exceptionUtil = new ExceptionUtil()
54     JsonUtils jsonUtil = new JsonUtils()
55     private static final Logger logger = LoggerFactory.getLogger( CreateGenericALaCarteServiceInstance.class);
56
57     public void preProcessRequest (DelegateExecution execution) {
58         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
59         execution.setVariable("prefix",Prefix)
60         String msg = ""
61
62         try {
63
64             String siRequest = execution.getVariable("bpmnRequest")
65             logger.debug(siRequest)
66
67             String requestId = execution.getVariable("mso-request-id")
68             execution.setVariable("msoRequestId", requestId)
69             logger.debug("Input Request:" + siRequest + " reqId:" + requestId)
70
71             String serviceInstanceId = execution.getVariable("serviceInstanceId")
72             if (isBlank(serviceInstanceId)) {
73                 serviceInstanceId = UUID.randomUUID().toString()
74                 logger.debug("Generated new Service Instance ID:" + serviceInstanceId)
75             } else {
76                 logger.debug("Using provided Service Instance ID:" + serviceInstanceId)
77             }
78
79             serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8")
80             execution.setVariable("serviceInstanceId", serviceInstanceId)
81
82             //subscriberInfo
83             String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId")
84             if (isBlank(globalSubscriberId)) {
85                 msg = "Input globalSubscriberId' is null"
86                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
87             } else {
88                 execution.setVariable("globalSubscriberId", globalSubscriberId)
89             }
90
91             //requestInfo
92             execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source"))
93             execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName"))
94             execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback"))
95             String productFamilyId = null;
96             try {
97                 productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
98             } catch (JSONException e) {
99                 productFamilyId = null;
100             }
101             if (isBlank(productFamilyId))
102             {
103                 msg = "Input productFamilyId is null"
104                 logger.debug(msg)
105                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
106             } else {
107                 execution.setVariable("productFamilyId", productFamilyId)
108             }
109
110             //modelInfo
111             String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
112             if (isBlank(serviceModelInfo)) {
113                 msg = "Input serviceModelInfo is null"
114                 logger.debug(msg)
115                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
116             } else
117             {
118                 execution.setVariable("serviceModelInfo", serviceModelInfo)
119             }
120
121             logger.debug("modelInfo" + serviceModelInfo)
122
123             //requestParameters
124             String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType")
125             if (isBlank(subscriptionServiceType)) {
126                 msg = "Input subscriptionServiceType is null"
127                 logger.debug(msg)
128                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
129             } else {
130                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
131             }
132
133
134             /*
135              * Extracting User Parameters from incoming Request and converting into a Map
136              */
137             def jsonSlurper = new JsonSlurper()
138             def jsonOutput = new JsonOutput()
139
140             Map reqMap = jsonSlurper.parseText(siRequest)
141
142             //InputParams
143             def userParams = reqMap.requestDetails?.requestParameters?.userParams
144
145             Map<String, String> inputMap = [:]
146             if (userParams) {
147                 userParams.each {
148                     userParam ->
149                         if ("Customer_Location".equals(userParam?.name)) {
150                             logger.debug("User Input customerLocation: " + userParam.value.toString())
151                             Map<String, String> customerMap = [:]
152                             userParam.value.each {
153                                 param ->
154
155                                     inputMap.put(param.key, param.value)
156                                     customerMap.put(param.key, param.value)
157                             }
158                             execution.setVariable("customerLocation", customerMap)
159                         }
160                         if ("Homing_Solution".equals(userParam?.name)) {
161                             logger.debug("User Input Homing_Solution: " + userParam.value.toString())
162                             execution.setVariable("homingService", userParam.value)
163                             execution.setVariable("callHoming", true)
164                             inputMap.put("Homing_Solution", userParam.value)
165                         }
166                         if (!"Homing_Solution".equals(userParam?.name) && !"Customer_Location".equals(userParam?.name))
167                         {
168                             logger.debug("User Input Parameter " + userParam.name + ": " + userParam.value.toString())
169                             inputMap.put(userParam.name, userParam.value)
170                         }
171                         if ("Orchestrator".equalsIgnoreCase(userParam?.name)) {
172                             execution.setVariable("orchestrator", userParam.value)
173                             inputMap.put("orchestrator", userParam.value)
174                         }
175                 }
176             }
177
178             logger.debug("User Input Parameters map: " + userParams.toString())
179             logger.debug("User Input Map: " + inputMap.toString())
180             if (inputMap.toString() != "[:]") {
181                 execution.setVariable("serviceInputParams", inputMap)
182             }
183
184             //TODO
185             //execution.setVariable("failExists", true)
186
187         } catch (BpmnError e) {
188             throw e;
189         } catch (Exception ex){
190             msg = "Exception in preProcessRequest " + ex.getMessage()
191             logger.debug(msg)
192             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
193         }
194         logger.trace("Exit preProcessRequest")
195     }
196
197     public void sendSyncResponse (DelegateExecution execution) {
198         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
199         logger.trace("Start sendSyncResponse")
200
201         try {
202             String requestId = execution.getVariable("msoRequestId")
203             String serviceInstanceId = execution.getVariable("serviceInstanceId")
204             // RESTResponse for API Handler (APIH) Reply Task
205             String createServiceRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
206             logger.debug(" sendSyncResponse to APIH:" + "\n" + createServiceRestRequest)
207             sendWorkflowResponse(execution, 202, createServiceRestRequest)
208             execution.setVariable("sentSyncResponse", true)
209
210         } catch (Exception ex) {
211             String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
212             logger.debug(msg)
213             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
214         }
215         logger.trace("Exit sendSyncResopnse")
216     }
217
218
219     public void sendSyncError (DelegateExecution execution) {
220         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
221         logger.trace("Start sendSyncError")
222
223         try {
224             String errorMessage = ""
225             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
226                 WorkflowException wfe = execution.getVariable("WorkflowException")
227                 errorMessage = wfe.getErrorMessage()
228             } else {
229                 errorMessage = "Sending Sync Error."
230             }
231
232             String buildworkflowException =
233                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
234                     <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
235                     <aetgt:ErrorCode>7000</aetgt:ErrorCode>
236                    </aetgt:WorkflowException>"""
237
238             logger.debug(buildworkflowException)
239             sendWorkflowResponse(execution, 500, buildworkflowException)
240
241         } catch (Exception ex) {
242             logger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
243         }
244
245     }
246
247     // *******************************
248     //
249     // *******************************
250     public void prepareDecomposeService(DelegateExecution execution) {
251         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
252         logger.trace("Inside prepareDecomposeService of CreateGenericALaCarteServiceInstance ")
253         try {
254             String siRequest = execution.getVariable("bpmnRequest")
255             String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
256             execution.setVariable("serviceModelInfo", serviceModelInfo)
257         } catch (Exception ex) {
258             // try error in method block
259             String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
260             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
261         }
262         logger.trace("Completed prepareDecomposeService of CreateGenericALaCarteServiceInstance")
263      }
264
265     public void processDecomposition(DelegateExecution execution) {
266         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
267
268         logger.trace("Inside processDecomposition() of CreateGenericALaCarteServiceInstance  ")
269
270         try {
271
272             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
273
274             // VNFs
275             List<VnfResource> vnfList = serviceDecomposition.getVnfResources()
276             serviceDecomposition.setVnfResources(vnfList)
277
278             execution.setVariable("vnfList", vnfList)
279             execution.setVariable("vnfListString", vnfList.toString())
280
281             String vnfModelInfoString = ""
282             if (vnfList != null && vnfList.size() > 0) {
283                 execution.setVariable(Prefix + "VNFsCount", vnfList.size())
284                 logger.debug("vnfs to create: " + vnfList.size())
285                 ModelInfo vnfModelInfo = vnfList[0].getModelInfo()
286
287                 vnfModelInfoString = vnfModelInfo.toString()
288                 String vnfModelInfoWithRoot = vnfModelInfo.toString()
289                 vnfModelInfoString = jsonUtil.getJsonValue(vnfModelInfoWithRoot, "modelInfo")
290             } else {
291                 execution.setVariable(Prefix + "VNFsCount", 0)
292                 logger.debug("no vnfs to create based upon serviceDecomposition content")
293             }
294
295             execution.setVariable("vnfModelInfo", vnfModelInfoString)
296             execution.setVariable("vnfModelInfoString", vnfModelInfoString)
297             logger.debug(" vnfModelInfoString :" + vnfModelInfoString)
298
299             logger.trace("Completed processDecomposition() of CreateGenericALaCarteServiceInstance ")
300         } catch (Exception ex) {
301             sendSyncError(execution)
302             String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. processDecomposition() - " + ex.getMessage()
303             logger.debug(exceptionMessage)
304             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
305         }
306     }
307
308      // *******************************
309      //
310      // *******************************
311      public void prepareCreateServiceInstance(DelegateExecution execution) {
312          def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
313  
314          try {
315              logger.trace("Inside prepareCreateServiceInstance of CreateGenericALaCarteServiceInstance")
316  
317              /*
318               * Extracting User Parameters from incoming Request and converting into a Map
319               */
320              def jsonSlurper = new JsonSlurper()
321              def jsonOutput = new JsonOutput()
322              def siRequest = execution.getVariable("bpmnRequest")
323              Map reqMap = jsonSlurper.parseText(siRequest)
324
325              //InputParams
326              def userParams = reqMap.requestDetails?.requestParameters?.userParams
327
328              Map<String, String> inputMap = [:]
329              if (userParams) {
330                  userParams.each {
331                      userParam ->
332                          if ("Customer_Location".equals(userParam?.name)) {
333                              logger.debug("User Input customerLocation: " + userParam.value.toString())
334                              Map<String, String> customerMap = [:]
335                              userParam.value.each {
336                                  param ->
337
338                                      inputMap.put(param.key, param.value)
339                                      customerMap.put(param.key, param.value)
340                              }
341                              execution.setVariable("customerLocation", customerMap)
342                          }
343                          if ("Homing_Solution".equals(userParam?.name)) {
344                              logger.debug("User Input Homing_Solution: " + userParam.value.toString())
345                              execution.setVariable("homingService", userParam.value)
346                              execution.setVariable("callHoming", true)
347                              inputMap.put("Homing_Solution", userParam.value)
348                          }
349                          if (!"Homing_Solution".equals(userParam?.name) && !"Customer_Location".equals(userParam?.name))
350                          {
351                              logger.debug("User Input Parameter " + userParam.name + ": " + userParam.value.toString())
352                              inputMap.put(userParam.name, userParam.value)
353                          }
354                          if ("Orchestrator".equalsIgnoreCase(userParam?.name)) {
355                              execution.setVariable("orchestrator", userParam.value)
356                              inputMap.put("orchestrator", userParam.value)
357                          }
358                  }
359              }
360
361              logger.debug("User Input Parameters map: " + userParams.toString())
362              logger.debug("User Input Map: " + inputMap.toString())
363              if (inputMap.toString() != "[:]") {
364                  execution.setVariable("serviceInputParams", inputMap)
365              }
366              ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
367
368              String serviceInstanceId = execution.getVariable("serviceInstanceId")
369              serviceDecomposition.getServiceInstance().setInstanceId(serviceInstanceId)
370
371              String serviceInstanceName = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName")
372              serviceDecomposition.getServiceInstance().setInstanceName(serviceInstanceName)
373              execution.setVariable("serviceInstanceName", serviceInstanceName)
374              execution.setVariable("serviceDecomposition", serviceDecomposition)
375              execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonString())
376              logger.debug("serviceDecomposition.serviceInstanceName: " + serviceDecomposition.getServiceInstance().getInstanceName())
377
378              logger.trace("Completed prepareCreateServiceInstance of CreateGenericALaCarteServiceInstance ***** ")
379          } catch (Exception ex) {
380              // try error in method block
381              String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
382              exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
383          }
384       }
385
386
387     public void prepareCompletionRequest (DelegateExecution execution) {
388         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
389         logger.trace("prepareCompletion *** ")
390
391         try {
392             String requestId = execution.getVariable("msoRequestId")
393             String serviceInstanceId = execution.getVariable("serviceInstanceId")
394             String source = execution.getVariable("source")
395
396             String msoCompletionRequest =
397                     """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
398                                 xmlns:ns="http://org.onap/so/request/types/v1">
399                         <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
400                             <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
401                             <action>CREATE</action>
402                             <source>${MsoUtils.xmlEscape(source)}</source>
403                         </request-info>
404                         <status-message>Service Instance was created successfully.</status-message>
405                         <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
406                         <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name>
407                     </aetgt:MsoCompletionRequest>"""
408
409             // Format Response
410             String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
411
412             execution.setVariable("completionRequest", xmlMsoCompletionRequest)
413             logger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
414
415         } catch (Exception ex) {
416             String msg = " Exception in prepareCompletion:" + ex.getMessage()
417             logger.debug(msg)
418             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
419         }
420         logger.trace("Exit prepareCompletionRequest")
421     }
422
423     public void prepareFalloutRequest(DelegateExecution execution){
424         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
425         logger.trace("prepareFalloutRequest")
426
427         try {
428             WorkflowException wfex = execution.getVariable("WorkflowException")
429             logger.debug(" Input Workflow Exception: " + wfex.toString())
430             String requestId = execution.getVariable("msoRequestId")
431             String source = execution.getVariable("source")
432             String requestInfo =
433                     """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
434                     <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
435                     <action>CREATE</action>
436                     <source>${MsoUtils.xmlEscape(source)}</source>
437                    </request-info>"""
438
439             String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
440             execution.setVariable("falloutRequest", falloutRequest)
441         } catch (Exception ex) {
442             logger.debug("Exception prepareFalloutRequest:" + ex.getMessage())
443             String errorException = "  Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
444             String requestId = execution.getVariable("msoRequestId")
445             String falloutRequest =
446                     """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
447                                                  xmlns:ns="http://org.onap/so/request/types/v1"
448                                                  xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
449                        <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
450                           <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
451                           <action>CREATE</action>
452                           <source>VID</source>
453                        </request-info>
454                         <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
455                             <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage>
456                             <aetgt:ErrorCode>7000</aetgt:ErrorCode>
457                         </aetgt:WorkflowException>
458                     </aetgt:FalloutHandlerRequest>"""
459
460             execution.setVariable("falloutRequest", falloutRequest)
461         }
462         logger.trace("Exit prepareFalloutRequest")
463     }
464 }