Cleaned up content of MsoLogger
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateVfModuleInfra.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts;
24
25 import org.apache.commons.lang3.*
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.delegate.DelegateExecution
28 import org.onap.aai.domain.yang.v12.GenericVnf;
29 import org.onap.appc.client.lcm.model.Action
30 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor;
31 import org.onap.so.bpmn.common.scripts.ExceptionUtil;
32 import org.onap.so.bpmn.common.scripts.MsoUtils
33 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils;
34 import org.onap.so.bpmn.core.RollbackData
35 import org.onap.so.bpmn.core.UrnPropertiesReader
36 import org.onap.so.bpmn.core.WorkflowException
37 import org.onap.so.bpmn.core.json.JsonUtils
38 import org.onap.so.bpmn.infrastructure.aai.AAICreateResources;
39 import org.onap.so.logger.MessageEnum
40 import org.onap.so.logger.MsoLogger
41 import org.slf4j.Logger
42 import org.slf4j.LoggerFactory
43 import org.w3c.dom.*
44 import javax.xml.parsers.*
45 import org.xml.sax.InputSource
46 import groovy.json.JsonOutput
47 import groovy.json.JsonSlurper
48
49 public class CreateVfModuleInfra extends AbstractServiceTaskProcessor {
50     private static final Logger logger = LoggerFactory.getLogger( CreateVfModuleInfra.class);
51
52         ExceptionUtil exceptionUtil = new ExceptionUtil()
53         JsonUtils jsonUtil = new JsonUtils()
54
55         private AbstractServiceTaskProcessor taskProcessor
56         
57         public SDNCAdapterUtils(AbstractServiceTaskProcessor taskProcessor) {
58                 this.taskProcessor = taskProcessor
59         }       
60
61         /**
62          * Validates the request message and sets up the workflow.
63          * @param execution the execution
64          */
65         public void preProcessRequest(DelegateExecution execution) {
66                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
67                         'execution=' + execution.getId() +
68                         ')'
69
70                 logger.debug('Started ' + method)
71                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
72                 
73                 execution.setVariable("CVFMI_sentSyncResponse", false)
74                 
75                 def prefix = 'CVFMI_'
76                 execution.setVariable('prefix', prefix)
77                 execution.setVariable("isVidRequest", "false")
78
79                 def rollbackData = execution.getVariable("RollbackData")
80                 if (rollbackData == null) {
81                         rollbackData = new RollbackData()
82                 }
83                 execution.setVariable("RollbackData", rollbackData)
84                 
85                 def incomingRequest = execution.getVariable('bpmnRequest')
86                 logger.debug("Incoming Infra Request: " + incomingRequest)
87                 logger.debug("CreateVfModule Infra incoming Request: " + incomingRequest)
88
89                 setBasicDBAuthHeader(execution, isDebugLogEnabled)
90                 
91                 // check if request is xml or json
92                 try {
93                         def jsonSlurper = new JsonSlurper()
94                         def jsonOutput = new JsonOutput()
95                         Map reqMap = jsonSlurper.parseText(incomingRequest)
96                         logger.debug(" Request is in JSON format.")
97
98                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
99                         def vnfId = execution.getVariable('vnfId')
100                         
101                         execution.setVariable(prefix + 'serviceInstanceId', serviceInstanceId)
102                         execution.setVariable(prefix+'vnfId', vnfId)
103                         execution.setVariable("isVidRequest", "true")
104                         
105                         def vnfName = ''
106                         def asdcServiceModelVersion = ''
107                         def serviceModelInfo = null
108                         def vnfModelInfo = null
109                         
110                         def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList
111                                                 
112                         if (relatedInstanceList != null) {
113                                 relatedInstanceList.each {
114                                         if (it.relatedInstance.modelInfo?.modelType == 'service') {
115                                                 asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion
116                                                 serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo)
117                                                 
118                                         }
119                                         if (it.relatedInstance.modelInfo.modelType == 'vnf') {
120                                                 vnfName = it.relatedInstance.instanceName ?: ''
121                                                 vnfModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo)
122                                         }
123                                 }
124                         }
125                         
126                         execution.setVariable(prefix + 'vnfName', vnfName)
127                         execution.setVariable(prefix + 'asdcServiceModelVersion', asdcServiceModelVersion)
128                         execution.setVariable(prefix + 'serviceModelInfo', serviceModelInfo)
129                         execution.setVariable(prefix + 'vnfModelInfo', vnfModelInfo)
130                         
131                         
132                         def vnfType = execution.getVariable('vnfType')
133                         execution.setVariable(prefix + 'vnfType', vnfType)      
134                         def vfModuleId = execution.getVariable('vfModuleId')
135                         execution.setVariable(prefix + 'vfModuleId', vfModuleId)
136                         def volumeGroupId = execution.getVariable('volumeGroupId')
137                         execution.setVariable(prefix + 'volumeGroupId', volumeGroupId)
138                         def userParams = reqMap.requestDetails?.requestParameters?.userParams                                   
139                         
140                         Map<String, String> userParamsMap = [:]
141                         if (userParams != null) {
142                                 userParams.each { userParam ->
143                                         userParamsMap.put(userParam.name, userParam.value.toString())
144                                 }                                                       
145                         }               
146                                                 
147                         logger.debug('Processed user params: ' + userParamsMap)         
148                         
149                         execution.setVariable(prefix + 'vfModuleInputParams', userParamsMap)
150                         
151                         def isBaseVfModule = "false"
152                         if (execution.getVariable('isBaseVfModule') == true) {
153                                 isBaseVfModule = "true"
154                         }                       
155                         
156                         execution.setVariable(prefix + 'isBaseVfModule', isBaseVfModule)
157                                                 
158                         def requestId = execution.getVariable("mso-request-id")
159                         execution.setVariable(prefix + 'requestId', requestId)
160                         
161                         def vfModuleModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo)
162                         execution.setVariable(prefix + 'vfModuleModelInfo', vfModuleModelInfo)
163                         
164                         def suppressRollback = reqMap.requestDetails?.requestInfo?.suppressRollback
165                         
166                         
167                         def backoutOnFailure = ""
168                         if(suppressRollback != null){
169                                 if ( suppressRollback == true) {
170                                         backoutOnFailure = "false"
171                                 } else if ( suppressRollback == false) {
172                                         backoutOnFailure = "true"
173                                 }
174                         }
175                         
176                         execution.setVariable('disableRollback', suppressRollback)
177                         
178                         def vfModuleName = reqMap.requestDetails?.requestInfo?.instanceName ?: null
179                         execution.setVariable(prefix + 'vfModuleName', vfModuleName)
180                         
181                         def serviceId = reqMap.requestDetails?.requestParameters?.serviceId ?: ''
182                         execution.setVariable(prefix + 'serviceId', serviceId)
183                         
184                         def usePreload = reqMap.requestDetails?.requestParameters?.usePreload
185                         execution.setVariable(prefix + 'usePreload', usePreload)
186                         
187                         // This is aLaCarte flow, so aLaCarte flag is always on                         
188                         execution.setVariable(prefix + 'aLaCarte', true)
189                         
190                         def cloudConfiguration = reqMap.requestDetails?.cloudConfiguration
191                         def lcpCloudRegionId    = cloudConfiguration.lcpCloudRegionId
192                         execution.setVariable(prefix + 'lcpCloudRegionId', lcpCloudRegionId)
193                         
194                         def cloudOwner  = cloudConfiguration.cloudOwner
195                         execution.setVariable(prefix + 'cloudOwner', cloudOwner)
196                         
197                         def tenantId = cloudConfiguration.tenantId
198                         execution.setVariable(prefix + 'tenantId', tenantId)
199                         
200                         def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: ''
201                         execution.setVariable(prefix + 'globalSubscriberId', globalSubscriberId)
202                         
203                         execution.setVariable(prefix + 'sdncVersion', '1702')
204
205                         execution.setVariable("CreateVfModuleInfraSuccessIndicator", false)
206                         execution.setVariable("RollbackCompleted", false)
207                         
208                         execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
209                         
210                         
211                         def source = reqMap.requestDetails?.requestInfo?.source
212                         execution.setVariable("CVFMI_source", source)
213                         
214                         //For Completion Handler & Fallout Handler
215                         String requestInfo =
216                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
217                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
218                                         <action>CREATE</action>
219                                         <source>${MsoUtils.xmlEscape(source)}</source>
220                                    </request-info>"""
221                         
222                         execution.setVariable("CVFMI_requestInfo", requestInfo)
223                         
224                         //backoutOnFailure
225                         
226                         execution.setVariable("CVFMI_originalWorkflowException", null)
227                         
228
229                         def newVfModuleId = UUID.randomUUID().toString()
230                         execution.setVariable("newVfModuleId", newVfModuleId)
231                         execution.setVariable(prefix + 'vfModuleId', newVfModuleId)
232                         execution.setVariable('actionHealthCheck', Action.HealthCheck)
233                         execution.setVariable('actionConfigScaleOut', Action.ConfigScaleOut)
234                         execution.setVariable('controllerType', "APPC")
235                         def controllerType = execution.getVariable('controllerType')
236                         execution.setVariable(prefix + 'controllerType', controllerType)
237                         execution.setVariable('healthCheckIndex0', 0)
238
239                         logger.debug('RequestInfo: ' + execution.getVariable("CVFMI_requestInfo"))                      
240                         
241                         logger.debug('rollbackEnabled: ' + execution.getVariable("CVFMI_rollbackEnabled"))
242
243                         logger.trace('Finished ' + method)
244                 } catch (BpmnError bpmnError) {
245                         throw bpmnError
246                 }
247                 catch(groovy.json.JsonException je) {
248                         logger.debug("Request is not in JSON format.")
249                         exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - During PreProcessRequest")
250                 }
251                 catch(Exception e) {
252                         String restFaultMessage = e.getMessage()
253                         //execution.setVariable("CVFMODVOL2_RESTFault", restFaultMessage)
254                         //execution.setVariable("CVFMODVOL2_isDataOk", false)
255                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
256                                         " Exception Encountered - " + "\n" + restFaultMessage, "BPMN",
257                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
258                         exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - During PreProcessRequest")
259                 }
260
261         }
262
263         /**
264          * Validates a workflow response.
265          * @param execution the execution
266          * @param responseVar the execution variable in which the response is stored
267          * @param responseCodeVar the execution variable in which the response code is stored
268          * @param errorResponseVar the execution variable in which the error response is stored
269          */
270         public void validateWorkflowResponse(DelegateExecution execution, String responseVar,
271                         String responseCodeVar, String errorResponseVar) {
272                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
273                 sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar)
274         }
275
276
277         /**
278          * Sends the empty, synchronous response back to the API Handler.
279          * @param execution the execution
280          */
281         public void sendResponse(DelegateExecution execution) {
282                 def method = getClass().getSimpleName() + '.sendResponse(' +
283                         'execution=' + execution.getId() +
284                         ')'
285                 
286                 logger.trace('Started ' + method)
287
288                 try {
289                         def requestInfo = execution.getVariable('CVFMI_requestInfo')
290                         def requestId = execution.getVariable('CVFMI_requestId')
291                         def source = execution.getVariable('CVFMI_source')                      
292                         
293                         // RESTResponse (for API Handler (APIH) Reply Task)
294                         def newVfModuleId = execution.getVariable("newVfModuleId")
295                         String synchResponse = """{"requestReferences":{"instanceId":"${newVfModuleId}","requestId":"${requestId}"}}""".trim()
296
297                         sendWorkflowResponse(execution, 200, synchResponse)
298
299                         execution.setVariable("CVFMI_sentSyncResponse", true)
300                         logger.debug("CreateVfModule Infra Response: " + synchResponse)
301                         logger.trace('Finished ' + method)
302                 } catch (BpmnError e) {
303                         throw e;
304                 } catch (Exception e) {
305                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
306                                         "Exception Encountered ", "BPMN",
307                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
308                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
309                 }
310         }
311
312         /**
313          * Query AAI for vnf orchestration status to determine if health check and config scaling should be run
314          */
315         public void queryAAIForVnfOrchestrationStatus(DelegateExecution execution) {
316                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
317                 def vnfId = execution.getVariable("CVFMI_vnfId")
318                 execution.setVariable("runHealthCheck", false);
319                 execution.setVariable("runConfigScaleOut", false);
320                 AAICreateResources aaiCreateResources = new AAICreateResources();
321                 Optional<GenericVnf> vnf = aaiCreateResources.getVnfInstance(vnfId);
322                 if(vnf.isPresent()){
323                         def vnfOrchestrationStatus = vnf.get().getOrchestrationStatus();
324                         if("active".equalsIgnoreCase(vnfOrchestrationStatus)){
325                                 execution.setVariable("runHealthCheck", false);
326                                 execution.setVariable("runConfigScaleOut", true);
327                         }
328                 }
329         }
330         
331         /**
332          * Retrieve data for ConfigScaleOut from SDNC topology
333          */
334         
335         public void retreiveConfigScaleOutData(DelegateExecution execution){
336                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
337                 def vfModuleId = execution.getVariable("CVFMI_vfModuleId")
338                 String ipAddress = "";
339                 String oamIpAddress = "";
340                 String vnfHostIpAddress = "";
341
342                 String vnfGetSDNC = execution.getVariable("DCVFM_getSDNCAdapterResponse");
343
344                 String data = utils.getNodeXml(vnfGetSDNC, "response-data")
345                 data = data.replaceAll("&lt;", "<")
346                 data = data.replaceAll("&gt;", ">")
347
348                 InputSource source = new InputSource(new StringReader(data));
349                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
350                 docFactory.setNamespaceAware(true)
351                 DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
352                 Document responseXml = docBuilder.parse(source)
353
354                 NodeList paramsList = responseXml.getElementsByTagNameNS("*", "vnf-parameters")
355                 for (int z = 0; z < paramsList.getLength(); z++) {
356                         Node node = paramsList.item(z)
357                         Element eElement = (Element) node
358                         String vnfParameterName = utils.getElementText(eElement, "vnf-parameter-name")
359                         String vnfParameterValue = utils.getElementText(eElement, "vnf-parameter-value")
360                         if (vnfParameterName.equals("vlb_private_ip_1")) {
361                                 vnfHostIpAddress = vnfParameterValue
362                         }
363                         else if (vnfParameterName.equals("vdns_private_ip_0")) {
364                                 ipAddress = vnfParameterValue
365                         }
366                         else if (vnfParameterName.equals("vdns_private_ip_1")) {                        
367                                 oamIpAddress = vnfParameterValue
368                         }
369                 }
370
371                 String payload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"" + vnfHostIpAddress + "\",\"vf-module-id\":\"" + vfModuleId + "\"},\"configuration-parameters\":{\"ip-addr\":\"" + ipAddress +"\", \"oam-ip-addr\":\""+ oamIpAddress +"\",\"enabled\":\"true\"}}"
372                 execution.setVariable("payload", payload);
373         }
374
375         /**
376          *
377          * @param execution the execution
378          */
379         public void postProcessResponse(DelegateExecution execution){
380                 logger.trace("STARTED PostProcessResponse Process")
381                 try{                    
382                         def requestInfo = execution.getVariable("CVFMI_requestInfo")
383                         def action = utils.getNodeText(requestInfo, "action")
384
385                         logger.debug("requestInfo is: " + requestInfo)
386                         logger.debug("action is: " + action)
387
388                         String payload =
389                                         """  <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
390                                xmlns:ns="http://org.onap/so/request/types/v1"
391                                xmlns:ns8="http://org.onap/so/workflow/schema/v1">
392                         <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
393                         ${requestInfo}
394                         </request-info>
395                         <ns8:status-message>Vf Module has been created successfully.</ns8:status-message>
396                         <ns8:mso-bpel-name>BPMN</ns8:mso-bpel-name>
397                         </aetgt:MsoCompletionRequest>"""
398
399                         payload = utils.formatXml(payload)
400                         execution.setVariable("CVFMI_SuccessFlag", true)
401                         execution.setVariable("CVFMI_msoCompletionRequest", payload)
402                         logger.debug("CreateVfModuleInfra completion request: " + payload)
403                         logger.debug("Outgoing MsoCompletionRequest: \n" + payload)
404
405                 }catch(Exception e){
406                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
407                                         "Exception Occured Processing PostProcessResponse - " + "\n", "BPMN",
408                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
409                         execution.setVariable("CVFMI_ErrorResponse", "Error Occured during PostProcessResponse Method:\n" + e.getMessage())
410                 }
411                 logger.trace("COMPLETED PostProcessResponse Process")
412         }
413
414
415
416
417
418         /**
419          * Validates the request, request id and service instance id.  If a problem is found,
420          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
421          * method also sets up the log context for the workflow.
422          * @param execution the execution
423          * @return the validated request
424          */
425         public String validateInfraRequest(DelegateExecution execution) {
426                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
427                         'execution=' + execution.getId() +
428                         ')'
429                 
430                 logger.trace('Started ' + method)
431
432                 String processKey = getProcessKey(execution);
433                 def prefix = execution.getVariable("prefix")
434
435                 if (prefix == null) {
436                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
437                 }
438
439                 try {
440                         def request = execution.getVariable(prefix + 'Request')
441
442                         if (request == null) {
443                                 request = execution.getVariable(processKey + 'Request')
444
445                                 if (request == null) {
446                                         request = execution.getVariable('bpmnRequest')
447                                 }
448
449                                 setVariable(execution, processKey + 'Request', null);
450                                 setVariable(execution, 'bpmnRequest', null);
451                                 setVariable(execution, prefix + 'Request', request);
452                         }
453
454                         if (request == null) {
455                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
456                         }
457
458                         /*
459
460                         def requestId = execution.getVariable("mso-request-id")
461
462                         if (requestId == null) {
463                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id")
464                         }
465
466                         setVariable(execution, prefix + 'requestId', requestId)
467
468                         def serviceInstanceId = execution.getVariable("mso-service-instance-id")
469
470                         if (serviceInstanceId == null) {
471                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id")
472                         }
473
474                         utils.logContext(requestId, serviceInstanceId)
475                         */
476                         logger.debug("CreateVfModule incoming request: " + request)
477                         logger.debug('Incoming message: ' + System.lineSeparator() + request)
478                         logger.trace('Finished ' + method)
479                         return request
480                 } catch (BpmnError e) {
481                         throw e;
482                 } catch (Exception e) {
483                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
484                                         "Caught exception in " + method , "BPMN",
485                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
486                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
487                 }
488         }
489
490         public void prepareUpdateInfraRequest(DelegateExecution execution){
491                 logger.trace("STARTED prepareUpdateInfraRequest Process")
492                 try{
493                         
494                         String requestInfo = execution.getVariable("CVFMI_requestInfo")                 
495                         def aicCloudRegion      = execution.getVariable("CVFMI_lcpCloudRegionId")
496                         def tenantId = execution.getVariable("CVFMI_tenantId")
497                         def requestId = utils.getNodeText(requestInfo, "request-id")
498                         def vnfId = execution.getVariable("CVFMI_vnfId")
499                         def vfModuleId = execution.getVariable("CVFMI_vfModuleId")
500                         // vfModuleName may be generated by DoCreateVfModule subprocess if it is not specified on the input
501                         def vfModuleName = execution.getVariable("CVFMI_vfModuleName")
502
503                         def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint",execution)
504                         execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
505                         logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
506
507                         String payload =
508                                 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
509                                                 xmlns:ns="http://org.onap.so/requestsdb">
510                                                 <soapenv:Header/>
511                                                 <soapenv:Body>
512                                                         <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb">
513                                                         <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
514                                                         <lastModifiedBy>BPMN</lastModifiedBy>
515                                                         <statusMessage>VF Module successfully created</statusMessage>
516                                                         <responseBody></responseBody>
517                                                         <requestStatus>COMPLETE</requestStatus>
518                                                         <progress>100</progress>
519                                                         <vnfOutputs>&lt;vnf-outputs xmlns="http://org.onap/so/infra/vnf-request/v1" xmlns:aetgt="http://org.onap/so/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"&gt;&lt;vnf-id&gt;${MsoUtils.xmlEscape(vnfId)}&lt;/vnf-id&gt;&lt;vf-module-id&gt;${MsoUtils.xmlEscape(vfModuleId)}&lt;/vf-module-id&gt;&lt;/vnf-outputs&gt;</vnfOutputs>
520                                                         <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId>
521                                                         <vfModuleName>${MsoUtils.xmlEscape(vfModuleName)}</vfModuleName>
522                                                 </ns:updateInfraRequest>
523                                         </soapenv:Body>
524                                 </soapenv:Envelope>"""
525
526                         payload = utils.formatXml(payload)
527                         execution.setVariable("CVFMI_updateInfraRequest", payload)
528                         logger.debug("Outgoing UpdateInfraRequest: \n" + payload)
529                         logger.debug("CreateVfModuleInfra Outgoing UpdateInfra Request: " + payload)
530
531                 }catch(Exception e){
532                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
533                                         "Exception Occured Processing prepareUpdateInfraRequest.", "BPMN",
534                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
535                         execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareUpdateInfraRequest Method:\n" + e.getMessage())
536                 }
537                 logger.trace("COMPLETED prepareUpdateInfraRequest Process")
538         }
539
540         /**
541          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
542          *
543          * @param execution the execution
544          * @param resultVar the execution variable in which the result will be stored
545          */
546         public void falloutHandlerPrep(DelegateExecution execution, String resultVar) {
547                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
548                         'execution=' + execution.getId() +
549                         ', resultVar=' + resultVar +
550                         ')'
551                 
552                 logger.trace("Started " + method)
553
554
555                 try {
556                         def WorkflowException workflowException = execution.getVariable("WorkflowException")                    
557                         def requestInformation = execution.getVariable("CVFMI_requestInfo")
558                         def errorResponseCode = workflowException.getErrorCode()
559                         def errorResponseMsg = workflowException.getErrorMessage()
560                         def encErrorResponseMsg = ""
561                         if (errorResponseMsg != null) {
562                                 encErrorResponseMsg = errorResponseMsg
563                         }
564
565                         String content = """
566                                 <aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
567                                                 xmlns:reqtype="http://org.onap/so/request/types/v1"
568                                                 xmlns:msoservtypes="http://org.onap/so/request/types/v1"
569                                                 xmlns:structuredtypes="http://org.onap/so/structured/types/v1">
570                                                 ${requestInformation}
571                                         <aetgt:WorkflowException>
572                                                 <aetgt:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</aetgt:ErrorMessage>
573                                                 <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</aetgt:ErrorCode>
574                                         </aetgt:WorkflowException>
575                                 </aetgt:FalloutHandlerRequest>
576                         """
577
578                         logger.debug("CONTENT before translation: " + content)
579                         content = utils.formatXml(content)
580                         logger.debug(resultVar + ' = ' + System.lineSeparator() + content)
581                         logger.debug("CreateVfModuleInfra FallOutHander Request: " + content)
582                         execution.setVariable(resultVar, content)
583
584                         logger.trace('Exited ' + method)
585                 } catch (BpmnError e) {
586                         throw e;
587                 } catch (Exception e) {
588                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
589                                         "Caught exception in " + method , "BPMN",
590                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
591                         exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error')
592                 }
593         }
594
595         public void logAndSaveOriginalException(DelegateExecution execution) {
596                 def method = getClass().getSimpleName() + '.validateRollbackResponse(' +
597                         'execution=' + execution.getId() +
598                         ')'
599                 logger.trace('Entered ' + method)
600
601                 logWorkflowException(execution, 'CreateVfModuleInfra caught an event')
602                 saveWorkflowException(execution, 'CVFMI_originalWorkflowException')
603         }
604
605         public void validateRollbackResponse(DelegateExecution execution) {
606                 def method = getClass().getSimpleName() + '.validateRollbackResponse(' +
607                         'execution=' + execution.getId() +
608                         ')'
609                 logger.trace('Entered ' + method)
610                 def originalException = execution.getVariable("CVFMI_originalWorkflowException")
611                 execution.setVariable("WorkflowException", originalException)
612
613                 execution.setVariable("RollbackCompleted", true)
614
615         }
616         
617         public void sendErrorResponse(DelegateExecution execution){
618                 logger.trace("STARTED CreateVfModulenfra sendErrorResponse Process")
619                 try {
620                         def sentSyncResponse = execution.getVariable("CVFMI_sentSyncResponse")
621                         if(sentSyncResponse == false){
622                                 WorkflowException wfex = execution.getVariable("WorkflowException")
623                                 String response = exceptionUtil.buildErrorResponseXml(wfex)
624                                 logger.debug(response)
625                                 sendWorkflowResponse(execution, 500, response)
626                         }else{
627                                 logger.debug("Not Sending Error Response.  Sync Response Already Sent")
628                         }
629
630                 } catch (Exception ex) {
631                         logger.debug("Error Occured in CreateVfModuleInfra sendErrorResponse Process " + ex.getMessage())
632                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVfModuleInfra sendErrorResponse Process")
633                 }
634                 logger.trace("COMPLETED CreateVfModuleInfra sendErrorResponse Process")
635         }
636
637
638 }