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