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