Merge "Add homing to CreateGenericALaCarteService flow"
[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 -> inputMap.put(userParam.name, userParam.value.toString())
146                 }
147             }
148
149             msoLogger.debug("User Input Parameters map: " + userParams.toString())
150             execution.setVariable("serviceInputParams", inputMap)
151
152             //TODO
153             //execution.setVariable("failExists", true)
154
155         } catch (BpmnError e) {
156             throw e;
157         } catch (Exception ex){
158             msg = "Exception in preProcessRequest " + ex.getMessage()
159             msoLogger.debug(msg)
160             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
161         }
162         msoLogger.trace("Exit preProcessRequest")
163     }
164
165     public void sendSyncResponse (DelegateExecution execution) {
166         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
167         msoLogger.trace("Start sendSyncResponse")
168
169         try {
170             String requestId = execution.getVariable("msoRequestId")
171             String serviceInstanceId = execution.getVariable("serviceInstanceId")
172             // RESTResponse for API Handler (APIH) Reply Task
173             String createServiceRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
174             msoLogger.debug(" sendSyncResponse to APIH:" + "\n" + createServiceRestRequest)
175             sendWorkflowResponse(execution, 202, createServiceRestRequest)
176             execution.setVariable("sentSyncResponse", true)
177
178         } catch (Exception ex) {
179             String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
180             msoLogger.debug(msg)
181             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
182         }
183         msoLogger.trace("Exit sendSyncResopnse")
184     }
185
186
187     public void sendSyncError (DelegateExecution execution) {
188         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
189         msoLogger.trace("Start sendSyncError")
190
191         try {
192             String errorMessage = ""
193             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
194                 WorkflowException wfe = execution.getVariable("WorkflowException")
195                 errorMessage = wfe.getErrorMessage()
196             } else {
197                 errorMessage = "Sending Sync Error."
198             }
199
200             String buildworkflowException =
201                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
202                     <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
203                     <aetgt:ErrorCode>7000</aetgt:ErrorCode>
204                    </aetgt:WorkflowException>"""
205
206             msoLogger.debug(buildworkflowException)
207             sendWorkflowResponse(execution, 500, buildworkflowException)
208
209         } catch (Exception ex) {
210             msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
211         }
212
213     }
214
215     // *******************************
216     //
217     // *******************************
218     public void prepareDecomposeService(DelegateExecution execution) {
219         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
220         msoLogger.trace("Inside prepareDecomposeService of CreateGenericALaCarteServiceInstance ")
221         try {
222             String siRequest = execution.getVariable("bpmnRequest")
223             String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
224             execution.setVariable("serviceModelInfo", serviceModelInfo)
225         } catch (Exception ex) {
226             // try error in method block
227             String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
228             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
229         }
230         msoLogger.trace("Completed prepareDecomposeService of CreateGenericALaCarteServiceInstance")
231      }
232
233     public void processDecomposition(DelegateExecution execution) {
234         def isDebugEnabled = execution.getVariable(DebugFlag)
235
236         msoLogger.trace("Inside processDecomposition() of CreateGenericALaCarteServiceInstance  ")
237
238         try {
239
240             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
241
242             // VNFs
243             List<VnfResource> vnfList = serviceDecomposition.getVnfResources()
244             filterVnfs(vnfList)
245             serviceDecomposition.setVnfResources(vnfList)
246
247             execution.setVariable("vnfList", vnfList)
248             execution.setVariable("vnfListString", vnfList.toString())
249
250             String vnfModelInfoString = ""
251             if (vnfList != null && vnfList.size() > 0) {
252                 execution.setVariable(Prefix + "VNFsCount", vnfList.size())
253                 msoLogger.debug("vnfs to create: " + vnfList.size())
254                 ModelInfo vnfModelInfo = vnfList[0].getModelInfo()
255
256                 vnfModelInfoString = vnfModelInfo.toString()
257                 String vnfModelInfoWithRoot = vnfModelInfo.toString()
258                 vnfModelInfoString = jsonUtil.getJsonValue(vnfModelInfoWithRoot, "modelInfo")
259             } else {
260                 execution.setVariable(Prefix + "VNFsCount", 0)
261                 msoLogger.debug("no vnfs to create based upon serviceDecomposition content")
262             }
263
264             execution.setVariable("vnfModelInfo", vnfModelInfoString)
265             execution.setVariable("vnfModelInfoString", vnfModelInfoString)
266             msoLogger.debug(" vnfModelInfoString :" + vnfModelInfoString)
267
268             msoLogger.trace("Completed processDecomposition() of CreateGenericALaCarteServiceInstance ")
269         } catch (Exception ex) {
270             sendSyncError(execution)
271             String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. processDecomposition() - " + ex.getMessage()
272             msoLogger.debug(exceptionMessage)
273             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
274         }
275     }
276
277      // *******************************
278      //
279      // *******************************
280      public void prepareCreateServiceInstance(DelegateExecution execution) {
281          def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
282  
283          try {
284              msoLogger.trace("Inside prepareCreateServiceInstance of CreateGenericALaCarteServiceInstance")
285  
286              /*
287               * Extracting User Parameters from incoming Request and converting into a Map
288               */
289              def jsonSlurper = new JsonSlurper()
290              def jsonOutput = new JsonOutput()
291              def siRequest = execution.getVariable("bpmnRequest")
292              Map reqMap = jsonSlurper.parseText(siRequest)
293              //InputParams
294              def userParams = reqMap.requestDetails?.requestParameters?.userParams
295              Map<String, String> inputMap = [:]
296              if (userParams != null) {
297                  userParams.each {
298                      userParam -> inputMap.put(userParam.name, userParam.value)
299                  }
300              }
301
302              msoLogger.debug("User Input Parameters map: " + userParams.toString())
303              execution.setVariable("serviceInputParams", inputMap)
304
305              ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
306
307              String serviceInstanceId = execution.getVariable("serviceInstanceId")
308              serviceDecomposition.getServiceInstance().setInstanceId(serviceInstanceId)
309
310              String serviceInstanceName = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName")
311              serviceDecomposition.getServiceInstance().setInstanceName(serviceInstanceName)
312              execution.setVariable("serviceInstanceName", serviceInstanceName)
313              execution.setVariable("serviceDecomposition", serviceDecomposition)
314              execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonString())
315              msoLogger.debug("serviceDecomposition.serviceInstanceName: " + serviceDecomposition.getServiceInstance().getInstanceName())
316
317              msoLogger.trace("Completed prepareCreateServiceInstance of CreateGenericALaCarteServiceInstance ***** ")
318          } catch (Exception ex) {
319              // try error in method block
320              String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
321              exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
322          }
323       }
324
325
326     public void prepareCompletionRequest (DelegateExecution execution) {
327         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
328         msoLogger.trace("prepareCompletion *** ")
329
330         try {
331             String requestId = execution.getVariable("msoRequestId")
332             String serviceInstanceId = execution.getVariable("serviceInstanceId")
333             String source = execution.getVariable("source")
334
335             String msoCompletionRequest =
336                     """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
337                                 xmlns:ns="http://org.onap/so/request/types/v1">
338                         <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
339                             <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
340                             <action>CREATE</action>
341                             <source>${MsoUtils.xmlEscape(source)}</source>
342                         </request-info>
343                         <status-message>Service Instance was created successfully.</status-message>
344                         <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
345                         <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name>
346                     </aetgt:MsoCompletionRequest>"""
347
348             // Format Response
349             String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
350
351             execution.setVariable("completionRequest", xmlMsoCompletionRequest)
352             msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
353
354         } catch (Exception ex) {
355             String msg = " Exception in prepareCompletion:" + ex.getMessage()
356             msoLogger.debug(msg)
357             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
358         }
359         msoLogger.trace("Exit prepareCompletionRequest")
360     }
361
362     public void prepareFalloutRequest(DelegateExecution execution){
363         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
364         msoLogger.trace("prepareFalloutRequest")
365
366         try {
367             WorkflowException wfex = execution.getVariable("WorkflowException")
368             msoLogger.debug(" Input Workflow Exception: " + wfex.toString())
369             String requestId = execution.getVariable("msoRequestId")
370             String source = execution.getVariable("source")
371             String requestInfo =
372                     """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
373                     <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
374                     <action>CREATE</action>
375                     <source>${MsoUtils.xmlEscape(source)}</source>
376                    </request-info>"""
377
378             String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
379             execution.setVariable("falloutRequest", falloutRequest)
380         } catch (Exception ex) {
381             msoLogger.debug("Exception prepareFalloutRequest:" + ex.getMessage())
382             String errorException = "  Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
383             String requestId = execution.getVariable("msoRequestId")
384             String falloutRequest =
385                     """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
386                                                  xmlns:ns="http://org.onap/so/request/types/v1"
387                                                  xmlns:wfsch="http://org.onap/so/workflow/schema/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>VID</source>
392                        </request-info>
393                         <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
394                             <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage>
395                             <aetgt:ErrorCode>7000</aetgt:ErrorCode>
396                         </aetgt:WorkflowException>
397                     </aetgt:FalloutHandlerRequest>"""
398
399             execution.setVariable("falloutRequest", falloutRequest)
400         }
401         msoLogger.trace("Exit prepareFalloutRequest")
402     }
403 }