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