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