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