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