Merge "Reorder modifiers"
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / 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.openecomp.mso.bpmn.infrastructure.scripts;
22
23 import static org.apache.commons.lang3.StringUtils.*;
24 import groovy.xml.XmlUtil
25 import groovy.json.*
26 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
27 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
28 import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition
29 import org.openecomp.mso.bpmn.core.WorkflowException
30 import org.openecomp.mso.bpmn.core.json.JsonUtils
31 import org.openecomp.mso.rest.APIResponse
32
33 import java.util.UUID;
34
35 import org.camunda.bpm.engine.delegate.BpmnError
36 import org.camunda.bpm.engine.delegate.DelegateExecution
37 import org.apache.commons.lang3.*
38 import org.apache.commons.codec.binary.Base64;
39 import org.springframework.web.util.UriUtils
40 import org.json.JSONException;
41
42 /**
43  * This groovy class supports the <class>CreateGenericALaCarteServiceInstance.bpmn</class> process.
44  * AlaCarte flow for 1702 ServiceInstance Create
45  *
46  */
47 public class CreateGenericALaCarteServiceInstance extends AbstractServiceTaskProcessor {
48         String Prefix="CRESI_"
49         ExceptionUtil exceptionUtil = new ExceptionUtil()
50         JsonUtils jsonUtil = new JsonUtils()
51
52         public void preProcessRequest (DelegateExecution execution) {
53                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
54                 execution.setVariable("prefix",Prefix)
55                 String msg = ""
56                 utils.log("DEBUG", " *** preProcessRequest() of CreateGenericALaCarteServiceInstance *** ", isDebugEnabled)
57
58                 try {
59
60                         String siRequest = execution.getVariable("bpmnRequest")
61                         utils.logAudit(siRequest)
62
63                         String requestId = execution.getVariable("mso-request-id")
64                         execution.setVariable("msoRequestId", requestId)
65                         utils.log("DEBUG", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled)
66
67                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
68                         if (isBlank(serviceInstanceId)) {
69                                 serviceInstanceId = UUID.randomUUID().toString()
70                                 utils.log("DEBUG", "Generated new Service Instance ID:" + serviceInstanceId, isDebugEnabled)
71                         } else {
72                                 utils.log("DEBUG", "Using provided Service Instance ID:" + serviceInstanceId, isDebugEnabled)
73                         }
74
75                         serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8")
76                         execution.setVariable("serviceInstanceId", serviceInstanceId)
77
78                         //subscriberInfo
79                         String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId")
80                         if (isBlank(globalSubscriberId)) {
81                                 msg = "Input globalSubscriberId' is null"
82                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
83                         } else {
84                                 execution.setVariable("globalSubscriberId", globalSubscriberId)
85                         }
86
87                         //requestInfo
88                         execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source"))
89                         execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName"))
90                         execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback"))
91                         String productFamilyId = null;
92                         try { 
93                                 productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
94                         } catch (JSONException e) {
95                                 productFamilyId = null;
96                         }
97                         if (isBlank(productFamilyId))
98                         {
99                                 msg = "Input productFamilyId is null"
100                                 utils.log("DEBUG", msg, isDebugEnabled)
101                                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
102                         } else {
103                                 execution.setVariable("productFamilyId", productFamilyId)
104                         }
105
106                         //modelInfo
107                         String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
108                         if (isBlank(serviceModelInfo)) {
109                                 msg = "Input serviceModelInfo is null"
110                                 utils.log("DEBUG", msg, isDebugEnabled)
111                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
112                         } else
113                         {
114                                 execution.setVariable("serviceModelInfo", serviceModelInfo)
115                         }
116
117                         utils.log("DEBUG", "modelInfo" + serviceModelInfo,  isDebugEnabled)
118                 
119                         //requestParameters
120                         String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType")
121                         if (isBlank(subscriptionServiceType)) {
122                                 msg = "Input subscriptionServiceType is null"
123                                 utils.log("DEBUG", msg, isDebugEnabled)
124                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
125                         } else {
126                                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
127                         }
128
129                         
130                         /*
131                          * Extracting User Parameters from incoming Request and converting into a Map
132                          */
133                         def jsonSlurper = new JsonSlurper()
134                         def jsonOutput = new JsonOutput()
135
136                         Map reqMap = jsonSlurper.parseText(siRequest)
137
138                         //InputParams
139                         def userParams = reqMap.requestDetails?.requestParameters?.userParams
140
141                         Map<String, String> inputMap = [:]
142                         if (userParams) {
143                                 userParams.each {
144                                         userParam -> inputMap.put(userParam.name, userParam.value.toString())
145                                 }
146                         }
147                         
148                         utils.log("DEBUG", "User Input Parameters map: " + userParams.toString(), isDebugEnabled)
149                         execution.setVariable("serviceInputParams", inputMap)
150                         
151                         //TODO
152                         //execution.setVariable("failExists", true)
153
154                 } catch (BpmnError e) {
155                         throw e;
156                 } catch (Exception ex){
157                         msg = "Exception in preProcessRequest " + ex.getMessage()
158                         utils.log("DEBUG", msg, isDebugEnabled)
159                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
160                 }
161                 utils.log("DEBUG"," ***** Exit preProcessRequest of CreateGenericALaCarteServiceInstance *****",  isDebugEnabled)
162         }
163
164         public void sendSyncResponse (DelegateExecution execution) {
165                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
166                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
167
168                 try {
169                         String requestId = execution.getVariable("msoRequestId")
170                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
171                         // RESTResponse for API Handler (APIH) Reply Task
172                         String createServiceRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
173                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + createServiceRestRequest, isDebugEnabled)
174                         sendWorkflowResponse(execution, 202, createServiceRestRequest)
175                         execution.setVariable("sentSyncResponse", true)
176
177                 } catch (Exception ex) {
178                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
179                         utils.log("DEBUG", msg, isDebugEnabled)
180                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
181                 }
182                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
183         }
184
185
186         public void sendSyncError (DelegateExecution execution) {
187                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
188                 utils.log("DEBUG", " *** sendSyncError *** ", isDebugEnabled)
189
190                 try {
191                         String errorMessage = ""
192                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
193                                 WorkflowException wfe = execution.getVariable("WorkflowException")
194                                 errorMessage = wfe.getErrorMessage()
195                         } else {
196                                 errorMessage = "Sending Sync Error."
197                         }
198
199                         String buildworkflowException =
200                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
201                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
202                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
203                                    </aetgt:WorkflowException>"""
204
205                         utils.logAudit(buildworkflowException)
206                         sendWorkflowResponse(execution, 500, buildworkflowException)
207
208                 } catch (Exception ex) {
209                         utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled)
210                 }
211
212         }
213
214         // *******************************
215         //
216         // *******************************
217         public void prepareDecomposeService(DelegateExecution execution) {
218                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
219                 utils.log("DEBUG", " ***** Inside prepareDecomposeService of CreateGenericALaCarteServiceInstance ***** ", isDebugEnabled)
220                 try {
221                         String siRequest = execution.getVariable("bpmnRequest")
222                         String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
223                         execution.setVariable("serviceModelInfo", serviceModelInfo)
224                 } catch (Exception ex) {
225                         // try error in method block
226                         String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
227                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
228                 }
229                 utils.log("DEBUG", " ***** Completed prepareDecomposeService of CreateGenericALaCarteServiceInstance ***** ", isDebugEnabled)
230          }
231          
232          
233          // *******************************
234          //
235          // *******************************
236          public void prepareCreateServiceInstance(DelegateExecution execution) {
237                  def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
238  
239                  try {
240                          utils.log("DEBUG", " ***** Inside prepareCreateServiceInstance of CreateGenericALaCarteServiceInstance ***** ", isDebugEnabled)
241  
242                          /*
243                           * Extracting User Parameters from incoming Request and converting into a Map
244                           */
245                          def jsonSlurper = new JsonSlurper()
246                          def jsonOutput = new JsonOutput()
247                          def siRequest = execution.getVariable("bpmnRequest")
248                          Map reqMap = jsonSlurper.parseText(siRequest)
249                          //InputParams
250                          def userParams = reqMap.requestDetails?.requestParameters?.userParams
251                          Map<String, String> inputMap = [:]
252                          if (userParams != null) {
253                                  userParams.each {
254                                          userParam -> inputMap.put(userParam.name, userParam.value)
255                                  }
256                          }
257                          
258                          utils.log("DEBUG", "User Input Parameters map: " + userParams.toString(), isDebugEnabled)
259                          execution.setVariable("serviceInputParams", inputMap)
260                          
261                          ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
262                         
263                          String serviceInstanceId = execution.getVariable("serviceInstanceId")
264                          serviceDecomposition.getServiceInstance().setInstanceId(serviceInstanceId)
265                          
266                          String serviceInstanceName = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName")
267                          serviceDecomposition.getServiceInstance().setInstanceName(serviceInstanceName)
268                          execution.setVariable("serviceInstanceName", serviceInstanceName)
269                          execution.setVariable("serviceDecomposition", serviceDecomposition)
270                          execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonString())
271                          utils.log("DEBUG", "serviceDecomposition.serviceInstanceName: " + serviceDecomposition.getServiceInstance().getInstanceName(), isDebugEnabled)
272                                                  
273                          utils.log("DEBUG", " ***** Completed prepareCreateServiceInstance of CreateGenericALaCarteServiceInstance ***** ", isDebugEnabled)
274                  } catch (Exception ex) {
275                          // try error in method block
276                          String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
277                          exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
278                  }
279           }
280           
281           
282         public void prepareCompletionRequest (DelegateExecution execution) {
283                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
284                 utils.log("DEBUG", " *** prepareCompletion *** ", isDebugEnabled)
285
286                 try {
287                         String requestId = execution.getVariable("msoRequestId")
288                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
289                         String source = execution.getVariable("source")
290                         
291                         String msoCompletionRequest =
292                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
293                                                                 xmlns:ns="http://org.openecomp/mso/request/types/v1">
294                                                 <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
295                                                         <request-id>${requestId}</request-id>
296                                                         <action>CREATE</action>
297                                                         <source>${source}</source>
298                                                 </request-info>
299                                                 <status-message>Service Instance was created successfully.</status-message>
300                                                 <serviceInstanceId>${serviceInstanceId}</serviceInstanceId>
301                                                 <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name>
302                                         </aetgt:MsoCompletionRequest>"""
303
304                         // Format Response
305                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
306
307                         execution.setVariable("completionRequest", xmlMsoCompletionRequest)
308                         utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
309
310                 } catch (Exception ex) {
311                         String msg = " Exception in prepareCompletion:" + ex.getMessage()
312                         utils.log("DEBUG", msg, isDebugEnabled)
313                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
314                 }
315                 utils.log("DEBUG", "*** Exit prepareCompletionRequest ***", isDebugEnabled)
316         }
317
318         public void prepareFalloutRequest(DelegateExecution execution){
319                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
320                 utils.log("DEBUG", " *** prepareFalloutRequest *** ", isDebugEnabled)
321
322                 try {
323                         WorkflowException wfex = execution.getVariable("WorkflowException")
324                         utils.log("DEBUG", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled)
325                         String requestId = execution.getVariable("msoRequestId")
326                         String source = execution.getVariable("source")
327                         String requestInfo =
328                                         """<request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
329                                         <request-id>${requestId}</request-id>
330                                         <action>CREATE</action>
331                                         <source>${source}</source>
332                                    </request-info>"""
333
334                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
335                         execution.setVariable("falloutRequest", falloutRequest)
336                 } catch (Exception ex) {
337                         utils.log("DEBUG", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled)
338                         String errorException = "  Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
339                         String requestId = execution.getVariable("msoRequestId")
340                         String falloutRequest =
341                                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
342                                                                      xmlns:ns="http://org.openecomp/mso/request/types/v1"
343                                                                      xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">
344                                            <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
345                                               <request-id>${requestId}</request-id>
346                                               <action>CREATE</action>
347                                               <source>VID</source>
348                                            </request-info>
349                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
350                                                         <aetgt:ErrorMessage>${errorException}</aetgt:ErrorMessage>
351                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
352                                                 </aetgt:WorkflowException>
353                                         </aetgt:FalloutHandlerRequest>"""
354
355                         execution.setVariable("falloutRequest", falloutRequest)
356                 }
357                 utils.log("DEBUG", "*** Exit prepareFalloutRequest ***", isDebugEnabled)
358         }
359 }