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