Cleaned up content of MsoLogger
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / CompleteMsoProcess.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.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.delegate.DelegateExecution
27 import org.onap.so.logger.MessageEnum
28 import org.onap.so.logger.MsoLogger
29 import org.slf4j.Logger
30 import org.slf4j.LoggerFactory
31
32 public class CompleteMsoProcess extends AbstractServiceTaskProcessor {
33     private static final Logger logger = LoggerFactory.getLogger( CompleteMsoProcess.class);
34
35         String Prefix="CMSO_"
36         ExceptionUtil exceptionUtil = new ExceptionUtil()
37
38         // Complete MSO Request processing
39         public initializeProcessVariables(DelegateExecution execution){
40
41                 def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')'
42                 logger.trace('Entered ' + method)
43                 try {
44
45                         /* Initialize all the process request variables in this block */
46                         execution.setVariable("prefix",Prefix)
47                         execution.setVariable("CMSO_request_id","")
48                         execution.setVariable("CMSO_notification-url","")
49                         execution.setVariable("CMSO_mso-bpel-name","")
50                         execution.setVariable("CMSO_request_action","")
51                         execution.setVariable("CMSO_notification-url-Ok", false)
52                         execution.setVariable("CMSO_request_id-Ok", false)
53
54                         //updateRequest Adapter process variables
55                         execution.setVariable("CMSO_updateRequestResponse", "")
56                         execution.setVariable("CMSO_updateRequestResponseCode", "")
57                         execution.setVariable("CMSO_updateFinalNotifyAckStatusFailedPayload", "")
58
59                         //Set DB adapter variables here
60                         execution.setVariable("CMSO_updateDBStatusToSuccessPayload", "")
61                         execution.setVariable("CMSO_updateInfraRequestDBPayload", "")
62                         execution.setVariable("CMSO_setUpdateDBstatustoSuccessPayload", "")
63
64                         //Auth variables
65                         execution.setVariable("BasicAuthHeaderValue","")
66
67                         //Response variables
68                         execution.setVariable("CompletionHandlerResponse","")
69                         execution.setVariable("CMSO_ErrorResponse", null)
70                         execution.setVariable("CMSO_ResponseCode", "")
71
72                         setSuccessIndicator(execution, false)
73
74                 } catch (BpmnError e) {
75                         throw e;
76                 } catch (Exception e) {
77                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' +
78                                         ' ' + method, "BPMN", MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
79                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
80                 }
81
82         }
83
84         public void preProcessRequest (DelegateExecution execution) {
85
86                 initializeProcessVariables(execution)
87                 def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')'
88                 //              logger.trace("Started CompleteMsoProcess preProcessRequest Method ");
89                 logger.trace('Entered ' + method)
90
91                 setBasicDBAuthHeader(execution, execution.getVariable('isDebugLogEnabled'))
92
93                 try {
94                         def xml = execution.getVariable("CompleteMsoProcessRequest")
95
96                         logger.debug("CompleteMsoProcess Request: " + xml)
97                         logger.debug("Incoming Request is: "+ xml)
98
99                         //mso-bpel-name from the incoming request
100                         def msoBpelName = utils.getNodeText(xml,"mso-bpel-name")
101                         execution.setVariable("CMSO_mso-bpel-name",msoBpelName)
102
103                         //Check the incoming request type
104                         //Incoming request can be ACTIVE_REQUESTS (request-information node) or  INFRA_ACTIVE_REQUESTS (request-info node)
105                         if (utils.nodeExists(xml, "request-information")) {
106                                 execution.setVariable("CMSO_request_id-Ok", true) // Incoming request is for ACTIVE_REQUESTS
107                         }
108
109                         //Check for rehome indicator
110                         def rehomeIndicator = utils.getNodeText(xml,"rehomeDone")
111                         execution.setVariable("rehomeDone", rehomeIndicator)
112
113                         //Check notification-url for the incoming request type
114                         //ACTIVE_REQUESTS may have notificationurl node
115                         //INFRA_ACTIVE_REQUESTS notificationurl node does not exist
116                         def notificationurl = ""
117                         if (utils.nodeExists(xml, "notification-url")) {
118                                 notificationurl = utils.getNodeText(xml,"notification-url")
119                                 if(notificationurl != null && !notificationurl.isEmpty()) {
120                                         execution.setVariable("CMSO_notification-url-Ok", true)
121                                         execution.setVariable("CMSO_notification-url",notificationurl)
122                                 }
123                         }
124
125                         //Check request_id for the incoming request type
126                         //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)
127                         //For ACTIVE_REQUESTS payload request-id is NOT optional
128                         def request_id = ""
129                         if (utils.nodeExists(xml, "request-id")) {
130                                 execution.setVariable("CMSO_request_id",utils.getNodeText(xml,"request-id"))
131                         }
132
133
134                         // INFRA_ACTIVE_REQUESTS         have "action" element ... mandatory
135                         // ACTIVE_REQUEST have "request-action" ... mandatory
136                         if (utils.nodeExists(xml, "request-action")) {
137                                 execution.setVariable("CMSO_request_action",utils.getNodeText(xml,"request-action"))
138                         } else if (utils.nodeExists(xml, "action")) {
139                                 execution.setVariable("CMSO_request_action",utils.getNodeText(xml,"action"))
140                         }
141
142                         //Check source for the incoming request type
143                         //For INFRA_ACTIVE_REQUESTS payload source IS optional
144                         //For ACTIVE_REQUESTS payload source is NOT optional
145                         def source = ""
146                         if (utils.nodeExists(xml, "source")) {
147                                 execution.setVariable("CMSO_source",utils.getNodeText(xml,"source"))
148                         }
149
150                         logger.trace("--> " + execution.getVariable(""))
151                         logger.trace("--> " + execution.getVariable(""))
152
153                         // set the DHV/Service Instantiation values if specified in the request
154                         execution.setVariable("CMSO_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText(xml, "is-srv-inst-req"))))
155                         logger.trace("--> " + execution.getVariable(""))
156                         execution.setVariable("CMSO_is_json_content", String.valueOf("JSON".equals(utils.getNodeText(xml, "resp-content-type"))))
157                         logger.trace("--> " + execution.getVariable(""))
158                         execution.setVariable("CMSO_service_inst_id", utils.getNodeText(xml, "service-instance-id"))
159                         logger.trace("--> " + execution.getVariable(""))
160                         execution.setVariable("CMSO_start_time", utils.getNodeText(xml, "start-time"))
161                         logger.trace("--> " + execution.getVariable(""))
162                         // this variable is used by the camunda flow to set the Content-Type for the async response
163                         if (execution.getVariable("CMSO_is_srv_inst_req").equals("true") &&
164                                 execution.getVariable("CMSO_is_json_content").equals("true")) {
165                                 execution.setVariable("CMSO_content_type", "application/json")
166                         } else {
167                                 execution.setVariable("CMSO_content_type", "text/xml")
168                         }
169
170                         logger.trace('Exited ' + method)
171                 } catch (BpmnError e) {
172                         throw e;
173                 } catch (Exception e) {
174                         logger.debug("Exception Occured During PreProcessRequest: " + e);
175                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
176                 }
177         }
178
179         public void setUpdateDBstatustoSuccessPayload (DelegateExecution execution){
180
181                 def method = getClass().getSimpleName() + '.setUpdateDBstatustoSuccessPayload(' +'execution=' + execution.getId() +')'
182                 logger.trace('Entered ' + method)
183
184                 try {
185
186                         def xml = execution.getVariable("CompleteMsoProcessRequest")
187
188                         //Get statusMessage if exists
189                         def statusMessage
190                         if(utils.nodeExists(xml, "status-message")){
191                                 statusMessage = utils.getNodeText(xml, "status-message")
192                         }else{
193                                 statusMessage = "Resource Completed Successfully"
194                         }
195
196                         //Get instance Id if exist
197                         String idXml = ""
198                         if(utils.nodeExists(xml, "vnfId")){
199                                 idXml = utils.getNodeXml(xml, "vnfId")
200                         }else if(utils.nodeExists(xml, "networkId")){
201                                 idXml = utils.getNodeXml(xml, "networkId")
202                         }else if(utils.nodeExists(xml, "configurationId")){
203                                 idXml = utils.getNodeXml(xml, "configurationId")
204                         }else if(utils.nodeExists(xml, "serviceInstanceId")){
205                                 idXml = utils.getNodeXml(xml, "serviceInstanceId")
206                         }else if(utils.nodeExists(xml, "vfModuleId")){
207                                 idXml = utils.getNodeXml(xml, "vfModuleId")
208                         }else if(utils.nodeExists(xml, "volumeGroupId")){
209                                 idXml = utils.getNodeXml(xml, "volumeGroupId")
210                         }else{
211                                 idXml = ""
212                         }
213                         idXml = utils.removeXmlPreamble(idXml)
214                         idXml = utils.removeXmlNamespaces(idXml)
215                         logger.debug("Incoming Instance Id Xml: " + idXml)
216
217                         String payload = """
218                                                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
219                                                    <soapenv:Header/>
220                                                    <soapenv:Body>
221                                                       <req:updateInfraRequest>
222                                                          <requestId>${MsoUtils.xmlEscape(execution.getVariable("CMSO_request_id"))}</requestId>
223                                                          <lastModifiedBy>${MsoUtils.xmlEscape(execution.getVariable("CMSO_mso-bpel-name"))}</lastModifiedBy>
224                                                          <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage>
225                                                          <requestStatus>COMPLETE</requestStatus>
226                                                                  <progress>100</progress>
227                                                                  ${idXml}
228                                                       </req:updateInfraRequest>
229                                                    </soapenv:Body>
230                                                 </soapenv:Envelope>"""
231
232                         execution.setVariable("CMSO_setUpdateDBstatustoSuccessPayload", payload)
233                         logger.debug("Outgoing Update Mso Request Payload is: " + payload)
234                         logger.debug("setUpdateDBstatustoSuccessPayload: " + payload)
235
236                 } catch (BpmnError e) {
237                         throw e;
238                 } catch (Exception e) {
239                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
240                                         'Caught exception in ' + method, "BPMN",
241                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
242                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
243                 }
244                 logger.trace('Exited ' + method)
245         }
246
247         public void buildDataError (DelegateExecution execution, String message) {
248
249                 def method = getClass().getSimpleName() + '.buildDataError(' +'execution=' + execution.getId() +')'
250                 logger.trace('Entered ' + method)
251                 try {
252
253                         String msoCompletionResponse = """
254                         <sdncadapterworkflow:MsoCompletionResponse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1">
255                            <sdncadapterworkflow:out>BPEL ${execution.getVariable("CMSO_mso-bpel-name")} FAILED</sdncadapterworkflow:out>
256                         </sdncadapterworkflow:MsoCompletionResponse>
257                         """.trim()
258
259                         // Format Response
260                         def xmlMsoCompletionResponse = utils.formatXml(msoCompletionResponse)
261                         String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim()
262                         logger.debug("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString)
263                         execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString)
264                         logger.debug("@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompletionHandlerResponse"))
265
266                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, message)
267
268                 } catch (BpmnError e) {
269                         logger.debug("Rethrowing MSOWorkflowException")
270                         throw e;
271                 } catch (Exception e) {
272                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
273                                         'Caught exception in ' + method, "BPMN",
274                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
275                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
276                 }
277
278         }
279
280         public void postProcessResponse (DelegateExecution execution) {
281
282                                 def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')'
283                                 logger.trace('Entered ' + method)
284                 //              logger.trace("Started CompleteMsoProcess PostProcessRequest Method ");
285                                 try {
286
287                                         String msoCompletionResponse = """
288                         <sdncadapterworkflow:MsoCompletionResponse xmlns:sdncadapterworkflow="http://ecomp.com/mso/workflow/schema/v1">
289                            <sdncadapterworkflow:out>BPEL ${execution.getVariable("CMSO_mso-bpel-name")} completed</sdncadapterworkflow:out>
290                         </sdncadapterworkflow:MsoCompletionResponse>
291                         """.trim()
292
293                                         // Format Response
294                                         def xmlMsoCompletionResponse = utils.formatXML(msoCompletionResponse)
295                                         String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim()
296                                         // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead
297                                         execution.setVariable("WorkflowResponse", buildMsoCompletionResponseAsString)
298                                         logger.debug("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString)
299                                         execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString)
300                                         execution.setVariable("CMSO_ResponseCode", "200")
301
302                                         setSuccessIndicator(execution, true)
303
304                                         logger.debug("@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompleteMsoProcessResponse"))
305
306                                         logger.trace('Exited ' + method)
307                                 } catch (BpmnError e) {
308                                         throw e;
309                                 } catch (Exception e) {
310                                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
311                                                         'Caught exception in ' + method, "BPMN",
312                                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
313                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
314                                 }
315         }
316
317
318 }