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