2a8f8f15934acb8c76766c54a11f085407abffe6
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / FalloutHandler.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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.common.scripts
24
25 import org.onap.so.bpmn.core.UrnPropertiesReader
26
27 import java.text.SimpleDateFormat
28
29 import org.apache.commons.lang3.*
30 import org.camunda.bpm.engine.delegate.DelegateExecution
31 import org.onap.so.logger.MessageEnum
32 import org.onap.so.logger.MsoLogger
33 import org.slf4j.Logger
34 import org.slf4j.LoggerFactory
35
36 public class FalloutHandler extends AbstractServiceTaskProcessor {
37     private static final Logger logger = LoggerFactory.getLogger( FalloutHandler.class);
38
39         String Prefix="FH_"
40         ExceptionUtil exceptionUtil = new ExceptionUtil()
41
42         public initializeProcessVariables(DelegateExecution execution){
43                 def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')'
44                 logger.trace('Entered ' + method)
45
46                 try {
47                         execution.setVariable("prefix",Prefix)
48
49                         //These variables are form the input Message to the BPMN
50                         execution.setVariable("FH_request_id","")
51                         execution.setVariable("FH_request_action","")
52                         execution.setVariable("FH_notification-url","")
53                         execution.setVariable("FH_mso-bpel-name","")
54                         execution.setVariable("FH_ErrorCode", "")
55                         execution.setVariable("FH_ErrorMessage", "")
56
57                         execution.setVariable("FH_notification-url-Ok", false)
58                         execution.setVariable("FH_request_id-Ok", false)
59
60                         //These variables are for Get Mso Aai Password Adapter
61                         execution.setVariable("FH_deliveryStatus", true)
62         
63                         //update Response Status to pending ...Adapter variables
64                         execution.setVariable("FH_updateResponseStatusPayload", null)
65                         execution.setVariable("FH_updateResponseStatusResponse", null)
66         
67                         //update Request Gamma ...Adapter variables
68                         execution.setVariable("FH_updateRequestGammaPayload", "")
69                         execution.setVariable("FH_updateRequestGammaResponse", null)
70                         execution.setVariable("FH_updateRequestGammaResponseCode", null)
71         
72                         //update Request Infra ...Adapter variables
73                         execution.setVariable("FH_updateRequestInfraPayload", "")
74                         execution.setVariable("FH_updateRequestInfraResponse", null)
75                         execution.setVariable("FH_updateRequestInfraResponseCode", null)
76         
77                         //assign True to success variable
78                         execution.setVariable("FH_success", true)
79         
80                         //Set notify status to Failed variable
81                         execution.setVariable("FH_NOTIFY_STATUS", "SUCCESS")
82         
83                         //Set DB update variable
84                         execution.setVariable("FH_updateRequestPayload", "")
85                         execution.setVariable("FH_updateRequestResponse", null)
86                         execution.setVariable("FH_updateRequestResponseCode", null)
87         
88                         //Auth variables
89                         execution.setVariable("BasicAuthHeaderValue","")
90
91                         //Parameter list
92                         execution.setVariable("FH_parameterList",  "")
93
94                         //Response variables
95                         execution.setVariable("FalloutHandlerResponse","")
96                         execution.setVariable("FH_ErrorResponse", null)
97                         execution.setVariable("FH_ResponseCode", "")
98
99                 } catch (Exception e) {
100                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
101                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
102                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
103                 //      exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
104                 }
105         }
106
107         public void preProcessRequest (DelegateExecution execution) {
108                 def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')'
109                 logger.trace('Entered ' + method)
110
111                 // Initialize flow variables
112                 initializeProcessVariables(execution)
113                 setSuccessIndicator(execution, false)
114
115                 setBasicDBAuthHeader(execution, execution.getVariable('isDebugLogEnabled'))
116
117                 try {
118                         def xml = execution.getVariable("FalloutHandlerRequest")
119                         logger.debug(" XML --> " + xml)
120                         logger.debug("FalloutHandler request: " + xml)
121
122                         //Check the incoming request type
123                         //Incoming request can be ACTIVE_REQUESTS (request-information node) or  INFRA_ACTIVE_REQUESTS (request-info node)
124                         if (utils.nodeExists(xml, "request-information")) {
125                                 execution.setVariable("FH_request_id-Ok", true) // Incoming request is for ACTIVE_REQUESTS
126                         }
127
128                         //Check notification-url for the incoming request type
129                         //ACTIVE_REQUESTS may have notificationurl node
130                         //INFRA_ACTIVE_REQUESTS notificationurl node does not exist
131                         def notificationurl = ""
132                         if (utils.nodeExists(xml, "notification-url")) {
133                                 notificationurl = utils.getNodeText(xml,"notification-url")
134                                 if(notificationurl != null && !notificationurl.isEmpty()) {
135                                         logger.debug("********** Incoming notification Url is: " + notificationurl);
136                                         execution.setVariable("FH_notification-url-Ok", true)
137                                         execution.setVariable("FH_notification-url",notificationurl)
138                                 }
139                         }
140         
141                         //Check request_id for the incoming request type
142                         //For INFRA_ACTIVE_REQUESTS payload request-id IS optional (Not sure why this is option since req id is primary key ... also tried exe through SOAP UI to check if MSO code handles null like auto generated seq not it does not)
143                         //For ACTIVE_REQUESTS payload request-id is NOT optional
144                         def request_id = ""
145                         if (utils.nodeExists(xml, "request-id")) {
146                                 execution.setVariable("FH_request_id",utils.getNodeText(xml,"request-id"))
147                         }
148                         logger.debug("FH_request_id: " + execution.getVariable("FH_request_id"))
149
150                         // INFRA_ACTIVE_REQUESTS         have "action" element ... mandatory
151                         // ACTIVE_REQUEST have "request-action" ... mandatory
152                         if (utils.nodeExists(xml, "request-action")) {
153                                 execution.setVariable("FH_request_action",utils.getNodeText(xml,"request-action"))
154                         } else if (utils.nodeExists(xml, "action")) {
155                                 execution.setVariable("FH_request_action",utils.getNodeText(xml,"action"))
156                         }
157
158
159                         //Check source for the incoming request type
160                         //For INFRA_ACTIVE_REQUESTS payload source IS optional
161                         //For ACTIVE_REQUESTS payload source is NOT optional
162                         def source = ""
163                         if (utils.nodeExists(xml, "source")) {
164                                 execution.setVariable("FH_source",utils.getNodeText(xml,"source"))
165                         }
166
167                         //Check if ErrorCode node exists. If yes, initialize it from request xml, if no, it will stay with defaulf value already set in initializeProcessVariables() method above.
168                         def errorCode = ""
169                         if (utils.nodeExists(xml, "ErrorCode")) {
170                                 errorCode = utils.getNodeText(xml,"ErrorCode")
171                                 if(errorCode != null && !errorCode.isEmpty()) {
172                                         execution.setVariable("FH_ErrorCode", errorCode)
173                                 }
174                         }
175                         logger.debug("FH_ErrorCode: " + errorCode)
176
177                         //Check if ErrorMessage node exists. If yes, initialize it from request xml, if no, it will stay with defaulf value already set in initializeProcessVariables() method above.
178                         def errorMessage = ""
179                         if (utils.nodeExists(xml, "ErrorMessage")) {
180                                 errorCode = utils.getNodeText(xml,"ErrorMessage")
181                                 if(errorCode != null && !errorCode.isEmpty()) {
182                                         errorCode = errorCode
183                                         execution.setVariable("FH_ErrorMessage", errorCode)
184                                 }
185                         }
186
187                         //Check for Parameter List
188                         if (utils.nodeExists(xml, "parameter-list")) {
189                                 def parameterList = utils.getNodeXml(xml, "parameter-list", false)
190                                 execution.setVariable("FH_parameterList", parameterList)
191                         }
192
193                         logger.trace("--> " + execution.getVariable(""))
194                         logger.debug("FH_request_id-OK --> " + execution.getVariable("FH_request_id-Ok"))
195
196                         // set the DHV/Service Instantiation values if specified in the request
197                         execution.setVariable("FH_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText(xml, "is-srv-inst-req"))))
198                         logger.trace("--> " + execution.getVariable(""))
199                         execution.setVariable("FH_is_json_content", String.valueOf("JSON".equals(utils.getNodeText(xml, "resp-content-type"))))
200                         logger.trace("--> " + execution.getVariable(""))
201                         execution.setVariable("FH_service_inst_id", utils.getNodeText(xml, "service-instance-id"))
202                         logger.trace("--> " + execution.getVariable(""))
203                         execution.setVariable("FH_start_time", utils.getNodeText(xml, "start-time"))
204                         logger.trace("--> " + execution.getVariable(""))
205                         // this variable is used by the camunda flow to set the Content-Type for the async response
206                         if (execution.getVariable("FH_is_srv_inst_req").equals("true") &&
207                                 execution.getVariable("FH_is_json_content").equals("true")) {
208                                 execution.setVariable("FH_content_type", "application/json")
209                         } else {
210                                 execution.setVariable("FH_content_type", "text/xml")
211                         }
212                 } catch (Exception e) {
213                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
214                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
215                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
216                 //      exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
217                 }
218
219                 logger.debug("OUTOF --> Initialize Variables Fallout Handler #########");
220         }
221
222         public String updateRequestPayload (DelegateExecution execution){
223                 def method = getClass().getSimpleName() + '.updateRequestPayload(' +'execution=' + execution.getId() +')'
224                 logger.trace('Entered ' + method)
225
226                 try {
227                         String payload = """
228                                         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
229                                         <soapenv:Header/>
230                                         <soapenv:Body>
231                                                 <req:updateRequest>
232                                                         <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId>
233                                                         <lastModifiedBy>BPEL</lastModifiedBy>
234                                                         <finalErrorMessage>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))}</finalErrorMessage>
235                                                         <finalErrorCode>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorCode"))}</finalErrorCode>
236                                                         <status>FAILED</status>
237                                                         <responseStatus>${MsoUtils.xmlEscape(execution.getVariable("FH_NOTIFY_STATUS"))}</responseStatus>
238                                                 </req:updateRequest>
239                                         </soapenv:Body>
240                                         </soapenv:Envelope>
241                                 """
242
243                         logger.debug("updateRequestPayload: " + payload)
244                         execution.setVariable("FH_updateRequestPayload", payload)
245                         return execution.getVariable("FH_updateRequestPayload")
246                 } catch (Exception e) {
247                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
248                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
249                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
250                 //      exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
251                 }
252         }
253
254         public String updateRequestInfraPayload (DelegateExecution execution){
255                 def method = getClass().getSimpleName() + '.updateRequestInfraPayload(' +'execution=' + execution.getId() +')'
256                 logger.trace('Entered ' + method)
257         
258                 try {
259                         String payload = """
260                                         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
261                                         <soapenv:Header/>
262                                         <soapenv:Body>
263                                                 <req:updateInfraRequest>
264                                                         <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId>
265                                                         <lastModifiedBy>BPEL</lastModifiedBy>
266                                                         <statusMessage>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))}</statusMessage>
267                                                         <requestStatus>FAILED</requestStatus>
268                                                         <progress>100</progress>
269                                                 </req:updateInfraRequest>
270                                         </soapenv:Body>
271                                         </soapenv:Envelope>
272                                 """
273         
274                         execution.setVariable("FH_updateRequestInfraPayload", payload)
275                         logger.debug("updateRequestInfraPayload: " + payload)
276                         return execution.getVariable("FH_updateRequestInfraPayload")
277                 } catch (Exception e) {
278                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
279                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
280                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
281                 //      exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
282                 }
283         }
284
285         public String updateRequestGammaPayload (DelegateExecution execution){
286                 def method = getClass().getSimpleName() + '.updateRequestGammaPayload(' +'execution=' + execution.getId() +')'
287                 logger.trace('Entered ' + method)
288
289                 try {
290                         String payload = """
291                                         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="${UrnPropertiesReader.getVariable("mso.default.adapter.namespace", execution)}/requestsdb">
292                                         <soapenv:Header/>
293                                         <soapenv:Body>
294                                                 <req:updateRequest>
295                                                         <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId>
296                                                         <lastModifiedBy>BPEL</lastModifiedBy>
297                                                         <finalErrorMessage>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))}</finalErrorMessage>
298                                                         <finalErrorCode>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorCode"))}</finalErrorCode>
299                                                         <status>FAILED</status>
300                                                 </req:updateRequest>
301                                         </soapenv:Body>
302                                         </soapenv:Envelope>
303                                 """
304
305                         execution.setVariable("FH_updateRequestGammaPayload", payload)
306                         logger.debug("updateRequestGammaPayload: " + payload)
307                         return execution.getVariable("FH_updateRequestGammaPayload")
308                 } catch (Exception e) {
309                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
310                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
311                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
312                 //      exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
313                 }
314         }
315
316         public String updateResponseStatusPayload (DelegateExecution execution){
317                 def method = getClass().getSimpleName() + '.updateResponseStatusPayload(' +'execution=' + execution.getId() +')'
318                 logger.trace('Entered ' + method)
319
320                 try {
321                         String payload = """
322                                         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
323                                         <soapenv:Header/>
324                                         <soapenv:Body>
325                                                 <req:updateResponseStatus>
326                                                         <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId>
327                                                         <lastModifiedBy>BPEL</lastModifiedBy>
328                                                         <responseStatus>SENDING_FINAL_NOTIFY</responseStatus>
329                                                 </req:updateResponseStatus>
330                                         </soapenv:Body>
331                                         </soapenv:Envelope>
332                                 """
333
334                         execution.setVariable("FH_updateResponseStatusPayload", payload)
335                         logger.debug("updateResponseStatusPayload: " + payload)
336                         return execution.getVariable("FH_updateResponseStatusPayload")
337                 } catch (Exception e) {
338                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
339                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
340                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
341                 //      exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
342                 }
343         }
344
345         public void buildDBWorkflowException(DelegateExecution execution, String responseCodeVariable) {
346                 def method = getClass().getSimpleName() + '.buildDBWorkflowException(' +
347                         'execution=' + execution.getId() +
348                         ', responseCodeVariable=' + responseCodeVariable + ')'
349                 logger.trace('Entered ' + method)
350
351                 try {
352                         def responseCode = execution.getVariable(responseCodeVariable)
353                         // If the HTTP response code was null, it means a connection fault occurred (a java exception)
354                         def errorMessage = responseCode == null ? "Could not connect to DB Adapter" : "DB Adapter returned ${responseCode} response"
355                         def errorCode = responseCode == null ? 7000 : 7020
356                 //      exceptionUtil.buildWorkflowException(execution, errorCode, errorMessage)
357                 } catch (Exception e) {
358                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
359                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
360                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
361                 //      exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
362                 }
363         }
364
365         /**
366          * Used to create a workflow response in success and failure cases.
367          */
368         public void postProcessResponse (DelegateExecution execution) {
369                 def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')'
370                 logger.trace('Entered ' + method)
371
372                 try {
373                         Boolean success = (Boolean) execution.getVariable("FH_success")
374                         String out = success ? "Fallout Handler Succeeded" : "Fallout Handler Failed";
375
376                         String falloutHandlerResponse = """
377                                         <workflow:FalloutHandlerResponse xmlns:workflow="http://org.onap/so/workflow/schema/v1">
378                                            <workflow:out>${MsoUtils.xmlEscape(out)}</workflow:out>
379                                         </workflow:FalloutHandlerResponse>
380                                 """
381
382                         falloutHandlerResponse = utils.formatXml(falloutHandlerResponse)
383                         logger.debug("FalloutHandler Response: " + falloutHandlerResponse);
384
385                         execution.setVariable("FalloutHandlerResponse", falloutHandlerResponse)
386                         execution.setVariable("WorkflowResponse", falloutHandlerResponse)
387                         execution.setVariable("FH_ResponseCode", success ? "200" : "500")
388                         setSuccessIndicator(execution, success)
389
390                         logger.debug("FalloutHandlerResponse =\n" + falloutHandlerResponse)
391                 } catch (Exception e) {
392                         // Do NOT throw WorkflowException!
393                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
394                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
395                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
396                 }
397         }
398 }