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