Merge "add queryparam to catalog db api to filter"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / ScaleCustomE2EServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 CMCC. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24
25 import org.onap.so.logger.LoggingAnchor
26 import org.onap.logging.filter.base.ErrorCode
27
28 import static org.apache.commons.lang3.StringUtils.*
29
30 import org.camunda.bpm.engine.delegate.BpmnError
31 import org.camunda.bpm.engine.delegate.DelegateExecution
32 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
33 import org.onap.so.bpmn.common.scripts.ExceptionUtil
34 import org.onap.so.bpmn.common.scripts.MsoUtils
35 import org.onap.so.bpmn.core.WorkflowException
36 import org.onap.so.bpmn.core.json.JsonUtils
37 import org.onap.so.bpmn.core.UrnPropertiesReader
38 import org.onap.so.logger.MessageEnum
39 import org.slf4j.Logger
40 import org.slf4j.LoggerFactory
41 import org.onap.so.utils.UUIDChecker
42 import org.springframework.web.util.UriUtils
43
44
45 /**
46  * This groovy class supports the <class>ScaleCustomE2EServiceInstance.bpmn</class> process.
47  *
48  */
49 public class ScaleCustomE2EServiceInstance extends AbstractServiceTaskProcessor {
50     private static final Logger logger = LoggerFactory.getLogger( ScaleCustomE2EServiceInstance.class);
51
52     String Prefix = "CRESI_"
53     ExceptionUtil exceptionUtil = new ExceptionUtil()
54     JsonUtils jsonUtil = new JsonUtils()
55
56     public void preProcessRequest(DelegateExecution execution) {
57         execution.setVariable("prefix", Prefix)
58         String msg = ""
59         logger.trace("preProcessRequest() ")
60
61         try {
62
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 = "NULL".toString()
73             }
74             logger.debug("Generated new Service Instance:" + serviceInstanceId)
75             serviceInstanceId = UriUtils.encode(serviceInstanceId, "UTF-8")
76             execution.setVariable("serviceInstanceId", serviceInstanceId)
77
78             // service instance ID is also service ID
79             execution.setVariable("serviceId", serviceInstanceId)
80             // service instance name
81             String serviceInstanceName = jsonUtil.getJsonValue(siRequest, "service.serviceInstanceName")
82             execution.setVariable("serviceInstanceName", serviceInstanceName)
83
84             // service instance name
85             String serviceType = jsonUtil.getJsonValue(siRequest, "service.serviceType")
86             execution.setVariable("serviceType", serviceType)
87
88             // operationa ID (key)
89             //String operationKey = UUIDChecker.generateUUID(msoLogger)
90             String operationId = jsonUtil.getJsonValue(siRequest, "operationId")
91             execution.setVariable("operationId", operationId)
92             logger.debug("Input Request:" + siRequest + " operationId:" + operationId)
93
94
95             String resources = jsonUtil.getJsonValue(siRequest, "service.resources")
96             execution.setVariable("resources", resources)
97
98             // node template UUID
99             String nodeTemplateUUID = UUIDChecker.getUUID();
100             execution.setVariable("nodeTemplateUUID", nodeTemplateUUID)
101
102             //subscriberInfo
103             String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "service.globalSubscriberId")
104             if (isBlank(globalSubscriberId)) {
105                 msg = "Input globalSubscriberId' is null"
106                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
107             } else {
108                 execution.setVariable("globalSubscriberId", globalSubscriberId)
109             }
110
111             String requestDescription = "request description for test"
112             execution.setVariable("requestDescription", requestDescription)
113             execution.setVariable("URN_mso_adapters_openecomp_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter")
114
115         } catch (BpmnError e) {
116             throw e;
117         } catch (Exception ex) {
118             msg = "Exception in preProcessRequest " + ex.getMessage()
119             logger.debug(msg)
120             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
121         }
122         logger.trace("Exit preProcessRequest ")
123     }
124
125     public void sendSyncResponse(DelegateExecution execution) {
126         logger.trace("sendSyncResponse ")
127
128         try {
129             String operationId = execution.getVariable("operationId")
130             String serviceInstanceId = execution.getVariable("serviceInstanceId")
131             // RESTResponse for API Handler (APIH) Reply Task
132                         String scaleServiceRestRequest = """{"operationId":"${operationId}"}""".trim()
133             logger.debug(" sendSyncResponse to APIH:" + "\n" + scaleServiceRestRequest)
134             sendWorkflowResponse(execution, 202, scaleServiceRestRequest)
135             execution.setVariable("sentSyncResponse", true)
136
137         } catch (Exception ex) {
138             String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
139             logger.debug(msg)
140             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
141         }
142         logger.trace("Exit sendSyncResopnse ")
143     }
144
145
146     public void sendSyncError(DelegateExecution execution) {
147         logger.trace("sendSyncError ")
148
149         try {
150             String errorMessage = ""
151             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
152                 WorkflowException wfe = execution.getVariable("WorkflowException")
153                 errorMessage = wfe.getErrorMessage()
154             } else {
155                 errorMessage = "Sending Sync Error."
156             }
157
158             String buildworkflowException =
159                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
160                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
161                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
162                                    </aetgt:WorkflowException>"""
163
164             logger.debug(buildworkflowException)
165             sendWorkflowResponse(execution, 500, buildworkflowException)
166
167         } catch (Exception ex) {
168             logger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
169         }
170
171     }
172
173     public void prepareCompletionRequest(DelegateExecution execution) {
174         logger.trace("prepareCompletion ")
175
176         try {
177             String requestId = execution.getVariable("msoRequestId")
178             String serviceInstanceId = execution.getVariable("serviceInstanceId")
179             String source = execution.getVariable("source")
180
181             String msoCompletionRequest =
182                     """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
183                                                                 xmlns:ns="http://org.onap/so/request/types/v1">
184                                                 <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
185                                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
186                                                         <action>SCALE</action>
187                                                         <source>${MsoUtils.xmlEscape(source)}</source>
188                                                    </request-info>
189                                                 <status-message>Service Instance was scaled successfully.</status-message>
190                                                 <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
191                                                    <mso-bpel-name>ScaleGenericALaCarteServiceInstance</mso-bpel-name>
192                                         </aetgt:MsoCompletionRequest>"""
193
194             // Format Response
195             String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
196
197             execution.setVariable("CompleteMsoProcessRequest", xmlMsoCompletionRequest)
198             logger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
199
200         } catch (Exception ex) {
201             String msg = " Exception in prepareCompletion:" + ex.getMessage()
202             logger.debug(msg)
203             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
204         }
205         logger.trace("Exit prepareCompletionRequest ")
206     }
207
208     public void prepareFalloutRequest(DelegateExecution execution) {
209         logger.trace("prepareFalloutRequest ")
210
211         try {
212             WorkflowException wfex = execution.getVariable("WorkflowException")
213             logger.debug(" Input Workflow Exception: " + wfex.toString())
214             String requestId = execution.getVariable("msoRequestId")
215             String source = execution.getVariable("source")
216             String requestInfo =
217                     """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
218                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
219                                         <action>SCALE</action>
220                                         <source>${MsoUtils.xmlEscape(source)}</source>
221                                    </request-info>"""
222
223             String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
224             execution.setVariable("falloutRequest", falloutRequest)
225         } catch (Exception ex) {
226             logger.debug("Exception prepareFalloutRequest:" + ex.getMessage())
227             String errorException = "  Bpmn error encountered in ScaleGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
228             String requestId = execution.getVariable("msoRequestId")
229             String falloutRequest =
230                     """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
231                                                                                                  xmlns:ns="http://org.onap/so/request/types/v1"
232                                                                                                  xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
233                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
234                                                   <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
235                                                   <action>SCALE</action>
236                                                   <source>UUI</source>
237                                            </request-info>
238                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
239                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage>
240                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
241                                                 </aetgt:WorkflowException>
242                                         </aetgt:FalloutHandlerRequest>"""
243
244             execution.setVariable("falloutRequest", falloutRequest)
245         }
246         logger.trace("Exit prepareFalloutRequest ")
247     }
248
249
250     /**
251      * Init the service Operation Status
252      */
253     public void prepareInitServiceOperationStatus(DelegateExecution execution){
254         logger.trace("STARTED prepareInitServiceOperationStatus Process ")
255         try{
256             String serviceId = execution.getVariable("serviceInstanceId")
257             //String serviceName = execution.getVariable("serviceInstanceName")
258             String operationId = execution.getVariable("operationId")
259             String operationType = "SCALE"
260             String userId = ""
261             String result = "processing"
262             String progress = "0"
263             String reason = ""
264             String operationContent = "Prepare service scaling"
265             execution.setVariable("serviceInstanceId", serviceId)
266             execution.setVariable("operationId", operationId)
267             execution.setVariable("operationType", operationType)
268
269             def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
270             execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
271             logger.info("DB Adapter Endpoint is: " + dbAdapterEndpoint)
272
273             String payload =
274                     """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
275                         xmlns:ns="http://org.onap.so/requestsdb">
276                         <soapenv:Header/>
277                         <soapenv:Body>
278                             <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
279                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
280                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
281                             <serviceName>${MsoUtils.xmlEscape(serviceName)}</serviceName>
282                             <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
283                             <userId>${MsoUtils.xmlEscape(userId)}</userId>
284                             <result>${MsoUtils.xmlEscape(result)}</result>
285                             <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent>
286                             <progress>${MsoUtils.xmlEscape(progress)}</progress>
287                             <reason>${MsoUtils.xmlEscape(reason)}</reason>
288                         </ns:updateServiceOperationStatus>
289                     </soapenv:Body>
290                 </soapenv:Envelope>"""
291
292             payload = utils.formatXml(payload)
293             execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
294             logger.info("Outgoing updateServiceOperStatusRequest: \n" + payload)
295             logger.debug("Scale network service updateServiceOperStatusRequest Request: " + payload)
296
297         }catch(Exception e){
298             logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
299                     "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN",
300                     ErrorCode.UnknownError.getValue(), e);
301             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage())
302         }
303         logger.trace("COMPLETED prepareInitServiceOperationStatus Process ")
304     }
305 }