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