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