Remove unnecessary use of Calendar.getInstance()
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / openecomp / mso / bpmn / common / scripts / CompleteMsoProcess.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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.openecomp.mso.bpmn.common.scripts
22
23 import org.apache.commons.lang3.*
24 import org.camunda.bpm.engine.delegate.BpmnError
25 import org.camunda.bpm.engine.runtime.Execution
26
27
28 public class CompleteMsoProcess extends AbstractServiceTaskProcessor {
29
30         String Prefix="CMSO_"
31         ExceptionUtil exceptionUtil = new ExceptionUtil()
32
33         // Complete MSO Request processing
34         public initializeProcessVariables(Execution execution){
35
36                 def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')'
37                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
38                 logDebug('Entered ' + method, isDebugLogEnabled)
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                         logError('Caught exception in ' + method, e)
74                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
75                 }
76
77         }
78
79         public void preProcessRequest (Execution execution) {
80
81                 initializeProcessVariables(execution)
82                 def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')'
83                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
84 //              utils.log("DEBUG", "*** Started CompleteMsoProcess preProcessRequest Method ***", isDebugLogEnabled);
85                 logDebug('Entered ' + method, isDebugLogEnabled)
86                 try {
87                         def xml = execution.getVariable("CompleteMsoProcessRequest")
88
89                         utils.logAudit("CompleteMsoProcess Request: " + xml)
90                         utils.log("DEBUG", "Incoming Request is: "+ xml, isDebugLogEnabled)
91
92                         //mso-bpel-name from the incoming request
93                         def msoBpelName = utils.getNodeText1(xml,"mso-bpel-name")
94                         execution.setVariable("CMSO_mso-bpel-name",msoBpelName)
95
96                         //Check the incoming request type
97                         //Incoming request can be ACTIVE_REQUESTS (request-information node) or  INFRA_ACTIVE_REQUESTS (request-info node)
98                         if (utils.nodeExists(xml, "request-information")) {
99                                 execution.setVariable("CMSO_request_id-Ok", true) // Incoming request is for ACTIVE_REQUESTS
100                         }
101
102                         //Check notification-url for the incoming request type
103                         //ACTIVE_REQUESTS may have notificationurl node
104                         //INFRA_ACTIVE_REQUESTS notificationurl node does not exist
105                         def notificationurl = ""
106                         if (utils.nodeExists(xml, "notification-url")) {
107                                 notificationurl = utils.getNodeText(xml,"notification-url")
108                                 if(notificationurl != null && !notificationurl.isEmpty()) {
109                                         execution.setVariable("CMSO_notification-url-Ok", true)
110                                         execution.setVariable("CMSO_notification-url",notificationurl)
111                                 }
112                         }
113
114                         //Check request_id for the incoming request type
115                         //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)
116                         //For ACTIVE_REQUESTS payload request-id is NOT optional
117                         def request_id = ""
118                         if (utils.nodeExists(xml, "request-id")) {
119                                 execution.setVariable("CMSO_request_id",utils.getNodeText(xml,"request-id"))
120                         }
121
122
123                         // INFRA_ACTIVE_REQUESTS         have "action" element ... mandatory
124                         // ACTIVE_REQUEST have "request-action" ... mandatory
125                         if (utils.nodeExists(xml, "request-action")) {
126                                 execution.setVariable("CMSO_request_action",utils.getNodeText(xml,"request-action"))
127                         } else if (utils.nodeExists(xml, "action")) {
128                                 execution.setVariable("CMSO_request_action",utils.getNodeText(xml,"action"))
129                         }
130
131                         //Check source for the incoming request type
132                         //For INFRA_ACTIVE_REQUESTS payload source IS optional
133                         //For ACTIVE_REQUESTS payload source is NOT optional
134                         def source = ""
135                         if (utils.nodeExists(xml, "source")) {
136                                 execution.setVariable("CMSO_source",utils.getNodeText(xml,"source"))
137                         }
138
139                         utils.log("DEBUG", "CMSO_notification-url-Ok --> " + execution.getVariable("CMSO_notification-url-Ok"), isDebugLogEnabled)
140                         utils.log("DEBUG", "CMSO_request_id-Ok --> " + execution.getVariable("CMSO_request_id-Ok"), isDebugLogEnabled)
141
142                         // set the DHV/Service Instantiation values if specified in the request
143                         execution.setVariable("CMSO_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText1(xml, "is-srv-inst-req"))))
144                         utils.log("DEBUG", "CMSO_is_srv_inst_req --> " + execution.getVariable("CMSO_is_srv_inst_req"), isDebugLogEnabled)
145                         execution.setVariable("CMSO_is_json_content", String.valueOf("JSON".equals(utils.getNodeText1(xml, "resp-content-type"))))
146                         utils.log("DEBUG", "CMSO_is_json_content --> " + execution.getVariable("CMSO_is_json_content"), isDebugLogEnabled)
147                         execution.setVariable("CMSO_service_inst_id", utils.getNodeText1(xml, "service-instance-id"))
148                         utils.log("DEBUG", "CMSO_service_inst_id --> " + execution.getVariable("CMSO_service_inst_id"), isDebugLogEnabled)
149                         execution.setVariable("CMSO_start_time", utils.getNodeText1(xml, "start-time"))
150                         utils.log("DEBUG", "CMSO_start_time --> " + execution.getVariable("CMSO_start_time"), isDebugLogEnabled)
151                         // this variable is used by the camunda flow to set the Content-Type for the async response
152                         if (execution.getVariable("CMSO_is_srv_inst_req").equals("true") &&
153                                 execution.getVariable("CMSO_is_json_content").equals("true")) {
154                                 execution.setVariable("CMSO_content_type", "application/json")
155                         } else {
156                                 execution.setVariable("CMSO_content_type", "text/xml")
157                         }
158                         
159                         logDebug('Exited ' + method, isDebugLogEnabled)
160                 } catch (BpmnError e) {
161                         throw e;
162                 } catch (Exception e) {
163                         utils.log("DEBUG", "Exception Occured During PreProcessRequest: " + e, isDebugLogEnabled);
164                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
165                 }
166
167 //              utils.log("DEBUG", "*** Completed CompleteMsoProcess preProcessRequest Method ***", isDebugLogEnabled);
168         }
169
170         public void postProcessResponse (Execution execution) {
171
172                 def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')'
173                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
174                 logDebug('Entered ' + method, isDebugLogEnabled)
175 //              utils.log("DEBUG", "*** Started CompleteMsoProcess PostProcessRequest Method ***", isDebugLogEnabled);
176                 try {
177
178                         def msoCompletionResponse = """
179                         <sdncadapterworkflow:MsoCompletionResponse xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1">
180                            <sdncadapterworkflow:out>BPEL ${execution.getVariable("CMSO_mso-bpel-name")} completed</sdncadapterworkflow:out>
181                         </sdncadapterworkflow:MsoCompletionResponse>
182                         """.trim()
183
184                         // Format Response
185                         def xmlMsoCompletionResponse = utils.formatXML(msoCompletionResponse)
186                         String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim()
187                         // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead
188                         execution.setVariable("WorkflowResponse", buildMsoCompletionResponseAsString)
189                         utils.logAudit("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString)
190                         execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString)
191                         execution.setVariable("CMSO_ResponseCode", "200")
192
193                         setSuccessIndicator(execution, true)
194
195                         utils.log("DEBUG", "@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompleteMsoProcessResponse"), isDebugLogEnabled)
196
197                         logDebug('Exited ' + method, isDebugLogEnabled)
198                 } catch (BpmnError e) {
199                         throw e;
200                 } catch (Exception e) {
201                         logError('Caught exception in ' + method, e)
202                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
203                 }
204 //              utils.log("DEBUG", "*** Completed CompleteMsoProcess PostProcessRequest Method ***", isDebugLogEnabled);
205
206         }
207
208         public void updateDBStatusToSuccessPayload (Execution execution){
209                 def method = getClass().getSimpleName() + '.updateDBStatusToSuccessPayload(' +'execution=' + execution.getId() +')'
210                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
211                 logDebug('Entered ' + method, isDebugLogEnabled)
212                 
213                 try {
214                         // Catalog DB headers Authorization
215                         String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth")
216                         utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled)
217                         
218                         def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey"))
219                         execution.setVariable("BasicAuthHeaderValueDB",encodedString)
220                 } catch (IOException ex) {
221                         String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage()
222                         utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled)
223                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
224                 }
225                 
226                 try {
227
228                         String payload = """
229                         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.openecomp.mso/requestsdb">
230                         <soapenv:Header/>
231                         <soapenv:Body>
232                            <req:updateStatus>
233                                   <requestId>${execution.getVariable("CMSO_request_id")}</requestId>
234                                   <lastModifiedBy>BPEL</lastModifiedBy>
235                                   <status>COMPLETED</status>
236                            </req:updateStatus>
237                         </soapenv:Body>
238                  </soapenv:Envelope>
239                 """
240                         execution.setVariable("CMSO_updateDBStatusToSuccessPayload", payload)
241                         utils.logAudit("updateDBStatusToSuccessPayload: " + payload)
242                         logDebug('Exited ' + method, isDebugLogEnabled)
243                         //println("CMSO_updateDBStatusToSuccessPayload --> " + execution.getVariable("CMSO_updateDBStatusToSuccessPayload"))
244
245                 } catch (BpmnError e) {
246                         throw e;
247                 } catch (Exception e) {
248                         logError('Caught exception in ' + method, e)
249                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
250                 }
251         }
252
253         public void setUpdateDBstatustoSuccessPayload (Execution execution){
254
255                 def method = getClass().getSimpleName() + '.setUpdateDBstatustoSuccessPayload(' +'execution=' + execution.getId() +')'
256                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
257                 logDebug('Entered ' + method, isDebugLogEnabled)
258                 
259                 try {
260                         String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth")
261                         utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled)
262                         
263                         def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey"))
264                         execution.setVariable("BasicAuthHeaderValueDB",encodedString)
265                 } catch (IOException ex) {
266                         String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage()
267                         utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled)
268                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
269                 } 
270                 
271                 try {
272
273                         def xml = execution.getVariable("CompleteMsoProcessRequest")
274
275                         //Get statusMessage if exists
276                         def statusMessage
277                         if(utils.nodeExists(xml, "status-message")){
278                                 statusMessage = utils.getNodeText1(xml, "status-message")
279                         }else{
280                                 statusMessage = "Resource Completed Successfully"
281                         }
282
283                         //Get instance Id if exist
284                         String idXml = ""
285                         if(utils.nodeExists(xml, "vnfId")){
286                                 idXml = utils.getNodeXml(xml, "vnfId")
287                         }else if(utils.nodeExists(xml, "networkId")){
288                                 idXml = utils.getNodeXml(xml, "networkId")
289                         }else if(utils.nodeExists(xml, "serviceInstanceId")){
290                                 idXml = utils.getNodeXml(xml, "serviceInstanceId")
291                         }else if(utils.nodeExists(xml, "vfModuleId")){
292                                 idXml = utils.getNodeXml(xml, "vfModuleId")
293                         }else if(utils.nodeExists(xml, "volumeGroupId")){
294                                 idXml = utils.getNodeXml(xml, "volumeGroupId")
295                         }else{
296                                 idXml = ""
297                         }
298                         idXml = utils.removeXmlPreamble(idXml)
299                         utils.log("DEBUG", "Incoming Instance Id Xml: " + idXml, isDebugLogEnabled)
300
301                         String payload = """
302                                                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.openecomp.mso/requestsdb">
303                                                    <soapenv:Header/>
304                                                    <soapenv:Body>
305                                                       <req:updateInfraRequest>
306                                                          <requestId>${execution.getVariable("CMSO_request_id")}</requestId>
307                                                          <lastModifiedBy>${execution.getVariable("CMSO_mso-bpel-name")}</lastModifiedBy>
308                                                          <statusMessage>${statusMessage}</statusMessage>
309                                                          <requestStatus>COMPLETE</requestStatus>
310                                                                  <progress>100</progress>
311                                                                  ${idXml}
312                                                       </req:updateInfraRequest>
313                                                    </soapenv:Body>
314                                                 </soapenv:Envelope>"""
315
316                         execution.setVariable("CMSO_setUpdateDBstatustoSuccessPayload", payload)
317                         utils.log("DEBUG", "Outgoing Update Mso Request Payload is: " + payload, isDebugLogEnabled)
318                         utils.logAudit("setUpdateDBstatustoSuccessPayload: " + payload)
319
320                 } catch (BpmnError e) {
321                         throw e;
322                 } catch (Exception e) {
323                         logError('Caught exception in ' + method, e)
324                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
325                 }
326                 logDebug('Exited ' + method, isDebugLogEnabled)
327         }
328
329         public void buildDataError (Execution execution, String message) {
330
331                 def method = getClass().getSimpleName() + '.buildDataError(' +'execution=' + execution.getId() +')'
332                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
333                 logDebug('Entered ' + method, isDebugLogEnabled)
334                 try {
335
336                         def msoCompletionResponse = """
337                         <sdncadapterworkflow:MsoCompletionResponse xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1">
338                            <sdncadapterworkflow:out>BPEL ${execution.getVariable("CMSO_mso-bpel-name")} FAILED</sdncadapterworkflow:out>
339                         </sdncadapterworkflow:MsoCompletionResponse>
340                         """.trim()
341
342                         // Format Response
343                         def xmlMsoCompletionResponse = utils.formatXml(msoCompletionResponse)
344                         String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim()
345                         utils.logAudit("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString)
346                         execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString)
347                         utils.log("DEBUG", "@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompletionHandlerResponse"), isDebugLogEnabled)
348
349                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, message)
350
351                 } catch (BpmnError e) {
352                         utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugLogEnabled)
353                         throw e;
354                 } catch (Exception e) {
355                         logError('Caught exception in ' + method, e)
356                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
357                 }
358
359         }
360
361 }