Remove unnecessary use of Calendar.getInstance()
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / CreateVfModuleInfra.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.json.JsonSlurper
24
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.runtime.Execution
27 import org.apache.commons.lang3.*
28 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor;
29 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil;
30 import org.openecomp.mso.bpmn.common.scripts.NetworkUtils;
31 import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils;
32 import org.openecomp.mso.bpmn.common.scripts.VidUtils;
33 import org.openecomp.mso.bpmn.core.RollbackData
34 import org.openecomp.mso.bpmn.core.WorkflowException
35
36 public class CreateVfModuleInfra extends AbstractServiceTaskProcessor {
37         
38         /**
39          * Validates the request message and sets up the workflow.
40          * @param execution the execution
41          */
42         public void preProcessRequest(Execution execution) {
43                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
44                         'execution=' + execution.getId() +
45                         ')'
46                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
47                 logDebug('Entered ' + method, isDebugLogEnabled)
48
49                 def prefix = 'CVFMI_'
50                 logDebug('Entered 1' + method, isDebugLogEnabled)
51                 execution.setVariable('prefix', prefix)
52                 logDebug('Entered 2' + method, isDebugLogEnabled)
53                 execution.setVariable("isVidRequest", "false")
54                 
55                 logDebug("Set variables", isDebugLogEnabled)    
56                 
57                 def rollbackData = execution.getVariable("RollbackData")
58                 if (rollbackData == null) {
59                         rollbackData = new RollbackData()
60                 }
61                 execution.setVariable("RollbackData", rollbackData)
62                 
63                 logDebug("Set rollback data", isDebugLogEnabled)
64                 def incomingRequest = execution.getVariable('bpmnRequest')
65                 
66                 utils.log("DEBUG", "Incoming Infra Request: " + incomingRequest, isDebugLogEnabled)
67                 utils.logAudit("CreateVfModule Infra incoming Request: " + incomingRequest)
68                 
69                 // check if request is xml or json
70                 try {
71                         def jsonSlurper = new JsonSlurper()
72                         Map reqMap = jsonSlurper.parseText(incomingRequest)
73                         utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled)
74                         
75                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
76                         def vnfId = execution.getVariable('vnfId')
77                         
78                         def vidUtils = new VidUtils(this)
79                         
80                         String requestInXmlFormat = vidUtils.createXmlVfModuleRequest(execution, reqMap, 'CREATE_VF_MODULE', serviceInstanceId)
81                         
82                         utils.log("DEBUG", " Request in XML format: " + requestInXmlFormat, isDebugLogEnabled)
83                         
84                         execution.setVariable(prefix + 'Request', requestInXmlFormat)
85                         execution.setVariable(prefix+'vnfId', vnfId)
86                         execution.setVariable("isVidRequest", "true")                   
87                         
88                 }
89                 catch(groovy.json.JsonException je) {
90                         utils.log("DEBUG", " Request is not in JSON format.", isDebugLogEnabled)
91                         workflowException(execution, "Invalid request format", 400)
92                         
93                 }
94                 catch(Exception e) {
95                         String restFaultMessage = e.getMessage()
96                         //execution.setVariable("CVFMODVOL2_RESTFault", restFaultMessage)
97                         //execution.setVariable("CVFMODVOL2_isDataOk", false)
98                         utils.log("ERROR", " Exception Encountered - " + "\n" + restFaultMessage, isDebugLogEnabled)
99                         workflowException(execution, restFaultMessage, 400)
100                 }
101
102                 try {
103                         String request = validateInfraRequest(execution)
104                         
105                         execution.setVariable("CreateVfModuleInfraSuccessIndicator", false)
106                         execution.setVariable("RollbackCompleted", false)
107                         execution.setVariable("DoCreateVfModuleRequest", request)
108                         execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
109                         execution.setVariable("CVFMI_requestInfo",utils.getNodeXml(request,"request-info"))     
110                         execution.setVariable("CVFMI_requestId",utils.getNodeText1(request,"request-id"))
111                         execution.setVariable("CVFMI_source",utils.getNodeText1(request,"source"))
112                         execution.setVariable("CVFMI_serviceInstanceId", utils.getNodeText1(request, "service-instance-id"))            
113                         execution.setVariable("CVFMI_vnfInputs",utils.getNodeXml(request,"vnf-inputs"))
114                         //backoutOnFailure
115                         
116                         NetworkUtils networkUtils = new NetworkUtils()
117                         execution.setVariable("CVFMI_rollbackEnabled", networkUtils.isRollbackEnabled(execution,request))
118                         execution.setVariable("CVFMI_originalWorkflowException", null)
119                         def vnfParams = ""
120                         if (utils.nodeExists(request, "vnf-params")) {
121                                 vnfParams = utils.getNodeXml(request,"vnf-params")
122                         }
123                         execution.setVariable("CVFMI_vnfParams", vnfParams)
124                         
125                         def newVfModuleId = UUID.randomUUID().toString()
126                         execution.setVariable("newVfModuleId", newVfModuleId)
127                         
128                         logDebug('RequestInfo: ' + execution.getVariable("CVFMI_requestInfo"), isDebugLogEnabled)
129                         logDebug('VnfInputs: ' + execution.getVariable("CVFMI_vnfInputs"), isDebugLogEnabled)
130                         logDebug('VnfParams: ' + execution.getVariable("CVFMI_vnfParams"), isDebugLogEnabled)
131                         logDebug('rollbackEnabled: ' + execution.getVariable("CVFMI_rollbackEnabled"), isDebugLogEnabled)
132                         
133                         logDebug('Exited ' + method, isDebugLogEnabled)
134                 } catch (BpmnError bpmnError) {
135                         buildErrorResponse(execution,bpmnError.getMessage(),"400")
136                         throw bpmnError
137                 } catch (Exception exception) {
138                         workflowException(execution, exception.getMessage(), 400)
139                 }                
140         }
141
142         /**
143          * Validates a workflow response.
144          * @param execution the execution
145          * @param responseVar the execution variable in which the response is stored
146          * @param responseCodeVar the execution variable in which the response code is stored
147          * @param errorResponseVar the execution variable in which the error response is stored
148          */
149         public void validateWorkflowResponse(Execution execution, String responseVar,
150                         String responseCodeVar, String errorResponseVar) {
151                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
152                 sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar)
153         }
154
155
156         /**
157          * Sends the empty, synchronous response back to the API Handler.
158          * @param execution the execution
159          */
160         public void sendResponse(Execution execution) {
161                 def method = getClass().getSimpleName() + '.sendResponse(' +
162                         'execution=' + execution.getId() +
163                         ')'
164                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
165                 logDebug('Entered ' + method, isDebugLogEnabled)
166
167                 try {
168                         def requestInfo = execution.getVariable('CVFMI_requestInfo')
169                         def requestId = execution.getVariable('CVFMI_requestId')
170                         def source = execution.getVariable('CVFMI_source')
171                         def progress = getNodeTextForce(requestInfo, 'progress')
172                         if (progress.isEmpty()) {
173                                 progress = '0'
174                         }
175                         def startTime = getNodeTextForce(requestInfo, 'start-time')
176                         if (startTime.isEmpty()) {
177                                 startTime = System.currentTimeMillis()
178                         }                       
179                                 
180                         // RESTResponse (for API Handler (APIH) Reply Task)
181                         def newVfModuleId = execution.getVariable("newVfModuleId")
182                         String synchResponse = """{"requestReferences":{"instanceId":"${newVfModuleId}","requestId":"${requestId}"}}""".trim()
183                         
184                         sendWorkflowResponse(execution, 200, synchResponse)
185                         
186                         utils.logAudit("CreateVfModule Infra Response: " + synchResponse)
187                         logDebug('Exited ' + method, isDebugLogEnabled)
188                 } catch (BpmnError e) {
189                         throw e;
190                 } catch (Exception e) {
191                         logError('Caught exception in ' + method, e)
192                         createWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
193                 }
194         }
195
196         /**
197          * 
198          * @param execution the execution
199          */
200         public void postProcessResponse(Execution execution){
201                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
202                 
203                 utils.log("DEBUG", " ======== STARTED PostProcessResponse Process ======== ", isDebugEnabled)
204                 try{
205                         def request = execution.getVariable("DoCreateVfModuleRequest")
206                         def requestInfo = utils.getNodeXml(request, 'request-info', false)
207                         def action = utils.getNodeText1(requestInfo, "action")
208                         
209                         utils.log("DEBUG", "requestInfo is: " + requestInfo, isDebugEnabled)                    
210                         utils.log("DEBUG", "action is: " + action, isDebugEnabled)
211
212                         String payload =
213                                         """  <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
214                                xmlns:ns="http://org.openecomp/mso/request/types/v1"
215                                xmlns:ns8="http://org.openecomp/mso/workflow/schema/v1">
216                         <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
217                         ${requestInfo}
218                         </request-info>
219                         <ns8:status-message>Vf Module has been created successfully.</ns8:status-message>
220                         <ns8:mso-bpel-name>BPMN</ns8:mso-bpel-name>
221                         </aetgt:MsoCompletionRequest>"""
222
223                         payload = utils.formatXml(payload)
224                         execution.setVariable("CVFMI_SuccessFlag", true)
225                         execution.setVariable("CVFMI_msoCompletionRequest", payload)
226                         utils.logAudit("CreateVfModuleInfra completion request: " + payload)
227                         utils.log("DEBUG", "Outgoing MsoCompletionRequest: \n" + payload, isDebugEnabled)
228
229                 }catch(Exception e){
230                         utils.log("ERROR", "Exception Occured Processing PostProcessResponse. Exception is:\n" + e, isDebugEnabled)
231                         execution.setVariable("CVFMI_ErrorResponse", "Error Occured during PostProcessResponse Method:\n" + e.getMessage())
232                 }
233                 utils.log("DEBUG", "======== COMPLETED PostProcessResponse Process ======== ", isDebugEnabled)
234         }
235
236         
237         
238         
239         
240         /**
241          * Validates the request, request id and service instance id.  If a problem is found,
242          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
243          * method also sets up the log context for the workflow.
244          * @param execution the execution
245          * @return the validated request
246          */
247         public String validateInfraRequest(Execution execution) {
248                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
249                         'execution=' + execution.getId() +
250                         ')'
251                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
252                 logDebug('Entered ' + method, isDebugLogEnabled)
253
254                 String processKey = getProcessKey(execution);
255                 def prefix = execution.getVariable("prefix")
256
257                 if (prefix == null) {
258                         createWorkflowException(execution, 1002, processKey + " prefix is null")
259                 }
260
261                 try {
262                         def request = execution.getVariable(prefix + 'Request')
263
264                         if (request == null) {
265                                 request = execution.getVariable(processKey + 'Request')
266         
267                                 if (request == null) {
268                                         request = execution.getVariable('bpmnRequest')
269                                 }
270         
271                                 setVariable(execution, processKey + 'Request', null);
272                                 setVariable(execution, 'bpmnRequest', null);
273                                 setVariable(execution, prefix + 'Request', request);
274                         }
275
276                         if (request == null) {
277                                 createWorkflowException(execution, 1002, processKey + " request is null")
278                         }
279                         
280                         /*
281
282                         def requestId = execution.getVariable("mso-request-id")
283                         
284                         if (requestId == null) {
285                                 createWorkflowException(execution, 1002, processKey + " request has no mso-request-id")
286                         }
287                         
288                         setVariable(execution, prefix + 'requestId', requestId)
289
290                         def serviceInstanceId = execution.getVariable("mso-service-instance-id")
291
292                         if (serviceInstanceId == null) {
293                                 createWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id")
294                         }
295
296                         utils.logContext(requestId, serviceInstanceId)
297                         */
298                         utils.logAudit("CreateVfModule incoming request: " + request)
299                         logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled)
300                         logDebug('Exited ' + method, isDebugLogEnabled)
301                         return request
302                 } catch (BpmnError e) {
303                         throw e;
304                 } catch (Exception e) {
305                         logError('Caught exception in ' + method, e)
306                         createWorkflowException(execution, 1002, "Invalid Message")
307                 }
308         }
309         
310         public void prepareUpdateInfraRequest(Execution execution){
311                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
312                 ExceptionUtil exceptionUtil = new ExceptionUtil()
313                 
314                 utils.log("DEBUG", " ======== STARTED prepareUpdateInfraRequest Process ======== ", isDebugEnabled)
315                 try{
316
317                         String vnfInputs = execution.getVariable("CVFMI_vnfInputs")
318                         String requestInfo = execution.getVariable("CVFMI_requestInfo")
319                         def aicCloudRegion      = utils.getNodeText1(vnfInputs, "aic-cloud-region")
320                         def tenantId = utils.getNodeText1(vnfInputs, "tenant-id")
321                         def requestId = utils.getNodeText1(requestInfo, "request-id")
322                         def vnfId = execution.getVariable("CVFMI_vnfId")
323                         def vfModuleId = execution.getVariable("CVFMI_vfModuleId")
324
325                         def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_db_endpoint")
326                         execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
327                         utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled)
328                         
329                         try {
330                                 String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth")
331                                 utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled)
332                                 
333                                 def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey"))
334                                 execution.setVariable("BasicAuthHeaderValueDB",encodedString)
335                         } catch (IOException ex) {
336                                 String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage()
337                                 utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
338                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
339                         }
340                         
341                         String payload =
342                                 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
343                                                 xmlns:ns="http://org.openecomp.mso/requestsdb">
344                                                 <soapenv:Header/>
345                                                 <soapenv:Body>
346                                                         <ns:updateInfraRequest xmlns:ns="http://org.openecomp.mso/requestsdb">
347                                                         <requestId>${requestId}</requestId>
348                                                         <lastModifiedBy>BPMN</lastModifiedBy>
349                                                         <statusMessage>VF Module successfully created</statusMessage>
350                                                         <responseBody></responseBody>
351                                                         <requestStatus>COMPLETE</requestStatus>
352                                                         <progress>100</progress>
353                                                         <vnfOutputs>&lt;vnf-outputs xmlns="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:aetgt="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"&gt;&lt;vnf-id&gt;${vnfId}&lt;/vnf-id&gt;&lt;vf-module-id&gt;${vfModuleId}&lt;/vf-module-id&gt;&lt;/vnf-outputs&gt;</vnfOutputs>
354                                                         <vfModuleId>${vfModuleId}</vfModuleId>
355                                                 </ns:updateInfraRequest> 
356                                         </soapenv:Body>
357                                 </soapenv:Envelope>"""
358
359                         payload = utils.formatXml(payload)
360                         execution.setVariable("CVFMI_updateInfraRequest", payload)
361                         utils.log("DEBUG", "Outgoing UpdateInfraRequest: \n" + payload, isDebugEnabled)
362                         utils.logAudit("CreateVfModuleInfra Outgoing UpdateInfra Request: " + payload)
363                         
364                 }catch(Exception e){
365                         utils.log("ERROR", "Exception Occured Processing prepareUpdateInfraRequest. Exception is:\n" + e, isDebugEnabled)
366                         execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareUpdateInfraRequest Method:\n" + e.getMessage())
367                 }
368                 utils.log("DEBUG", "======== COMPLETED prepareUpdateInfraRequest Process ======== ", isDebugEnabled)
369         }
370         
371         /**
372          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
373          * 
374          * @param execution the execution
375          * @param resultVar the execution variable in which the result will be stored
376          */
377         public void falloutHandlerPrep(Execution execution, String resultVar) {
378                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
379                         'execution=' + execution.getId() +
380                         ', resultVar=' + resultVar +
381                         ')'
382                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
383                 logDebug('Entered ' + method, isDebugLogEnabled)
384                 
385                 
386                 try {
387                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
388                         def request = execution.getVariable("DoCreateVfModuleRequest")
389                         def requestInformation = utils.getNodeXml(request, 'request-info', false)
390                         def errorResponseCode = workflowException.getErrorCode()
391                         def errorResponseMsg = workflowException.getErrorMessage()
392                         def encErrorResponseMsg = ""
393                         if (errorResponseMsg != null) {
394                                 encErrorResponseMsg = errorResponseMsg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
395                         }
396
397                         String content = """
398                                 <aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
399                                                 xmlns:reqtype="http://org.openecomp/mso/request/types/v1"
400                                                 xmlns:msoservtypes="http://org.openecomp/mso/request/types/v1"
401                                                 xmlns:structuredtypes="http://org.openecomp/mso/structured/types/v1">
402                                                 ${requestInformation}                                                                           
403                                         <aetgt:WorkflowException>
404                                                 <aetgt:ErrorMessage>${encErrorResponseMsg}</aetgt:ErrorMessage>
405                                                 <aetgt:ErrorCode>${errorResponseCode}</aetgt:ErrorCode>
406                                         </aetgt:WorkflowException>      
407                                 </aetgt:FalloutHandlerRequest>
408                         """
409                         
410                         logDebug("CONTENT before translation: " + content, isDebugLogEnabled)
411                         content = utils.formatXml(content)
412                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
413                         utils.logAudit("CreateVfModuleInfra FallOutHander Request: " + content)
414                         execution.setVariable(resultVar, content)
415
416                         logDebug('Exited ' + method, isDebugLogEnabled)
417                 } catch (BpmnError e) {
418                         throw e;
419                 } catch (Exception e) {
420                         logError('Caught exception in ' + method, e)
421                         createWorkflowException(execution, 2000, 'Internal Error')
422                 }
423         }
424         
425         public void logAndSaveOriginalException(Execution execution) {
426                 def method = getClass().getSimpleName() + '.validateRollbackResponse(' +
427                         'execution=' + execution.getId() +
428                         ')'
429                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
430                 logDebug('Entered ' + method, isDebugLogEnabled)
431                 
432                 logWorkflowException(execution, 'CreateVfModuleInfra caught an event')
433                 saveWorkflowException(execution, 'CVFMI_originalWorkflowException')
434         }
435         
436         public void validateRollbackResponse(Execution execution) {
437                 def method = getClass().getSimpleName() + '.validateRollbackResponse(' +
438                         'execution=' + execution.getId() +
439                         ')'
440                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
441                 logDebug('Entered ' + method, isDebugLogEnabled)
442                 
443                 def originalException = execution.getVariable("CVFMI_originalWorkflowException")
444                 execution.setVariable("WorkflowException", originalException)
445                 
446                 execution.setVariable("RollbackCompleted", true)
447         
448         }
449         
450                 
451 }