450c5b1147328f1b97924d8ebc20e849af792f84
[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.List;
35 import java.util.UUID;
36
37 import org.camunda.bpm.engine.delegate.BpmnError
38 import org.camunda.bpm.engine.runtime.Execution
39 import org.apache.commons.lang3.*
40 import org.apache.commons.codec.binary.Base64;
41 import org.springframework.web.util.UriUtils
42
43 /**
44  * This groovy class supports the <class>CreateServiceInstance.bpmn</class> process.
45  * AlaCarte flow for 1702 ServiceInstance Create
46  *
47  */
48 public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor {
49         String Prefix="CRESI_"
50         ExceptionUtil exceptionUtil = new ExceptionUtil()
51         JsonUtils jsonUtil = new JsonUtils()
52
53
54         public void preProcessRequest (Execution execution) {
55                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
56                 execution.setVariable("prefix",Prefix)
57                 String msg = ""
58                 utils.log("INFO", " *** preProcessRequest() *** ", isDebugEnabled)
59
60                 try {
61
62                         String siRequest = execution.getVariable("bpmnRequest")
63                         utils.logAudit(siRequest)
64
65                         String requestId = execution.getVariable("mso-request-id")
66                         execution.setVariable("msoRequestId", requestId)
67                         utils.log("INFO", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled)
68
69                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
70                         if (isBlank(serviceInstanceId)) {
71                                 serviceInstanceId = UUID.randomUUID().toString()
72                         }
73                         utils.log("INFO", "Generated new Service Instance:" + serviceInstanceId, isDebugEnabled)
74                         serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8")
75                         execution.setVariable("serviceInstanceId", serviceInstanceId)
76
77                         //subscriberInfo
78                         String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId")
79                         if (isBlank(globalSubscriberId)) {
80                                 msg = "Input globalSubscriberId' is null"
81                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
82                         } else {
83                                 execution.setVariable("globalSubscriberId", globalSubscriberId)
84                         }
85
86                         //requestInfo
87                         execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source"))
88                         execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName"))
89                         execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback"))
90                         String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
91                         if (isBlank(productFamilyId))
92                         {
93                                 msg = "Input productFamilyId is null"
94                                 utils.log("INFO", msg, isDebugEnabled)
95                                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
96                         } else {
97                                 execution.setVariable("productFamilyId", productFamilyId)
98                         }
99                  String userParams = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams")      
100              utils.log("INFO", "userParams:" + userParams, isDebugEnabled)
101                  List<String> paramList = jsonUtil.StringArrayToList(execution, userParams)
102                  String uuiRequest = jsonUtil.getJsonValue(paramList.get(0), "UUIRequest")
103                         //modelInfo
104                         if (isBlank(uuiRequest)) {
105                                 msg = "Input uuiRequest is null"
106                                 utils.log("INFO", msg, isDebugEnabled)
107                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
108                         } else
109                         {
110                                 execution.setVariable("uuiRequest", uuiRequest)
111                         }
112
113                         utils.log("INFO", "uuiRequest:\n" + uuiRequest,  isDebugEnabled)
114
115                         //requestParameters
116                         String serviceType = jsonUtil.getJsonValue(uuiRequest, "service.parameters.serviceType")
117                         if (isBlank(serviceType)) {
118                                 msg = "Input serviceType is null"
119                                 utils.log("INFO", msg, isDebugEnabled)
120                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
121                         } else {
122                                 execution.setVariable("serviceType", serviceType)
123                         }
124                         execution.setVariable("URN_mso_adapters_openecomp_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter")
125
126                 } catch (BpmnError e) {
127                         throw e;
128                 } catch (Exception ex){
129                         msg = "Exception in preProcessRequest " + ex.getMessage()
130                         utils.log("INFO", msg, isDebugEnabled)
131                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
132                 }
133                 utils.log("INFO"," ***** Exit preProcessRequest *****",  isDebugEnabled)
134         }
135
136         public void sendSyncResponse (Execution execution) {
137                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
138                 utils.log("INFO", " *** sendSyncResponse *** ", isDebugEnabled)
139
140                 try {
141                         String operationId = execution.getVariable("operationId")
142                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
143                         // RESTResponse for API Handler (APIH) Reply Task
144                         String createServiceRestRequest = """{"service":{"serviceId":"${serviceInstanceId}","operationId":"${operationId}"}}""".trim()
145                         utils.log("INFO", " sendSyncResponse to APIH:" + "\n" + createServiceRestRequest, isDebugEnabled)
146                         sendWorkflowResponse(execution, 202, createServiceRestRequest)
147                         execution.setVariable("sentSyncResponse", true)
148
149                 } catch (Exception ex) {
150                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
151                         utils.log("INFO", msg, isDebugEnabled)
152                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
153                 }
154                 utils.log("INFO"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
155         }
156
157
158         public void sendSyncError (Execution execution) {
159                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
160                 utils.log("INFO", " *** sendSyncError *** ", isDebugEnabled)
161
162                 try {
163                         String errorMessage = ""
164                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
165                                 WorkflowException wfe = execution.getVariable("WorkflowException")
166                                 errorMessage = wfe.getErrorMessage()
167                         } else {
168                                 errorMessage = "Sending Sync Error."
169                         }
170
171                         String buildworkflowException =
172                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">\r
173                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
174                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
175                                    </aetgt:WorkflowException>"""
176
177                         utils.logAudit(buildworkflowException)
178                         sendWorkflowResponse(execution, 500, buildworkflowException)
179
180                 } catch (Exception ex) {
181                         utils.log("INFO", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled)
182                 }
183
184         }
185
186         public void prepareCompletionRequest (Execution execution) {
187                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
188                 utils.log("INFO", " *** prepareCompletion *** ", isDebugEnabled)
189
190                 try {
191                         String requestId = execution.getVariable("msoRequestId")
192                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
193                         String source = execution.getVariable("source")
194                         
195                         String msoCompletionRequest =
196                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"\r
197                                                                 xmlns:ns="http://org.openecomp/mso/request/types/v1">\r
198                                                 <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">\r
199                                                         <request-id>${requestId}</request-id>
200                                                         <action>CREATE</action>
201                                                         <source>${source}</source>
202                                                 </request-info>
203                                                 <status-message>Service Instance was created successfully.</status-message>
204                                                 <serviceInstanceId>${serviceInstanceId}</serviceInstanceId>
205                                                 <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name>
206                                         </aetgt:MsoCompletionRequest>"""
207
208                         // Format Response
209                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
210
211                         execution.setVariable("completionRequest", xmlMsoCompletionRequest)
212                         utils.log("INFO", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
213
214                 } catch (Exception ex) {
215                         String msg = " Exception in prepareCompletion:" + ex.getMessage()
216                         utils.log("INFO", msg, isDebugEnabled)
217                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
218                 }
219                 utils.log("INFO", "*** Exit prepareCompletionRequest ***", isDebugEnabled)
220         }
221
222         public void prepareFalloutRequest(Execution execution){
223                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
224                 utils.log("INFO", " *** prepareFalloutRequest *** ", isDebugEnabled)
225
226                 try {
227                         WorkflowException wfex = execution.getVariable("WorkflowException")
228                         utils.log("INFO", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled)
229                         String requestId = execution.getVariable("msoRequestId")
230                         String source = execution.getVariable("source")
231                         String requestInfo =
232                                         """<request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">\r
233                                         <request-id>${requestId}</request-id>
234                                         <action>CREATE</action>
235                                         <source>${source}</source>
236                                    </request-info>"""
237
238                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
239                         execution.setVariable("falloutRequest", falloutRequest)
240                 } catch (Exception ex) {
241                         utils.log("INFO", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled)
242                         String errorException = "  Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
243                         String requestId = execution.getVariable("msoRequestId")
244                         String falloutRequest =
245                                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"\r
246                                                                      xmlns:ns="http://org.openecomp/mso/request/types/v1"\r
247                                                                      xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">\r
248                                            <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">\r
249                                               <request-id>${requestId}</request-id>
250                                               <action>CREATE</action>
251                                               <source>UUI</source>
252                                            </request-info>
253                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">\r
254                                                         <aetgt:ErrorMessage>${errorException}</aetgt:ErrorMessage>
255                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
256                                                 </aetgt:WorkflowException>
257                                         </aetgt:FalloutHandlerRequest>"""
258
259                         execution.setVariable("falloutRequest", falloutRequest)
260                 }
261                 utils.log("INFO", "*** Exit prepareFalloutRequest ***", isDebugEnabled)
262         }
263         
264         /**
265          * Init the service Operation Status
266          */
267         public void prepareInitServiceOperationStatus(Execution execution){
268         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
269         utils.log("INFO", " ======== STARTED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled)
270         try{
271             String serviceId = execution.getVariable("serviceInstanceId")
272             String operationId = UUID.randomUUID().toString()
273             String serviceName = execution.getVariable("serviceInstanceName")
274             String operationType = "CREATE"
275             String userId = ""
276             String result = "processing"
277             String progress = "0"
278             String reason = ""
279             String operationContent = "Prepare service creation"
280             utils.log("INFO", "Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId, isDebugEnabled)
281             serviceId = UriUtils.encode(serviceId,"UTF-8")
282             execution.setVariable("serviceInstanceId", serviceId)
283             execution.setVariable("operationId", operationId)
284             execution.setVariable("operationType", operationType)
285
286             def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint")
287             execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
288             utils.log("INFO", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled)
289
290             String payload =
291                 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
292                         xmlns:ns="http://org.openecomp.mso/requestsdb">
293                         <soapenv:Header/>
294                         <soapenv:Body>
295                             <ns:updateServiceOperationStatus xmlns:ns="http://org.openecomp.mso/requestsdb">
296                             <serviceId>${serviceId}</serviceId>
297                             <operationId>${operationId}</operationId>
298                             <serviceName>${serviceName}</serviceName>
299                             <operationType>${operationType}</operationType>
300                             <userId>${userId}</userId>
301                             <result>${result}</result>
302                             <operationContent>${operationContent}</operationContent>
303                             <progress>${progress}</progress>
304                             <reason>${reason}</reason>
305                         </ns:updateServiceOperationStatus>
306                     </soapenv:Body>
307                 </soapenv:Envelope>"""
308
309             payload = utils.formatXml(payload)
310             execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
311             utils.log("INFO", "Outgoing updateServiceOperStatusRequest: \n" + payload, isDebugEnabled)
312             utils.logAudit("CreateVfModuleInfra Outgoing updateServiceOperStatusRequest Request: " + payload)
313
314         }catch(Exception e){
315             utils.log("ERROR", "Exception Occured Processing prepareInitServiceOperationStatus. Exception is:\n" + e, isDebugEnabled)
316             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage())
317         }
318         utils.log("INFO", "======== COMPLETED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled)    
319         }
320         
321 }