Remove unnecessary use of Calendar.getInstance()
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / DeleteVfModuleInfra.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.infrastructure.scripts
22
23 import groovy.util.Node
24 import groovy.util.XmlParser;
25 import groovy.xml.QName
26
27 import java.io.Serializable;
28
29 import org.camunda.bpm.engine.delegate.BpmnError
30 import org.camunda.bpm.engine.runtime.Execution
31
32 import groovy.json.JsonSlurper
33
34 import org.openecomp.mso.rest.APIResponse
35 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor;
36 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil;
37 import org.openecomp.mso.bpmn.common.scripts.VidUtils;
38 import org.openecomp.mso.bpmn.core.RollbackData
39 import org.openecomp.mso.bpmn.core.WorkflowException
40 import org.openecomp.mso.bpmn.core.json.JsonUtils;
41
42
43 public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor {
44         
45         ExceptionUtil exceptionUtil = new ExceptionUtil()
46         JsonUtils jsonUtil = new JsonUtils()
47         /**
48          * Initialize the flow's variables.
49          *
50          * @param execution The flow's execution instance.
51          */
52         public void initProcessVariables(Execution execution) {
53                 execution.setVariable('prefix', 'DELVfModI_')
54                 execution.setVariable('DELVfModI_requestInfo', null)
55                 execution.setVariable('DELVfModI_requestId', null)
56                 execution.setVariable('DELVfModI_source', null)
57                 execution.setVariable('DELVfModI_vnfInputs', null)
58                 execution.setVariable('DELVfModI_vnfId', null)
59                 execution.setVariable('DELVfModI_vfModuleId', null)
60                 execution.setVariable('DELVfModI_tenantId', null)
61                 execution.setVariable('DELVfModI_volumeGroupId', null)
62                 execution.setVariable('DELVfModI_vnfParams', null)
63                 execution.setVariable('DELVfModI_updateInfraRequest', null)
64                 execution.setVariable('DeleteVfModuleRequest', null)
65                 execution.setVariable('DeleteVfModuleSuccessIndicator', false)
66         }
67
68         /**
69          * Process the incoming DELETE_VF_MODULE vnf-request.
70          *
71          * @param execution The flow's execution instance.
72          */
73         public void preProcessRequest(Execution execution) {
74                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
75                         'execution=' + execution.getId() +
76                         ')'
77                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
78                 logDebug('Entered ' + method, isDebugLogEnabled)
79                 execution.setVariable("isVidRequest", "false")
80                 initProcessVariables(execution)
81                 
82                 def prefix = execution.getVariable('prefix')
83                 
84                 def incomingRequest = execution.getVariable('bpmnRequest')
85                 
86                 utils.log("DEBUG", "Incoming Infra Request: " + incomingRequest, isDebugLogEnabled)
87                 utils.logAudit("DeleteVfModule Infra incoming Request: " + incomingRequest)
88                 
89                 // check if request is xml or json
90                 try {
91                         def jsonSlurper = new JsonSlurper()
92                         Map reqMap = jsonSlurper.parseText(incomingRequest)
93                         utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled)
94                         
95                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
96                         utils.log("DEBUG", "serviceInstanceId is: " + serviceInstanceId, isDebugLogEnabled)
97                         def vnfId = execution.getVariable('vnfId')
98                         utils.log("DEBUG", "vnfId is: " + vnfId, isDebugLogEnabled)
99                         def cloudConfiguration = jsonUtil.getJsonValue(incomingRequest, "requestDetails.cloudConfiguration")
100                         execution.setVariable("cloudConfiguration", cloudConfiguration)
101                         utils.log("DEBUG", "CloudConfiguration is: " + cloudConfiguration, isDebugLogEnabled)
102                         def vfModuleModelInfo = jsonUtil.getJsonValue(incomingRequest, "requestDetails.modelInfo")
103                         
104                         execution.setVariable("vfModuleModelInfo", vfModuleModelInfo)
105                         utils.log("DEBUG", "VfModuleModelInfo is: " + vfModuleModelInfo, isDebugLogEnabled)
106                         
107                         def vidUtils = new VidUtils(this)
108                         
109                         String requestInXmlFormat = vidUtils.createXmlVfModuleRequest(execution, reqMap, 'DELETE_VF_MODULE', serviceInstanceId)
110                         
111                         utils.log("DEBUG", " Request in XML format: " + requestInXmlFormat, isDebugLogEnabled)
112                         
113                         try {
114                                 // Catalog DB headers Authorization
115                                 String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth")
116                                 utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled)
117                                 
118                                 def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey"))
119                                 execution.setVariable("BasicAuthHeaderValueDB",encodedString)
120                         } catch (IOException ex) {
121                                 String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage()
122                                 utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled)
123                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
124                         }
125                         
126                         execution.setVariable(prefix + 'Request', requestInXmlFormat)
127                         execution.setVariable(prefix+'vnfId', vnfId)
128                         execution.setVariable("isVidRequest", "true")
129                         
130                 }
131                 catch(groovy.json.JsonException je) {
132                         utils.log("DEBUG", " Request is not in JSON format.", isDebugLogEnabled)
133                         workflowException(execution, "Invalid request format", 400)
134                         
135                 }
136                 catch(Exception e) {
137                         String restFaultMessage = e.getMessage()
138                         utils.log("ERROR", " Exception Encountered - " + "\n" + restFaultMessage, isDebugLogEnabled)
139                         workflowException(execution, restFaultMessage, 400)
140                 }
141                 
142         
143                 try {
144                         
145                         String request = validateRequest(execution)
146                         execution.setVariable('DeleteVfModuleRequest', request)
147                         utils.logAudit("DeleteVfModuleInfra Request: " + request)
148                         
149                         def requestInfo = getRequiredNodeXml(execution, request, 'request-info')
150                         execution.setVariable('DELVfModI_requestInfo', requestInfo)
151                         execution.setVariable('DELVfModI_requestId', getRequiredNodeText(execution, requestInfo, 'request-id'))
152                         execution.setVariable('DELVfModI_source', getNodeTextForce(requestInfo, 'source'))
153                         
154                         def vnfInputs = getRequiredNodeXml(execution, request, 'vnf-inputs')
155                         execution.setVariable('DELVfModI_vnfInputs', vnfInputs)
156                         execution.setVariable('DELVfModI_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id'))
157                         execution.setVariable('DELVfModI_vfModuleId', getRequiredNodeText(execution, vnfInputs, 'vf-module-id'))
158                         execution.setVariable('DELVfModI_vfModuleName', getNodeTextForce(vnfInputs, 'vf-module-name'))
159                         execution.setVariable('DELVfModI_tenantId', getRequiredNodeText(execution, vnfInputs, 'tenant-id'))
160                         execution.setVariable('DELVfModI_volumeGroupId', getNodeTextForce(vnfInputs, 'volume-group-id'))
161                         
162                         def vnfParams = utils.getNodeXml(request, 'vnf-params')
163                         execution.setVariable('DELVfModI_vnfParams', vnfParams)
164         
165                         logDebug('Exited ' + method, isDebugLogEnabled)
166                 } catch (BpmnError e) {
167                         throw e;
168                 } catch (Exception e) {
169                         logError('Caught exception in ' + method, e)
170                         createWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
171                 }
172         }
173
174         /**
175          * Sends the 'IN_PROGRESS' synchronous response.
176          *
177          * @param execution The flow's execution instance.
178          */
179         public void sendSynchResponse(Execution execution) {
180                 def method = getClass().getSimpleName() + '.sendResponse(' +
181                         'execution=' + execution.getId() +
182                         ')'
183                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
184                 logDebug('Entered ' + method, isDebugLogEnabled)
185         
186                 try {
187                         def requestInfo = execution.getVariable('DELVfModI_requestInfo')
188                         def requestId = execution.getVariable('DELVfModI_requestId')
189                         def source = execution.getVariable('DELVfModI_source')
190                         def progress = getNodeTextForce(requestInfo, 'progress')
191                         if (progress.isEmpty()) {
192                                 progress = '0'
193                         }
194                         def startTime = getNodeTextForce(requestInfo, 'start-time')
195                         if (startTime.isEmpty()) {
196                                 startTime = System.currentTimeMillis()
197                         }
198                                 
199                         // RESTResponse (for API Handler (APIH) Reply Task)
200                         def vfModuleId = execution.getVariable('DELVfModI_vfModuleId')
201                         String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim()
202                                 
203                         utils.logAudit("DeleteVfModuleInfra Synch Response: " + synchResponse)
204                         sendWorkflowResponse(execution, 200, synchResponse)
205
206                         logDebug('Exited ' + method, isDebugLogEnabled)
207                 } catch (BpmnError e) {
208                         throw e;
209                 } catch (Exception e) {
210                         logError('Caught exception in ' + method, e)
211                         createWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
212                 }
213         }
214                 
215         /**
216          * Currently passing the entire DELETE_VF_MODULE vnf-request to DoDeleteVfModule.
217          * 'DeleteVfModuleRequest' is now being set in preProcessRequest().
218          * TBD: may want to eventually create a specific request that only contains the needed fields.
219          *
220          * @param execution The flow's execution instance.
221          */
222         public void prepDoDeleteVfModule(Execution execution) {
223                 def method = getClass().getSimpleName() + '.prepDoDeleteVfModule(' +
224                         'execution=' + execution.getId() +
225                         ')'
226                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
227                 logDebug('Entered ' + method, isDebugLogEnabled)
228
229                 try {
230
231                         logDebug('Exited ' + method, isDebugLogEnabled)
232                 } catch (BpmnError e) {
233                         throw e;
234                 } catch (Exception e) {
235                         logError('Caught exception in ' + method, e)
236                         createWorkflowException(execution, 1002, 'Error in prepDoDeleteVfModule(): ' + e.getMessage())
237                 }
238         }
239                 
240         /**
241          * Prepare the DB update to add an entry for the Vf Module request.
242          *
243          * @param execution The flow's execution instance.
244          */
245         public void prepUpdateInfraRequest(Execution execution) {
246                 def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' +
247                         'execution=' + execution.getId() +
248                         ')'
249                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
250                 logDebug('Entered ' + method, isDebugLogEnabled)
251
252                 try {
253                         def requestId = execution.getVariable('DELVfModI_requestId')
254                         def vnfId = execution.getVariable('DELVfModI_vnfId')
255                         def vfModuleId = execution.getVariable('DELVfModI_vfModuleId')
256                         def tenantId = execution.getVariable('DELVfModI_tenantId')
257                         def volumeGroupId = execution.getVariable('DELVfModI_volumeGroupId')
258
259                         String updateInfraRequest = """
260                         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
261                                         xmlns:req="http://org.openecomp.mso/requestsdb">
262                                 <soapenv:Header/>
263                                 <soapenv:Body>
264                                         <req:updateInfraRequest>
265                                                 <requestId>${requestId}</requestId>
266                                                 <lastModifiedBy>BPMN</lastModifiedBy>
267                                                 <requestStatus>COMPLETED</requestStatus>
268                                                 <progress>100</progress>
269                                         </req:updateInfraRequest>
270                                 </soapenv:Body>
271                         </soapenv:Envelope>
272                 """
273
274                         updateInfraRequest = utils.formatXml(updateInfraRequest)
275                         execution.setVariable('DELVfModI_updateInfraRequest', updateInfraRequest)
276                         utils.logAudit("DeleteAAIVfModuleInfra Update Request: " + updateInfraRequest)
277                         logDebug('Request for Update Infra Request:\n' + updateInfraRequest, isDebugLogEnabled)
278
279                         logDebug('Exited ' + method, isDebugLogEnabled)
280                 } catch (BpmnError e) {
281                         throw e;
282                 } catch (Exception e) {
283                         logError('Caught exception in ' + method, e)
284                         createWorkflowException(execution, 1002, 'Error in prepInfraRequest(): ' + e.getMessage())
285                 }
286         }
287
288         /**
289          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
290          *
291          * @param execution the execution
292          * @param resultVar the execution variable in which the result will be stored
293          */
294         public void completionHandlerPrep(Execution execution, String resultVar) {
295                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
296                         'execution=' + execution.getId() +
297                         ', resultVar=' + resultVar +
298                         ')'
299                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
300                 logDebug('Entered ' + method, isDebugLogEnabled)
301
302                 try {
303                         def request = execution.getVariable("DeleteVfModuleRequest")
304                         def requestInfo = utils.getNodeXml(request, 'request-info', false)
305                         def action = utils.getNodeText1(requestInfo, "action")
306                         
307                         String content =
308                                         """  <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
309                                                    xmlns:ns="http://org.openecomp/mso/request/types/v1"
310                                                    xmlns:ns8="http://org.openecomp/mso/workflow/schema/v1">
311                 <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
312                 ${requestInfo}
313                 </request-info>
314                 <ns8:status-message>Vf Module has been deleted successfully.</ns8:status-message>
315                 <ns8:mso-bpel-name>BPMN</ns8:mso-bpel-name>
316                 </aetgt:MsoCompletionRequest>"""
317                         
318                         content = utils.formatXml(content)
319                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
320                         utils.logAudit("DeleteVfModule Infra Completion Handler Request: " + content)
321                         execution.setVariable(resultVar, content)
322
323                         logDebug('Exited ' + method, isDebugLogEnabled)
324                 } catch (BpmnError e) {
325                         throw e;
326                 } catch (Exception e) {
327                         logError('Caught exception in ' + method, e)
328                         createWorkflowException(execution, 2000, 'Internal Error')
329                 }
330         }
331
332         /**
333          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
334          *
335          * @param execution the execution
336          * @param resultVar the execution variable in which the result will be stored
337          */
338         public void falloutHandlerPrep(Execution execution, String resultVar) {
339                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
340                         'execution=' + execution.getId() +
341                         ', resultVar=' + resultVar +
342                         ')'
343                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
344                 logDebug('Entered ' + method, isDebugLogEnabled)
345                 
346                 try {
347                         def prefix = execution.getVariable('prefix')
348                         def request = execution.getVariable("DeleteVfModuleRequest")
349                         def requestInfo = utils.getNodeXml(request, 'request-info', false)
350                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
351                         def errorResponseCode = workflowException.getErrorCode()
352                         def errorResponseMsg = workflowException.getErrorMessage()
353                         def encErrorResponseMsg = ""
354                         if (errorResponseMsg != null) {
355                                 encErrorResponseMsg = errorResponseMsg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
356                         }
357
358                         String content = """
359                         <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
360                                         xmlns:reqtype="http://org.openecomp/mso/request/types/v1"
361                                         xmlns:msoservtypes="http://org.openecomp/mso/request/types/v1"
362                                         xmlns:structuredtypes="http://org.openecomp/mso/structured/types/v1">
363                                 ${requestInfo}
364                                 <sdncadapterworkflow:WorkflowException>
365                                         <sdncadapterworkflow:ErrorMessage>${encErrorResponseMsg}</sdncadapterworkflow:ErrorMessage>
366                                         <sdncadapterworkflow:ErrorCode>${errorResponseCode}</sdncadapterworkflow:ErrorCode>
367                                 </sdncadapterworkflow:WorkflowException>
368                         </sdncadapterworkflow:FalloutHandlerRequest>
369                 """
370                         content = utils.formatXml(content)
371                         utils.logAudit("DeleteVfModuleInfra Fallout Handler Request: " + content)
372                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
373                         execution.setVariable(resultVar, content)
374
375                         logDebug('Exited ' + method, isDebugLogEnabled)
376                 } catch (BpmnError e) {
377                         throw e;
378                 } catch (Exception e) {
379                         logError('Caught exception in ' + method, e)
380                         createWorkflowException(execution, 2000, 'Internal Error')
381                 }
382         }
383 }