Remove unnecessary use of Calendar.getInstance()
[so.git] / bpmn / MSOGammaBPMN / src / main / groovy / com / att / bpm / scripts / UpdateVfModuleInfra.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 com.att.bpm.scripts
22
23 import groovy.json.JsonSlurper
24 import groovy.util.Node
25 import groovy.util.XmlParser;
26 import groovy.xml.QName
27
28 import java.io.Serializable;
29
30 import org.camunda.bpm.engine.delegate.BpmnError
31 import org.camunda.bpm.engine.runtime.Execution
32
33 import org.openecomp.mso.rest.APIResponse
34 import org.openecomp.mso.rest.RESTClient
35 import org.openecomp.mso.rest.RESTConfig
36 import org.openecomp.mso.bpmn.core.RollbackData
37 import org.openecomp.mso.bpmn.core.WorkflowException
38
39
40 public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor {
41                 
42         /**
43          * Initialize the flow's variables.
44          * 
45          * @param execution The flow's execution instance.
46          */
47         public void initProcessVariables(Execution execution) {
48                 execution.setVariable('prefix', 'UPDVfModI_')
49                 execution.setVariable('UPDVfModI_Request', null)
50                 execution.setVariable('UPDVfModI_requestInfo', null)
51                 execution.setVariable('UPDVfModI_requestId', null)
52                 execution.setVariable('UPDVfModI_source', null)
53                 execution.setVariable('UPDVfModI_vnfInputs', null)
54                 execution.setVariable('UPDVfModI_vnfId', null)
55                 execution.setVariable('UPDVfModI_vfModuleId', null)
56                 execution.setVariable('UPDVfModI_tenantId', null)
57                 execution.setVariable('UPDVfModI_volumeGroupId', null)
58                 execution.setVariable('UPDVfModI_vnfParams', null)
59                 execution.setVariable('UPDVfModI_updateInfraRequest', null)
60                 execution.setVariable('UpdateVfModuleSuccessIndicator', false)
61         }       
62         
63         /**
64          * Check for missing elements in the received request.
65          * 
66          * @param execution The flow's execution instance.
67          */
68         public void preProcessRequest(Execution execution) {
69                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
70                         'execution=' + execution.getId() +
71                         ')'
72                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
73                 logDebug('Entered ' + method, isDebugLogEnabled)
74                 
75                 initProcessVariables(execution)
76                 
77                 def prefix = "UPDVfModI_"
78                 
79                 execution.setVariable("isVidRequest", "false")
80                 
81                 def incomingRequest = execution.getVariable('bpmnRequest')
82                 
83                 utils.log("DEBUG", "Incoming Infra Request: " + incomingRequest, isDebugLogEnabled)
84                 
85                 // check if request is xml or json
86                 try {
87                         def jsonSlurper = new JsonSlurper()
88                         Map reqMap = jsonSlurper.parseText(incomingRequest)
89                         utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled)
90                         
91                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
92                         def vnfId = execution.getVariable('vnfId')
93                         
94                         def vidUtils = new VidUtils(this)
95                         
96                         String requestInXmlFormat = vidUtils.createXmlVfModuleRequest(execution, reqMap, 'UPDATE_VF_MODULE', serviceInstanceId)
97                         
98                         utils.log("DEBUG", " Request in XML format: " + requestInXmlFormat, isDebugLogEnabled)
99                         
100                         execution.setVariable(prefix + 'Request', requestInXmlFormat)
101                         execution.setVariable(prefix+'vnfId', vnfId)
102                         execution.setVariable("isVidRequest", "true")                   
103                         
104                 }
105                 catch(groovy.json.JsonException je) {
106                         utils.log("DEBUG", " Request is not in JSON format.", isDebugLogEnabled)
107                         workflowException(execution, "Invalid request format", 400)
108                         
109                 }
110                 catch(Exception e) {
111                         String restFaultMessage = e.getMessage()                        
112                         utils.log("ERROR", " Exception Encountered - " + "\n" + restFaultMessage, isDebugLogEnabled)
113                         workflowException(execution, restFaultMessage, 400)
114                 }
115                                 
116
117                 try {
118                         
119                         String request = validateInfraRequest(execution)
120                         
121                         def requestInfo = getRequiredNodeXml(execution, request, 'request-info')
122                         execution.setVariable('UPDVfModI_requestInfo', requestInfo)
123                         execution.setVariable('UPDVfModI_requestId', getRequiredNodeText(execution, requestInfo, 'request-id'))
124                         execution.setVariable('UPDVfModI_source', getNodeTextForce(requestInfo, 'source'))
125                         
126                         def vnfInputs = getRequiredNodeXml(execution, request, 'vnf-inputs')
127                         execution.setVariable('UPDVfModI_vnfInputs', vnfInputs)
128                         execution.setVariable('UPDVfModI_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id'))
129                         execution.setVariable('UPDVfModI_vfModuleId', getRequiredNodeText(execution, vnfInputs, 'vf-module-id'))
130                         execution.setVariable('UPDVfModI_tenantId', getRequiredNodeText(execution, vnfInputs, 'tenant-id'))
131                         execution.setVariable('UPDVfModI_volumeGroupId', getNodeTextForce(vnfInputs, 'volume-group-id'))
132
133                         def vnfParams = utils.getNodeXml(request, 'vnf-params')
134                         execution.setVariable('UPDVfModI_vnfParams', vnfParams)
135
136                         logDebug('Exited ' + method, isDebugLogEnabled)
137                 } catch (BpmnError e) {
138                         throw e;
139                 } catch (Exception e) {
140                         logError('Caught exception in ' + method, e)
141                         createWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
142                 }
143         }
144         
145         /**
146          * Prepare and send the sychronous response for this flow.
147          * 
148          * @param execution The flow's execution instance.
149          */
150         public void sendSynchResponse(Execution execution) {
151                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
152                         'execution=' + execution.getId() +
153                         ')'
154                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
155                 logDebug('Entered ' + method, isDebugLogEnabled)
156
157                 
158                 try {
159                         def requestInfo = execution.getVariable('UPDVfModI_requestInfo')
160                         def requestId = execution.getVariable('UPDVfModI_requestId')
161                         def source = execution.getVariable('UPDVfModI_source')
162                         def progress = getNodeTextForce(requestInfo, 'progress')
163                         if (progress.isEmpty()) {
164                                 progress = '0'
165                         }
166                         def startTime = getNodeTextForce(requestInfo, 'start-time')
167                         if (startTime.isEmpty()) {
168                                 startTime = System.currentTimeMillis()
169                         }                       
170                                 
171                         // RESTResponse (for API Handler (APIH) Reply Task)
172                         def vfModuleId = execution.getVariable("vfModuleId")
173                         String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim()
174                         
175                         sendWorkflowResponse(execution, 200, synchResponse)
176
177                         logDebug('Exited ' + method, isDebugLogEnabled)
178                 } catch (BpmnError e) {
179                         throw e;
180                 } catch (Exception e) {
181                         logError('Caught exception in ' + method, e)
182                         createWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
183                 }
184         }
185         
186         /**
187          * Prepare the Request for invoking the DoUpdateVfModule subflow.
188          * 
189          * NOTE: Currently, the method just logs passing through as the
190          * incoming Request to this main flow is used as the Request to
191          * the DoUpdateVfModule subflow. No preparation processing is
192          * necessary.
193          * 
194          * @param execution The flow's execution instance.
195          */
196         public void prepDoUpdateVfModule(Execution execution) {
197                 def method = getClass().getSimpleName() + '.prepDoUpdateVfModule(' +
198                         'execution=' + execution.getId() +
199                         ')'
200                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
201                 logDebug('Entered ' + method, isDebugLogEnabled)
202
203                 try {
204                         
205                         logDebug('Exited ' + method, isDebugLogEnabled)
206                 } catch (BpmnError e) {
207                         throw e;
208                 } catch (Exception e) {
209                         logError('Caught exception in ' + method, e)
210                         createWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage())
211                 }
212         }
213         
214         /**
215          * Prepare the Request for updating the DB for this Infra Request.
216          * 
217          * @param execution The flow's execution instance.
218          */
219         public void prepUpdateInfraRequest(Execution execution) {
220                 def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' +
221                         'execution=' + execution.getId() +
222                         ')'
223                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
224                 logDebug('Entered ' + method, isDebugLogEnabled)
225
226                 try {
227                         def requestId = execution.getVariable('UPDVfModI_requestId')
228                         def vnfId = execution.getVariable('UPDVfModI_vnfId')
229                         def vfModuleId = execution.getVariable('UPDVfModI_vfModuleId')
230                         def tenantId = execution.getVariable('UPDVfModI_tenantId')
231                         def volumeGroupId = execution.getVariable('UPDVfModI_volumeGroupId')
232                         
233                         String updateInfraRequest = """
234                                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
235                                                 xmlns:req="http://com.att.mso/requestsdb">
236                                         <soapenv:Header/>
237                                         <soapenv:Body>
238                                                 <req:updateInfraRequest>
239                                                         <requestId>${requestId}</requestId>
240                                                         <lastModifiedBy>BPEL</lastModifiedBy>
241                                                         <requestStatus>COMPLETE</requestStatus>
242                                                         <progress>100</progress>
243                                                         <vnfOutputs>
244                                                                 <vnf-id>${vnfId}</vnf-id>
245                                                                 <vf-module-id>${vfModuleId}</vf-module-id>
246                                                                 <tenant-id>${tenantId}</tenant-id>
247                                                                 <volume-group-id>${volumeGroupId}</volume-group-id>
248                                                         </vnfOutputs>
249                                                 </req:updateInfraRequest>
250                                         </soapenv:Body>
251                                 </soapenv:Envelope>
252                         """
253
254                         updateInfraRequest = utils.formatXml(updateInfraRequest)
255                         execution.setVariable('UPDVfModI_updateInfraRequest', updateInfraRequest)
256                         logDebug('Request for Update Infra Request:\n' + updateInfraRequest, isDebugLogEnabled)
257
258                         logDebug('Exited ' + method, isDebugLogEnabled)
259                 } catch (BpmnError e) {
260                         throw e;
261                 } catch (Exception e) {
262                         logError('Caught exception in ' + method, e)
263                         createWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage())
264                 }
265         }
266         
267         /**
268          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
269          * 
270          * @param execution the execution
271          * @param resultVar the execution variable in which the result will be stored
272          */
273         public void completionHandlerPrep(Execution execution, String resultVar) {
274                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
275                         'execution=' + execution.getId() +
276                         ', resultVar=' + resultVar +
277                         ')'
278                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
279                 logDebug('Entered ' + method, isDebugLogEnabled)
280
281                 try {
282                         def requestInfo = getVariable(execution, 'UPDVfModI_requestInfo')
283                         
284                         String content = """
285                                 <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://ecomp.att.com/mso/workflow/schema/v1"
286                                                 xmlns:reqtype="http://ecomp.att.com/mso/request/types/v1">
287                                         ${requestInfo}
288                                         <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name>
289                                 </sdncadapterworkflow:MsoCompletionRequest>
290                         """
291
292                         content = utils.formatXml(content)
293                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
294                         execution.setVariable(resultVar, content)
295
296                         logDebug('Exited ' + method, isDebugLogEnabled)
297                 } catch (BpmnError e) {
298                         throw e;
299                 } catch (Exception e) {
300                         logError('Caught exception in ' + method, e)
301                         createWorkflowException(execution, 2000, 'Internal Error')
302                 }
303         }
304
305         /**
306          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
307          * 
308          * @param execution the execution
309          * @param resultVar the execution variable in which the result will be stored
310          */
311         public void falloutHandlerPrep(Execution execution, String resultVar) {
312                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
313                         'execution=' + execution.getId() +
314                         ', resultVar=' + resultVar +
315                         ')'
316                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
317                 logDebug('Entered ' + method, isDebugLogEnabled)
318                 
319                 try {
320                         def prefix = execution.getVariable('prefix')
321                         def request = getVariable(execution, prefix+'Request')
322                         def requestInformation = utils.getNodeXml(request, 'request-info', false)
323                         
324                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
325                         def errorResponseCode = workflowException.getErrorCode()
326                         def errorResponseMsg = workflowException.getErrorMessage()
327                         def encErrorResponseMsg = ""
328                         if (errorResponseMsg != null) {
329                                 encErrorResponseMsg = errorResponseMsg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
330                         }
331
332                         String content = """
333                                 <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://ecomp.att.com/mso/workflow/schema/v1"
334                                                 xmlns:reqtype="http://ecomp.att.com/mso/request/types/v1"
335                                                 xmlns:msoservtypes="http://ecomp.att.com/mso/request/types/v1"
336                                                 xmlns:structuredtypes="http://ecomp.att.com/mso/structured/types/v1">
337                                         ${requestInformation}
338                                         <sdncadapterworkflow:WorkflowException>
339                                                 <sdncadapterworkflow:ErrorMessage>${encErrorResponseMsg}</sdncadapterworkflow:ErrorMessage>
340                                                 <sdncadapterworkflow:ErrorCode>${errorResponseCode}</sdncadapterworkflow:ErrorCode>
341                                         </sdncadapterworkflow:WorkflowException>        
342                                 </sdncadapterworkflow:FalloutHandlerRequest>
343                         """
344                         content = utils.formatXml(content)
345                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
346                         execution.setVariable(resultVar, content)
347
348                         logDebug('Exited ' + method, isDebugLogEnabled)
349                 } catch (BpmnError e) {
350                         throw e;
351                 } catch (Exception e) {
352                         logError('Caught exception in ' + method, e)
353                         createWorkflowException(execution, 2000, 'Internal Error')
354                 }
355         }
356         
357         /**
358          * Validates the request, request id and service instance id.  If a problem is found,
359          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
360          * method also sets up the log context for the workflow.
361          * @param execution the execution
362          * @return the validated request
363          */
364         public String validateInfraRequest(Execution execution) {
365                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
366                         'execution=' + execution.getId() +
367                         ')'
368                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
369                 logDebug('Entered ' + method, isDebugLogEnabled)
370
371                 String processKey = getProcessKey(execution);
372                 def prefix = execution.getVariable("prefix")
373
374                 if (prefix == null) {
375                         createWorkflowException(execution, 1002, processKey + " prefix is null")
376                 }
377
378                 try {
379                         def request = execution.getVariable(prefix + 'Request')
380
381                         if (request == null) {
382                                 request = execution.getVariable(processKey + 'Request')
383         
384                                 if (request == null) {
385                                         request = execution.getVariable('bpmnRequest')
386                                 }
387         
388                                 setVariable(execution, processKey + 'Request', null);
389                                 setVariable(execution, 'bpmnRequest', null);
390                                 setVariable(execution, prefix + 'Request', request);
391                         }
392
393                         if (request == null) {
394                                 createWorkflowException(execution, 1002, processKey + " request is null")
395                         }
396                         
397                         /*
398
399                         def requestId = execution.getVariable("att-mso-request-id")
400                         
401                         if (requestId == null) {
402                                 createWorkflowException(execution, 1002, processKey + " request has no att-mso-request-id")
403                         }
404                         
405                         setVariable(execution, prefix + 'requestId', requestId)
406
407                         def serviceInstanceId = execution.getVariable("att-mso-service-instance-id")
408
409                         if (serviceInstanceId == null) {
410                                 createWorkflowException(execution, 1002, processKey + " request message has no att-mso-service-instance-id")
411                         }
412
413                         utils.logContext(requestId, serviceInstanceId)
414                         */
415                         logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled)
416                         logDebug('Exited ' + method, isDebugLogEnabled)
417                         return request
418                 } catch (BpmnError e) {
419                         throw e;
420                 } catch (Exception e) {
421                         logError('Caught exception in ' + method, e)
422                         createWorkflowException(execution, 1002, "Invalid Message")
423                 }
424         }
425         
426 }