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