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