7f4f78762e24f368c72422e5d8d4793a9a413653
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / CreateCustomE2EServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. 
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.mso.bpmn.infrastructure.scripts;
23
24 import static org.apache.commons.lang3.StringUtils.*;
25 import groovy.xml.XmlUtil
26 import groovy.json.*
27 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
28 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
29
30 import org.openecomp.mso.bpmn.core.WorkflowException
31 import org.openecomp.mso.bpmn.core.json.JsonUtils
32 import org.openecomp.mso.rest.APIResponse
33
34 import java.util.UUID;
35
36 import org.camunda.bpm.engine.delegate.BpmnError
37 import org.camunda.bpm.engine.runtime.Execution
38 import org.apache.commons.lang3.*
39 import org.apache.commons.codec.binary.Base64;
40 import org.springframework.web.util.UriUtils
41
42 /**
43  * This groovy class supports the <class>CreateServiceInstance.bpmn</class> process.
44  * AlaCarte flow for 1702 ServiceInstance Create
45  *
46  */
47 public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor {
48         String Prefix="CRESI_"
49         ExceptionUtil exceptionUtil = new ExceptionUtil()
50         JsonUtils jsonUtil = new JsonUtils()
51
52
53         public void preProcessRequest (Execution execution) {
54                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
55                 execution.setVariable("prefix",Prefix)
56                 String msg = ""
57                 utils.log("DEBUG", " *** preProcessRequest() *** ", isDebugEnabled)
58
59                 try {
60
61                         String siRequest = execution.getVariable("bpmnRequest")
62                         utils.logAudit(siRequest)
63
64                         String requestId = execution.getVariable("mso-request-id")
65                         execution.setVariable("msoRequestId", requestId)
66                         utils.log("DEBUG", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled)
67
68                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
69                         if (isBlank(serviceInstanceId)) {
70                                 serviceInstanceId = UUID.randomUUID().toString()
71                         }
72                         utils.log("DEBUG", "Generated new Service Instance:" + serviceInstanceId, isDebugEnabled)
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 = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
90                         if (isBlank(productFamilyId))
91                         {
92                                 msg = "Input productFamilyId is null"
93                                 utils.log("DEBUG", msg, isDebugEnabled)
94                                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
95                         } else {
96                                 execution.setVariable("productFamilyId", productFamilyId)
97                         }
98
99                         //modelInfo
100                         String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
101                         if (isBlank(serviceModelInfo)) {
102                                 msg = "Input serviceModelInfo is null"
103                                 utils.log("DEBUG", msg, isDebugEnabled)
104                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
105                         } else
106                         {
107                                 execution.setVariable("serviceModelInfo", serviceModelInfo)
108                         }
109
110                         utils.log("DEBUG", "modelInfo" + serviceModelInfo,  isDebugEnabled)
111
112                         //requestParameters
113                         String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType")
114                         if (isBlank(subscriptionServiceType)) {
115                                 msg = "Input subscriptionServiceType is null"
116                                 utils.log("DEBUG", msg, isDebugEnabled)
117                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
118                         } else {
119                                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
120                         }
121
122                         
123                         /*
124                          * Extracting User Parameters from incoming Request and converting into a Map
125                          */
126                         def jsonSlurper = new JsonSlurper()
127                         def jsonOutput = new JsonOutput()
128
129                         Map reqMap = jsonSlurper.parseText(siRequest)
130
131                         //InputParams
132                         def userParams = reqMap.requestDetails?.requestParameters?.userParams
133
134                         Map<String, String> inputMap = [:]
135                         if (userParams) {
136                                 userParams.each {
137                                         userParam -> inputMap.put(userParam.name, userParam.value)
138                                 }
139                         }
140                         
141                         utils.log("DEBUG", "User Input Parameters map: " + userParams.toString(), isDebugEnabled)
142                         execution.setVariable("serviceInputParams", inputMap)
143                         
144                         //TODO
145                         //execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams"))
146                         //execution.setVariable("failExists", true)
147
148                 } catch (BpmnError e) {
149                         throw e;
150                 } catch (Exception ex){
151                         msg = "Exception in preProcessRequest " + ex.getMessage()
152                         utils.log("DEBUG", msg, isDebugEnabled)
153                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
154                 }
155                 utils.log("DEBUG"," ***** Exit preProcessRequest *****",  isDebugEnabled)
156         }
157
158         public void sendSyncResponse (Execution execution) {
159                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
160                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
161
162                 try {
163                         String requestId = execution.getVariable("msoRequestId")
164                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
165                         // RESTResponse for API Handler (APIH) Reply Task
166                         String createServiceRestRequest = """{"service":{"serviceId":"${serviceInstanceId}","operationId":"${requestId}"}}""".trim()
167                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + createServiceRestRequest, isDebugEnabled)
168                         sendWorkflowResponse(execution, 202, createServiceRestRequest)
169                         execution.setVariable("sentSyncResponse", true)
170
171                 } catch (Exception ex) {
172                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
173                         utils.log("DEBUG", msg, isDebugEnabled)
174                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
175                 }
176                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
177         }
178
179
180         public void sendSyncError (Execution execution) {
181                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
182                 utils.log("DEBUG", " *** sendSyncError *** ", isDebugEnabled)
183
184                 try {
185                         String errorMessage = ""
186                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
187                                 WorkflowException wfe = execution.getVariable("WorkflowException")
188                                 errorMessage = wfe.getErrorMessage()
189                         } else {
190                                 errorMessage = "Sending Sync Error."
191                         }
192
193                         String buildworkflowException =
194                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">\r
195                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
196                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
197                                    </aetgt:WorkflowException>"""
198
199                         utils.logAudit(buildworkflowException)
200                         sendWorkflowResponse(execution, 500, buildworkflowException)
201
202                 } catch (Exception ex) {
203                         utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled)
204                 }
205
206         }
207
208         public void prepareCompletionRequest (Execution execution) {
209                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
210                 utils.log("DEBUG", " *** prepareCompletion *** ", isDebugEnabled)
211
212                 try {
213                         String requestId = execution.getVariable("msoRequestId")
214                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
215                         String source = execution.getVariable("source")
216                         
217                         String msoCompletionRequest =
218                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"\r
219                                                                 xmlns:ns="http://org.openecomp/mso/request/types/v1">\r
220                                                 <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">\r
221                                                         <request-id>${requestId}</request-id>
222                                                         <action>CREATE</action>
223                                                         <source>${source}</source>
224                                                 </request-info>
225                                                 <status-message>Service Instance was created successfully.</status-message>
226                                                 <serviceInstanceId>${serviceInstanceId}</serviceInstanceId>
227                                                 <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name>
228                                         </aetgt:MsoCompletionRequest>"""
229
230                         // Format Response
231                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
232
233                         execution.setVariable("completionRequest", xmlMsoCompletionRequest)
234                         utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
235
236                 } catch (Exception ex) {
237                         String msg = " Exception in prepareCompletion:" + ex.getMessage()
238                         utils.log("DEBUG", msg, isDebugEnabled)
239                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
240                 }
241                 utils.log("DEBUG", "*** Exit prepareCompletionRequest ***", isDebugEnabled)
242         }
243
244         public void prepareFalloutRequest(Execution execution){
245                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
246                 utils.log("DEBUG", " *** prepareFalloutRequest *** ", isDebugEnabled)
247
248                 try {
249                         WorkflowException wfex = execution.getVariable("WorkflowException")
250                         utils.log("DEBUG", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled)
251                         String requestId = execution.getVariable("msoRequestId")
252                         String source = execution.getVariable("source")
253                         String requestInfo =
254                                         """<request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">\r
255                                         <request-id>${requestId}</request-id>
256                                         <action>CREATE</action>
257                                         <source>${source}</source>
258                                    </request-info>"""
259
260                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
261                         execution.setVariable("falloutRequest", falloutRequest)
262                 } catch (Exception ex) {
263                         utils.log("DEBUG", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled)
264                         String errorException = "  Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
265                         String requestId = execution.getVariable("msoRequestId")
266                         String falloutRequest =
267                                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"\r
268                                                                      xmlns:ns="http://org.openecomp/mso/request/types/v1"\r
269                                                                      xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">\r
270                                            <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">\r
271                                               <request-id>${requestId}</request-id>
272                                               <action>CREATE</action>
273                                               <source>UUI</source>
274                                            </request-info>
275                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">\r
276                                                         <aetgt:ErrorMessage>${errorException}</aetgt:ErrorMessage>
277                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
278                                                 </aetgt:WorkflowException>
279                                         </aetgt:FalloutHandlerRequest>"""
280
281                         execution.setVariable("falloutRequest", falloutRequest)
282                 }
283                 utils.log("DEBUG", "*** Exit prepareFalloutRequest ***", isDebugEnabled)
284         }
285         
286         /**
287          * Init the service Operation Status
288          */
289         public void prepareInitServiceOperationStatus(Execution execution){
290         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
291         utils.log("DEBUG", " ======== STARTED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled)
292         try{
293             String serviceId = execution.getVariable("serviceInstanceId")
294             String operationId = UUID.randomUUID().toString()
295             String operationType = "CREATE"
296             String userId = ""
297             String result = "processing"
298             String progress = "0"
299             String reason = ""
300             String operationContent = "Prepare service creation"
301             utils.log("DEBUG", "Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId, isDebugEnabled)
302             serviceId = UriUtils.encode(serviceId,"UTF-8")
303             execution.setVariable("serviceInstanceId", serviceId)
304             execution.setVariable("operationId", operationId)
305             execution.setVariable("operationType", operationType)
306
307             def dbAdapterEndpoint = execution.getVariable("URN_mso_openecomp_adapters_db_endpoint")
308             execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
309             utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled)
310
311             String payload =
312                 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
313                         xmlns:ns="http://org.openecomp.mso/requestsdb">
314                         <soapenv:Header/>
315                         <soapenv:Body>
316                             <ns:updateServiceOperationStatus xmlns:ns="http://org.openecomp.mso/requestsdb">
317                             <serviceId>${serviceId}</serviceId>
318                             <operationId>${operationId}</operationId>
319                             <operationType>${operationType}</operationType>
320                             <userId>${userId}</responseBody>
321                             <result>${result}</result>
322                             <operationContent>${operationContent}</operationContent>
323                             <progress>${progress}</progress>
324                             <reason>${reason}</reason>
325                         </ns:updateServiceOperationStatus>
326                     </soapenv:Body>
327                 </soapenv:Envelope>"""
328
329             payload = utils.formatXml(payload)
330             execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
331             utils.log("DEBUG", "Outgoing updateServiceOperStatusRequest: \n" + payload, isDebugEnabled)
332             utils.logAudit("CreateVfModuleInfra Outgoing updateServiceOperStatusRequest Request: " + payload)
333
334         }catch(Exception e){
335             utils.log("ERROR", "Exception Occured Processing prepareInitServiceOperationStatus. Exception is:\n" + e, isDebugEnabled)
336             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage())
337         }
338         utils.log("DEBUG", "======== COMPLETED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled)    
339         }
340 }