Groovy scripts header correction
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / DoCreateVfModule.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.openecomp.mso.bpmn.infrastructure.scripts;
22
23 import javax.xml.parsers.DocumentBuilder
24 import javax.xml.parsers.DocumentBuilderFactory
25
26 import org.apache.commons.lang3.*
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.runtime.Execution
29 import org.openecomp.mso.bpmn.common.scripts.AaiUtil
30 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
31 import org.openecomp.mso.bpmn.common.scripts.NetworkUtils
32 import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils
33 import org.openecomp.mso.bpmn.common.scripts.VfModuleBase
34 import org.openecomp.mso.bpmn.core.RollbackData
35 import org.openecomp.mso.bpmn.core.WorkflowException
36 import org.openecomp.mso.bpmn.core.json.JsonUtils
37 import org.openecomp.mso.rest.APIResponse
38 import org.openecomp.mso.rest.RESTClient
39 import org.openecomp.mso.rest.RESTConfig
40 import org.springframework.web.util.UriUtils
41 import org.w3c.dom.Document
42 import org.w3c.dom.Element
43 import org.w3c.dom.NamedNodeMap
44 import org.w3c.dom.Node
45 import org.w3c.dom.NodeList
46 import org.xml.sax.InputSource
47
48
49
50 public class DoCreateVfModule extends VfModuleBase {
51
52         String Prefix="DCVFM_"
53         ExceptionUtil exceptionUtil = new ExceptionUtil()
54         JsonUtils jsonUtil = new JsonUtils()
55         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
56
57         /**
58          * Validates the request message and sets up the workflow.
59          * @param execution the execution
60          */
61         public void preProcessRequest(Execution execution) {
62                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
63                         'execution=' + execution.getId() +
64                         ')'
65                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
66                 logDebug('Entered ' + method, isDebugLogEnabled)
67
68                 execution.setVariable('prefix', Prefix)
69                 try{
70                         def rollbackData = execution.getVariable("rollbackData")
71                         if (rollbackData == null) {
72                                 rollbackData = new RollbackData()
73                         }
74
75                         execution.setVariable("DCVFM_vnfParamsExistFlag", false)
76                         execution.setVariable("DCVFM_oamManagementV4Address", "")
77                         execution.setVariable("DCVFM_oamManagementV6Address", "")
78
79                         String request = execution.getVariable("DoCreateVfModuleRequest")
80
81                         if (request == null || request.isEmpty()) {
82                                 // Building Block-type request
83
84                                 String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo")           
85                                 
86                                 def serviceModelInfo = execution.getVariable("serviceModelInfo")
87                                 logDebug("serviceModelInfo: " + serviceModelInfo, isDebugLogEnabled)
88                                 def vnfModelInfo = execution.getVariable("vnfModelInfo")
89                                 
90
91                                 //tenantId
92                                 def tenantId = execution.getVariable("tenantId")
93                                 execution.setVariable("DCVFM_tenantId", tenantId)
94                                 rollbackData.put("VFMODULE", "tenantid", tenantId)
95                                 //volumeGroupId
96                                 def volumeGroupId = execution.getVariable("volumeGroupId")
97                                 execution.setVariable("DCVFM_volumeGroupId", volumeGroupId)
98                                 //volumeGroupName
99                                 def volumeGroupName = execution.getVariable("volumeGroupName")
100                                 execution.setVariable("DCVFM_volumeGroupName", volumeGroupName)
101                                 //cloudSiteId
102                                 def cloudSiteId = execution.getVariable("lcpCloudRegionId")
103                                 execution.setVariable("DCVFM_cloudSiteId", cloudSiteId)
104                                 rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId)
105                                 logDebug("cloudSiteId: " + cloudSiteId, isDebugLogEnabled)
106                                 //vnfType
107                                 def vnfType = execution.getVariable("vnfType")
108                                 execution.setVariable("DCVFM_vnfType", vnfType)
109                                 rollbackData.put("VFMODULE", "vnftype", vnfType)
110                                 logDebug("vnfType: " + vnfType, isDebugLogEnabled)
111                                 //vnfName
112                                 def vnfName = execution.getVariable("vnfName")
113                                 execution.setVariable("DCVFM_vnfName", vnfName)
114                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
115                                 logDebug("vnfName: " + vnfName, isDebugLogEnabled)
116                                 //vnfId
117                                 def vnfId = execution.getVariable("vnfId")
118                                 execution.setVariable("DCVFM_vnfId", vnfId)
119                                 rollbackData.put("VFMODULE", "vnfid", vnfId)
120                                 logDebug("vnfId: " + vnfId, isDebugLogEnabled)
121                                 //vfModuleName
122                                 def vfModuleName = execution.getVariable("vfModuleName")
123                                 execution.setVariable("DCVFM_vfModuleName", vfModuleName)
124                                 rollbackData.put("VFMODULE", "vfmodulename", vfModuleName)
125                                 logDebug("vfModuleName: " + vfModuleName, isDebugLogEnabled)
126                                 //vfModuleModelName
127                                 def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName")
128                                 execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName)
129                                 rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName)
130                                 logDebug("vfModuleModelName: " + vfModuleModelName, isDebugLogEnabled)
131                                 //modelCustomizationUuid
132                                 def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelCustomizationUuid")
133                                 execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid)
134                                 rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid)
135                                 logDebug("modelCustomizationUuid: " + modelCustomizationUuid, isDebugLogEnabled)
136                                 //vfModuleId
137                                 def vfModuleId = execution.getVariable("vfModuleId")
138                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
139                                 logDebug("vfModuleId: " + vfModuleId, isDebugLogEnabled)
140                                 def requestId = execution.getVariable("msoRequestId")
141                                 execution.setVariable("DCVFM_requestId", requestId)
142                                 logDebug("requestId: " + requestId, isDebugLogEnabled)
143                                 rollbackData.put("VFMODULE", "msorequestid", requestId)
144                                 // Set mso-request-id to request-id for VNF Adapter interface
145                                 execution.setVariable("mso-request-id", requestId)
146                                 //serviceId
147                                 def serviceId = execution.getVariable("serviceId")
148                                 execution.setVariable("DCVFM_serviceId", serviceId)
149                                 logDebug("serviceId: " + serviceId, isDebugLogEnabled)
150                                 //serviceInstanceId
151                                 def serviceInstanceId = execution.getVariable("serviceInstanceId")
152                                 execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId)
153                                 rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId)
154                                 logDebug("serviceInstanceId: " + serviceInstanceId, isDebugLogEnabled)
155                                 //source - HARDCODED
156                                 def source = "VID"
157                                 execution.setVariable("DCVFM_source", source)
158                                 rollbackData.put("VFMODULE", "source", source)
159                                 logDebug("source: " + source, isDebugLogEnabled)
160                                 //backoutOnFailure
161                                 def disableRollback = execution.getVariable("disableRollback")
162                                 def backoutOnFailure = true
163                                 if (disableRollback != null && disableRollback == true) {
164                                         backoutOnFailure = false
165                                 }
166                                 execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure)
167                                 logDebug("backoutOnFailure: " + backoutOnFailure, isDebugLogEnabled)
168                                 //isBaseVfModule
169                                 def isBaseVfModule = execution.getVariable("isBaseVfModule")
170                                 execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule)
171                                 logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled)
172                                 //asdcServiceModelVersion
173                                 def asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion")
174                                 execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion)
175                                 logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled)
176                                 //personaModelId
177                                 execution.setVariable("DCVFM_personaModelId", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInvariantUuid"))
178                                 //personaModelVersion
179                                 execution.setVariable("DCVFM_personaModelVersion", jsonUtil.getJsonValue(vfModuleModelInfo, "modelUuid"))
180                                 //vfModuleLabel
181                                 def vfModuleLabel = execution.getVariable("vfModuleLabel")
182                                 if (vfModuleLabel != null) {
183                                         execution.setVariable("DCVFM_vfModuleLabel", vfModuleLabel)
184                                         logDebug("vfModuleLabel: " + vfModuleLabel, isDebugLogEnabled)
185                                 }
186                                 //Get or Generate UUID
187                                 String uuid = execution.getVariable("DCVFM_uuid")
188                                 if(uuid == null){
189                                         uuid = UUID.randomUUID()
190                                         logDebug("Generated messageId (UUID) is: " + uuid, isDebugLogEnabled)
191                                 }else{
192                                         logDebug("Found messageId (UUID) is: " + uuid, isDebugLogEnabled)
193                                 }
194                                 //isVidRequest
195                                 String isVidRequest = execution.getVariable("isVidRequest")
196                                 // default to true
197                                 if (isVidRequest == null || isVidRequest.isEmpty()) {
198                                         execution.setVariable("isVidRequest", "true")
199                                 }
200                                 //globalSubscriberId
201                                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
202                                 execution.setVariable("DCVFM_globalSubscriberId", globalSubscriberId)
203                                 logDebug("globalSubsrciberId: " + globalSubscriberId, isDebugLogEnabled)                                
204                                 Map<String,String> vfModuleInputParams = execution.getVariable("vfModuleInputParams")
205                                 if (vfModuleInputParams != null) {
206                                         execution.setVariable("DCVFM_vnfParamsMap", vfModuleInputParams)
207                                         execution.setVariable("DCVFM_vnfParamsExistFlag", true)
208                                 }
209                                 //usePreload
210                                 def usePreload = execution.getVariable("usePreload")
211                                 execution.setVariable("DCVFM_usePreload", usePreload)
212                                 logDebug("usePreload: " + usePreload, isDebugLogEnabled)
213
214                         }
215                         else {
216                                 // The info is inside the request - DEAD CODE
217                                 utils.logAudit("DoCreateVfModule request: " + request)
218
219                                 //tenantId
220                                 def tenantId = ""
221                                 if (utils.nodeExists(request, "tenant-id")) {
222                                         tenantId = utils.getNodeText(request, "tenant-id")
223                                 }
224                                 execution.setVariable("DCVFM_tenantId", tenantId)
225                                 rollbackData.put("VFMODULE", "tenantid", tenantId)
226                                 //volumeGroupId
227                                 def volumeGroupId = ""
228                                 if (utils.nodeExists(request, "volume-group-id")) {
229                                         volumeGroupId = utils.getNodeText(request, "volume-group-id")
230                                 }
231                                 execution.setVariable("DCVFM_volumeGroupId", volumeGroupId)
232                                 //volumeGroupId
233                                 def volumeGroupName = ""
234                                 if (utils.nodeExists(request, "volume-group-name")) {
235                                         volumeGroupName = utils.getNodeText(request, "volume-group-name")
236                                 }
237                                 execution.setVariable("DCVFM_volumeGroupName", volumeGroupName)
238                                 //cloudSiteId
239                                 def cloudSiteId = ""
240                                 if (utils.nodeExists(request, "aic-cloud-region")) {
241                                         cloudSiteId = utils.getNodeText(request, "aic-cloud-region")
242                                 }
243                                 execution.setVariable("DCVFM_cloudSiteId", cloudSiteId)
244                                 rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId)
245                                 logDebug("cloudSiteId: " + cloudSiteId, isDebugLogEnabled)
246                                 //vnfType
247                                 def vnfType = ""
248                                 if (utils.nodeExists(request, "vnf-type")) {
249                                         vnfType = utils.getNodeText(request, "vnf-type")
250                                 }
251                                 execution.setVariable("DCVFM_vnfType", vnfType)
252                                 rollbackData.put("VFMODULE", "vnftype", vnfType)
253                                 logDebug("vnfType: " + vnfType, isDebugLogEnabled)
254                                 //vnfName
255                                 def vnfName = ""
256                                 if (utils.nodeExists(request, "vnf-name")) {
257                                         vnfName = utils.getNodeText(request, "vnf-name")
258                                 }
259                                 execution.setVariable("DCVFM_vnfName", vnfName)
260                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
261                                 logDebug("vnfName: " + vnfName, isDebugLogEnabled)
262                                 //vnfId
263                                 def vnfId = ""
264                                 if (utils.nodeExists(request, "vnf-id")) {
265                                         vnfId = utils.getNodeText(request, "vnf-id")
266                                 }
267                                 execution.setVariable("DCVFM_vnfId", vnfId)
268                                 rollbackData.put("VFMODULE", "vnfid", vnfId)
269                                 logDebug("vnfId: " + vnfId, isDebugLogEnabled)
270                                 //vfModuleName
271                                 def vfModuleName = ""
272                                 if (utils.nodeExists(request, "vf-module-name")) {
273                                         vfModuleName = utils.getNodeText(request, "vf-module-name")
274                                 }
275                                 execution.setVariable("DCVFM_vfModuleName", vfModuleName)
276                                 rollbackData.put("VFMODULE", "vfmodulename", vfModuleName)
277                                 logDebug("vfModuleName: " + vfModuleName, isDebugLogEnabled)
278                                 //vfModuleModelName
279                                 def vfModuleModelName = ""
280                                 if (utils.nodeExists(request, "vf-module-model-name")) {
281                                         vfModuleModelName = utils.getNodeText(request, "vf-module-model-name")
282                                 }
283                                 execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName)
284                                 rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName)
285                                 logDebug("vfModuleModelName: " + vfModuleModelName, isDebugLogEnabled)
286                                 //modelCustomizationUuid
287                                 def modelCustomizationUuid = ""
288                                 if (utils.nodeExists(request, "model-customization-id")) {
289                                         modelCustomizationUuid = utils.getNodeText(request, "model-customization-id")
290                                 }
291                                 execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid)
292                                 rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid)
293                                 logDebug("modelCustomizationUuid: " + modelCustomizationUuid, isDebugLogEnabled)
294                                 //vfModuleId
295                                 def vfModuleId = ""
296                                 if (utils.nodeExists(request, "vf-module-id")) {
297                                         vfModuleId = utils.getNodeText(request, "vf-module-id")
298                                 }
299                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
300                                 logDebug("vfModuleId: " + vfModuleId, isDebugLogEnabled)
301                                 def requestId = ""
302                                 if (utils.nodeExists(request, "request-id")) {
303                                         requestId = utils.getNodeText(request, "request-id")
304                                 }
305                                 execution.setVariable("DCVFM_requestId", requestId)
306                                 logDebug("requestId: " + requestId, isDebugLogEnabled)
307                                 //serviceId
308                                 def serviceId = ""
309                                 if (utils.nodeExists(request, "service-id")) {
310                                         serviceId = utils.getNodeText(request, "service-id")
311                                 }
312                                 execution.setVariable("DCVFM_serviceId", serviceId)
313                                 logDebug("serviceId: " + serviceId, isDebugLogEnabled)
314                                 //serviceInstanceId
315                                 def serviceInstanceId = ""
316                                 if (utils.nodeExists(request, "service-instance-id")) {
317                                         serviceInstanceId = utils.getNodeText(request, "service-instance-id")
318                                 }
319                                 execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId)
320                                 rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId)
321                                 logDebug("serviceInstanceId: " + serviceInstanceId, isDebugLogEnabled)
322                                 //source
323                                 def source = ""
324                                 if (utils.nodeExists(request, "source")) {
325                                         source = utils.getNodeText(request, "source")
326                                 }
327                                 execution.setVariable("DCVFM_source", source)
328                                 rollbackData.put("VFMODULE", "source", source)
329                                 logDebug("source: " + source, isDebugLogEnabled)
330                                 //backoutOnFailure
331                                 NetworkUtils networkUtils = new NetworkUtils()
332                                 def backoutOnFailure = networkUtils.isRollbackEnabled(execution,request)
333                                 execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure)
334                                 logDebug("backoutOnFailure: " + backoutOnFailure, isDebugLogEnabled)
335                                 //isBaseVfModule
336                                 def isBaseVfModule = "false"
337                                 if (utils.nodeExists(request, "is-base-vf-module")) {
338                                         isBaseVfModule = utils.getNodeText(request, "is-base-vf-module")
339                                 }
340                                 execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule)
341                                 logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled)
342
343                                 //asdcServiceModelVersion
344                                 def asdcServiceModelVersion = ""
345                                 if (utils.nodeExists(request, "asdc-service-model-version")) {
346                                         asdcServiceModelVersion = utils.getNodeText(request, "asdc-service-model-version")
347                                 }
348                                 execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion)
349                                 logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled)
350
351                                 //personaModelId
352                                 def personaModelId = ""
353                                 if (utils.nodeExists(request, "persona-model-id")) {
354                                         personaModelId = utils.getNodeText(request, "persona-model-id")
355                                 }
356                                 execution.setVariable("DCVFM_personaModelId", personaModelId)
357                                 logDebug("personaModelId: " + personaModelId, isDebugLogEnabled)
358
359                                 //personaModelVersion
360                                 def personaModelVersion = ""
361                                 if (utils.nodeExists(request, "persona-model-version")) {
362                                         personaModelVersion = utils.getNodeText(request, "persona-model-version")
363                                 }
364                                 execution.setVariable("DCVFM_personaModelVersion", personaModelVersion)
365                                 logDebug("personaModelVersion: " + personaModelVersion, isDebugLogEnabled)
366
367                                 // Process the parameters
368
369                                                 String vnfParamsChildNodes = utils.getChildNodes(request, "vnf-params")
370                                                 if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){
371                                                                 utils.log("DEBUG", "Request contains NO VNF Params", isDebugLogEnabled)
372                                                 }else{
373                                                                 utils.log("DEBUG", "Request does contain VNF Params", isDebugLogEnabled)
374                                                                 execution.setVariable("DCVFM_vnfParamsExistFlag", true)
375
376                                                                 InputSource xmlSource = new InputSource(new StringReader(request));
377                                                                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
378                                                                 docFactory.setNamespaceAware(true)
379                                                                 DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
380                                                                 Document xml = docBuilder.parse(xmlSource)
381                                                                 //Get params, build map
382                                                                 Map<String, String> paramsMap = new HashMap<String, String>()
383                                                                 NodeList paramsList = xml.getElementsByTagNameNS("*", "param")
384
385                                                                 for (int z = 0; z < paramsList.getLength(); z++) {
386                                                                         Node node = paramsList.item(z)
387                                                                         String paramValue = node.getTextContent()
388                                                                         NamedNodeMap e = node.getAttributes()
389                                                                         String paramName = e.getNamedItem("name").getTextContent()
390                                                                         paramsMap.put(paramName, paramValue)
391                                                                 }
392                                                                 execution.setVariable("DCVFM_vnfParamsMap", paramsMap)
393                                                         }
394                         }
395
396                         //Get or Generate UUID
397                         String uuid = execution.getVariable("DCVFM_uuid")
398                         if(uuid == null){
399                                 uuid = UUID.randomUUID()
400                                 logDebug("Generated messageId (UUID) is: " + uuid, isDebugLogEnabled)
401                         }else{
402                                 logDebug("Found messageId (UUID) is: " + uuid, isDebugLogEnabled)
403                         }
404                         // Get sdncVersion, default to empty
405                         String sdncVersion = execution.getVariable("sdncVersion")
406                         if (sdncVersion == null) {
407                                 sdncVersion = ""
408                         }
409                         logDebug("sdncVersion: " + sdncVersion, isDebugLogEnabled)
410                         execution.setVariable("DCVFM_sdncVersion", sdncVersion)
411                         
412                         execution.setVariable("DCVFM_uuid", uuid)
413                         execution.setVariable("DCVFM_baseVfModuleId", "")
414                         execution.setVariable("DCVFM_baseVfModuleHeatStackId", "")
415                         execution.setVariable("DCVFM_heatStackId", "")
416                         execution.setVariable("DCVFM_contrailServiceInstanceFqdn", "")
417                         execution.setVariable("DCVFM_volumeGroupStackId", "")
418                         execution.setVariable("DCVFM_cloudRegionForVolume", "")
419                         execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", "")
420                         execution.setVariable("DCVFM_vnfTypeToQuery", "generic-vnf")
421                         rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "false")
422                         rollbackData.put("VFMODULE", "rollbackUpdateAAIVfModule", "false")
423                         rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "false")
424                         rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "false")
425                         rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "false")
426                         rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "false")
427                         rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "false")
428                         rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "false")
429
430                         String sdncCallbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback')
431                                 if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) {
432                                         def msg = 'Required variable \'URN_mso_workflow_sdncadapter_callback\' is missing'
433                                         logError(msg)
434                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
435                                 }
436                                 execution.setVariable("DCVFM_sdncCallbackUrl", sdncCallbackUrl)
437                                 utils.logAudit("SDNC Callback URL: " + sdncCallbackUrl)
438                             logDebug("SDNC Callback URL is: " + sdncCallbackUrl, isDebugLogEnabled)
439
440
441                         execution.setVariable("rollbackData", rollbackData)
442                 }catch(BpmnError b){
443                         throw b
444                 }catch(Exception e){
445                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!")
446                 }
447
448                 logDebug('Exited ' + method, isDebugLogEnabled)
449         }
450
451         /**
452          * Validates a workflow response.
453          * @param execution the execution
454          * @param responseVar the execution variable in which the response is stored
455          * @param responseCodeVar the execution variable in which the response code is stored
456          * @param errorResponseVar the execution variable in which the error response is stored
457          */
458         public void validateWorkflowResponse(Execution execution, String responseVar,
459                         String responseCodeVar, String errorResponseVar) {
460                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
461                 sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar)
462         }
463
464
465         /**
466          * Sends the empty, synchronous response back to the API Handler.
467          * @param execution the execution
468          */
469         public void sendResponse(Execution execution) {
470                 def method = getClass().getSimpleName() + '.sendResponse(' +
471                         'execution=' + execution.getId() +
472                         ')'
473                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
474                 logDebug('Entered ' + method, isDebugLogEnabled)
475
476                 try {
477                         sendWorkflowResponse(execution, 200, "")
478                         logDebug('Exited ' + method, isDebugLogEnabled)
479                 } catch (BpmnError e) {
480                         throw e;
481                 } catch (Exception e) {
482                         logError('Caught exception in ' + method, e)
483                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Internal Error')
484                 }
485         }
486
487         /**
488          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
489          * A 200 response is expected with the VNF info in the response body. Will find out the base module info
490          * and existing VNF's name for add-on modules
491          *
492          * @param execution The flow's execution instance.
493          */
494         public void postProcessCreateAAIVfModule(Execution execution) {
495                 def method = getClass().getSimpleName() + '.getVfModule(' +
496                         'execution=' + execution.getId() +
497                         ')'
498                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
499                 logDebug('Entered ' + method, isDebugLogEnabled)
500
501                 try {
502                         def createResponse = execution.getVariable('DCVFM_createVfModuleResponse')
503                         utils.logAudit("createVfModule Response: " + createResponse)
504
505                         def rollbackData = execution.getVariable("rollbackData")
506                         String vnfName = utils.getNodeText1(createResponse, 'vnf-name')
507                         if (vnfName != null) {
508                                 execution.setVariable('DCVFM_vnfName', vnfName)
509                                 logDebug("vnfName retrieved from AAI is: " + vnfName, isDebugLogEnabled)
510                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
511                         }
512                         String vnfId = utils.getNodeText1(createResponse, 'vnf-id')
513                         execution.setVariable('DCVFM_vnfId', vnfId)
514                         logDebug("vnfId is: " + vnfId, isDebugLogEnabled)
515                         String vfModuleId = utils.getNodeText1(createResponse, 'vf-module-id')
516                         execution.setVariable('DCVFM_vfModuleId', vfModuleId)
517                         logDebug("vfModuleId is: " + vfModuleId, isDebugLogEnabled)
518                         String vfModuleIndex= utils.getNodeText1(createResponse, 'vf-module-index')
519                         execution.setVariable('DCVFM_vfModuleIndex', vfModuleIndex)
520                         logDebug("vfModuleIndex is: " + vfModuleIndex, isDebugLogEnabled)
521                         rollbackData.put("VFMODULE", "vnfid", vnfId)
522                         rollbackData.put("VFMODULE", "vfmoduleid", vfModuleId)
523                         rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "true")
524                         rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "true")
525                         execution.setVariable("rollbackData", rollbackData)
526                 } catch (Exception ex) {
527                                 ex.printStackTrace()
528                                 logDebug('Exception occurred while postProcessing CreateAAIVfModule request:' + ex.getMessage(),isDebugLogEnabled)
529                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Bad response from CreateAAIVfModule' + ex.getMessage())
530                 }
531                 logDebug('Exited ' + method, isDebugLogEnabled)
532         }
533
534
535         /**
536          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
537          * A 200 response is expected with the VNF info in the response body. Will find out the base module info.
538          *
539          * @param execution The flow's execution instance.
540          */
541         public void queryAAIVfModule(Execution execution) {
542                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
543                 def method = getClass().getSimpleName() + '.getVfModule(' +
544                         'execution=' + execution.getId() +
545                         ')'
546                 logDebug('Entered ' + method, isDebugLogEnabled)
547
548                 try {
549                         def vnfId = execution.getVariable('DCVFM_vnfId')
550                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
551
552                         AaiUtil aaiUriUtil = new AaiUtil(this)
553                         String  aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
554                         logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled)
555
556                         String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1"
557                         utils.logAudit("AAI endPoint: " + endPoint)
558
559                         try {
560                                 RESTConfig config = new RESTConfig(endPoint);
561                                 def responseData = ''
562                                 def aaiRequestId = UUID.randomUUID().toString()
563                                 RESTClient client = new RESTClient(config).
564                                         addHeader('X-TransactionId', aaiRequestId).
565                                         addHeader('X-FromAppId', 'MSO').
566                                         addHeader('Content-Type', 'application/xml').
567                                         addHeader('Accept','application/xml');
568                                 logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled)
569                                 APIResponse response = client.httpGet()
570                                 utils.logAudit("createVfModule - invoking httpGet() to AAI")
571
572                                 responseData = response.getResponseBodyAsString()
573                                 if (responseData != null) {
574                                         logDebug("Received generic VNF data: " + responseData, isDebugLogEnabled)
575
576                                 }
577
578                                 utils.logAudit("createVfModule - queryAAIVfModule Response: " + responseData)
579                                 utils.logAudit("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode())
580
581                                 execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode())
582                                 execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData)
583                                 logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled)
584                                 logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled)
585                                 if (response.getStatusCode() == 200) {
586                                         // Parse the VNF record from A&AI to find base module info
587                                         logDebug('Parsing the VNF data to find base module info', isDebugLogEnabled)
588                                         if (responseData != null) {
589                                                 def vfModulesText = utils.getNodeXml(responseData, "vf-modules")
590                                                 def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
591                                                 def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
592                                                 int vfModulesSize = 0
593                                                 for (i in 0..vfModules.size()-1) {
594                                                         def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
595                                                         def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module")
596
597                                                         if (isBaseVfModule == "true") {
598                                                             String baseModuleId = utils.getNodeText1(vfModuleXml, "vf-module-id")
599                                                             execution.setVariable("DCVFM_baseVfModuleId", baseModuleId)
600                                                             logDebug('Received baseVfModuleId: ' + baseModuleId, isDebugLogEnabled)
601                                                             String baseModuleHeatStackId = utils.getNodeText1(vfModuleXml, "heat-stack-id")
602                                                             execution.setVariable("DCVFM_baseVfModuleHeatStackId", baseModuleHeatStackId)
603                                                             logDebug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId, isDebugLogEnabled)
604                                                         }
605                                                 }
606                                         }
607                                 }
608                         } catch (Exception ex) {
609                                 ex.printStackTrace()
610                                 logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled)
611                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
612                         }
613                         logDebug('Exited ' + method, isDebugLogEnabled)
614                 } catch (BpmnError e) {
615                         throw e;
616                 } catch (Exception e) {
617                         logError('Caught exception in ' + method, e)
618                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage())
619                 }
620         }
621
622
623         public void preProcessSDNCAssignRequest(Execution execution){
624                 def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled")
625                 execution.setVariable("prefix", Prefix)
626                 logDebug(" ======== STARTED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled)
627                 def vnfId = execution.getVariable("DCVFM_vnfId")
628                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
629                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
630                 logDebug("NEW VNF ID: " + vnfId, isDebugLogEnabled)
631                 utils.logAudit("NEW VNF ID: " + vnfId)
632
633                 try{
634
635                         //Build SDNC Request
636
637                         def svcInstId = ""
638                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
639                                 svcInstId = vfModuleId
640                         }
641                         else {
642                                 svcInstId = serviceInstanceId
643                         }
644
645                         String assignSDNCRequest = buildSDNCRequest(execution, svcInstId, "assign")
646
647                         assignSDNCRequest = utils.formatXml(assignSDNCRequest)
648                         execution.setVariable("DCVFM_assignSDNCRequest", assignSDNCRequest)
649                         logDebug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest, isDebugLogEnabled)
650                         utils.logAudit("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest)
651
652                 }catch(Exception e){
653                         utils.log("ERROR", "Exception Occured Processing preProcessSDNCAssignRequest. Exception is:\n" + e, isDebugLogEnabled)
654                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage())
655                 }
656                 logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled)
657         }
658
659         public void preProcessSDNCGetRequest(Execution execution, String element){
660                 def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled")
661                 String sdncVersion = execution.getVariable("DCVFM_sdncVersion")
662                 execution.setVariable("prefix", Prefix)
663                 utils.log("DEBUG", " ======== STARTED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled)
664                 try{
665                         def serviceInstanceId = execution.getVariable('DCVFM_serviceInstanceId')
666                         
667                         String uuid = execution.getVariable('testReqId') // for junits
668                         if(uuid==null){
669                                 uuid = execution.getVariable("mso-request-id") + "-" +  System.currentTimeMillis()
670                         }
671                                         
672                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
673                         utils.logAudit("callbackUrl:" + callbackUrl)
674                         
675                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
676                         
677                         def svcInstId = ""
678                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
679                                 svcInstId = vfModuleId
680                         }
681                         else {
682                                 svcInstId = serviceInstanceId
683                         }
684                         
685                         def msoAction = ""
686                         if (!sdncVersion.equals("1707")) {
687                                 msoAction = "mobility"
688                         }
689                         else {
690                                 msoAction = "vfmodule"
691                         }
692                         // For VNF, serviceOperation (URI for topology GET) will be retrieved from "selflink" element 
693                         // in the response from GenericGetVnf
694                         // For VF Module, in 1707 serviceOperation will be retrieved from "object-path" element
695                         // in SDNC Assign Response
696                         // For VF Module for older versions, serviceOperation is constructed using vfModuleId
697                         
698                         String serviceOperation = ""
699                         if (element.equals("vnf")) {
700                                 def vnfQueryResponse = execution.getVariable("DCVFM_vnfQueryResponse")
701                                 serviceOperation = utils.getNodeText1(vnfQueryResponse, "selflink")
702                                 utils.log("DEBUG", "VNF - service operation: " + serviceOperation, isDebugLogEnabled)
703                         }
704                         else if (element.equals("vfmodule")) {
705                                 String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
706                                 utils.logAudit("DCVFM_assignSDNCAdapterResponse is: \n" + response)                                                     
707                         
708                                 if (!sdncVersion.equals("1707")) {
709                                         serviceOperation = "/VNF-API:vnfs/vnf-list/" + vfModuleId
710                                         utils.log("DEBUG", "VF Module with sdncVersion before 1707 - service operation: " + serviceOperation, isDebugLogEnabled)
711                                 }
712                                 else {                          
713                                         String data = utils.getNodeXml(response, "response-data")                                       
714                                         data = data.replaceAll("&lt;", "<")
715                                         data = data.replaceAll("&gt;", ">")
716                                         utils.log("DEBUG", "responseData: " + data, isDebugLogEnabled)
717                                         serviceOperation = utils.getNodeText1(data, "object-path")
718                                         utils.log("DEBUG", "VF Module with sdncVersion of 1707 - service operation: " + serviceOperation, isDebugLogEnabled)
719                                 }                               
720                         }               
721
722                         //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE
723                         sleep(5000)
724
725                         String SDNCGetRequest =
726                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
727                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
728                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
729                                         <sdncadapter:RequestHeader>
730                                         <sdncadapter:RequestId>${uuid}</sdncadapter:RequestId>
731                                         <sdncadapter:SvcInstanceId>${svcInstId}</sdncadapter:SvcInstanceId>
732                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
733                                         <sdncadapter:SvcOperation>${serviceOperation}</sdncadapter:SvcOperation>
734                                         <sdncadapter:CallbackUrl>${callbackUrl}</sdncadapter:CallbackUrl>
735                                         <sdncadapter:MsoAction>${msoAction}</sdncadapter:MsoAction>
736                                 </sdncadapter:RequestHeader>
737                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
738                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
739
740                         utils.logAudit("SDNCGetRequest: \n" + SDNCGetRequest)
741                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
742                         utils.log("DEBUG", "Outgoing GetSDNCRequest is: \n" + SDNCGetRequest, isDebugLogEnabled)
743
744                 }catch(Exception e){
745                         utils.log("ERROR", "Exception Occurred Processing preProcessSDNCGetRequest. Exception is:\n" + e, isDebugLogEnabled)
746                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
747                 }
748                 utils.log("DEBUG", "======== COMPLETED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled)
749         }
750
751
752         public void preProcessVNFAdapterRequest(Execution execution) {
753                 def method = getClass().getSimpleName() + '.VNFAdapterCreateVfModule(' +
754                         'execution=' + execution.getId() +
755                         ')'
756                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
757                 logDebug('Entered ' + method, isDebugLogEnabled)
758
759                 //def xml = execution.getVariable("DoCreateVfModuleRequest")
760                 //logDebug('VNF REQUEST is: ' + xml, isDebugLogEnabled)
761
762                 //Get variables
763                 //cloudSiteId
764                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
765                 //tenantId
766                 def tenantId = execution.getVariable("DCVFM_tenantId")
767                 //vnfType
768                 def vnfType = execution.getVariable("DCVFM_vnfType")
769                 //vnfName
770                 def vnfName = execution.getVariable("DCVFM_vnfName")
771                 //vnfId
772                 def vnfId = execution.getVariable("DCVFM_vnfId")
773                 //vfModuleName
774                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
775                 //vfModuleModelName
776                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
777                 //vfModuleId
778                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
779                 //vfModuleIndex
780                 def vfModuleIndex = execution.getVariable("DCVFM_vfModuleIndex")
781                 //requestId
782                 def requestId = execution.getVariable("DCVFM_requestId")
783                 //serviceId
784                 def serviceId = execution.getVariable("DCVFM_serviceId")
785                 //serviceInstanceId
786                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
787                 //backoutOnFailure
788                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
789                 //volumeGroupId
790                 def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
791                 // baseVfModuleId
792                 def baseVfModuleId = execution.getVariable("DCVFM_baseVfModuleId")
793                 // baseVfModuleStackId
794                 def baseVfModuleStackId = execution.getVariable("DCVFM_baseVfModuleHeatStackId")
795                 // asdcServiceModelVersion
796                 def asdcServiceModelVersion = execution.getVariable("DCVFM_asdcServiceModelVersion")
797                 //volumeGroupStackId
798                 def volumeGroupStackId = execution.getVariable("DCVFM_volumeGroupStackId")
799                 //modelCustomizationUuid
800                 def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid")
801
802                 def messageId = execution.getVariable('mso-request-id') + '-' +
803                                 System.currentTimeMillis()
804
805                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
806                 def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host")
807
808                 utils.logAudit("notificationUrl: " + notificationUrl)
809                 utils.logAudit("QualifiedHostName: " + useQualifiedHostName)
810
811                 if ('true'.equals(useQualifiedHostName)) {
812                         notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
813                 }
814
815                 Map<String, String> vnfParamsMap = execution.getVariable("DCVFM_vnfParamsMap")
816                 String vfModuleParams = ""
817                 //Get SDNC Response Data for VF Module Topology
818                 String vfModuleSdncGetResponse = execution.getVariable('DCVFM_getSDNCAdapterResponse')
819                 utils.logAudit("sdncGetResponse: " + vfModuleSdncGetResponse)
820                 def sdncVersion = execution.getVariable("sdncVersion")
821                 
822                 if (!sdncVersion.equals("1707")) {
823                                                 
824                         vfModuleParams = buildVfModuleParams(vnfParamsMap, vfModuleSdncGetResponse, vnfId, vnfName,
825                                 vfModuleId, vfModuleName, vfModuleIndex)
826                 }
827                 else {
828                         //Get SDNC Response Data for Vnf Topology
829                         String vnfSdncGetResponse = execution.getVariable('DCVFM_getVnfSDNCAdapterResponse')
830                         utils.logAudit("vnfSdncGetResponse: " + vnfSdncGetResponse)
831                         
832                         vfModuleParams = buildVfModuleParamsFromCombinedTopologies(vnfParamsMap, vnfSdncGetResponse, vfModuleSdncGetResponse, vnfId, vnfName,
833                                 vfModuleId, vfModuleName, vfModuleIndex)                        
834                 }
835
836                 def svcInstId = ""
837                 if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
838                                 svcInstId = serviceId
839                 }
840                 else {
841                         svcInstId = serviceInstanceId
842                 }
843
844                 def createVnfARequest = """
845                 <createVfModuleRequest>
846                 <cloudSiteId>${cloudSiteId}</cloudSiteId>
847                 <tenantId>${tenantId}</tenantId>
848                 <vnfId>${vnfId}</vnfId>
849                 <vnfName>${vnfName}</vnfName>
850                 <vfModuleName>${vfModuleName}</vfModuleName>
851                 <vfModuleId>${vfModuleId}</vfModuleId>
852                 <vnfType>${vnfType}</vnfType>
853                 <vfModuleType>${vfModuleModelName}</vfModuleType>
854                 <vnfVersion>${asdcServiceModelVersion}</vnfVersion>
855                 <modelCustomizationUuid>${modelCustomizationUuid}</modelCustomizationUuid>
856                 <requestType></requestType>
857                 <volumeGroupId>${volumeGroupId}</volumeGroupId>
858         <volumeGroupStackId>${volumeGroupStackId}</volumeGroupStackId>
859         <baseVfModuleId>${baseVfModuleId}</baseVfModuleId>
860         <baseVfModuleStackId>${baseVfModuleStackId}</baseVfModuleStackId>
861         <skipAAI>true</skipAAI>
862         <backout>${backoutOnFailure}</backout>
863         <failIfExists>true</failIfExists>
864                 <vfModuleParams>
865                 ${vfModuleParams}
866                 </vfModuleParams>
867                 <msoRequest>
868                         <requestId>${requestId}</requestId>
869                         <serviceInstanceId>${svcInstId}</serviceInstanceId>
870                 </msoRequest>
871                 <messageId>${messageId}</messageId>
872                 <notificationUrl>${notificationUrl}</notificationUrl>
873                 </createVfModuleRequest>"""
874
875                 utils.logAudit("Create VfModule Request to VNF Adapter : " + createVnfARequest)
876                 logDebug("Create VfModule Request to VNF Adapter: " + createVnfARequest, isDebugLogEnabled)
877                 execution.setVariable("DCVFM_createVnfARequest", createVnfARequest)
878         }
879
880         /**
881          * Validates the request, request id and service instance id.  If a problem is found,
882          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
883          * method also sets up the log context for the workflow.
884          * @param execution the execution
885          * @return the validated request
886          */
887         public String validateInfraRequest(Execution execution) {
888                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
889                         'execution=' + execution.getId() +
890                         ')'
891                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
892                 logDebug('Entered ' + method, isDebugLogEnabled)
893
894                 String processKey = getProcessKey(execution);
895                 def prefix = execution.getVariable("prefix")
896
897                 if (prefix == null) {
898                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
899                 }
900
901                 try {
902                         def request = execution.getVariable(prefix + 'Request')
903
904                         if (request == null) {
905                                 request = execution.getVariable(processKey + 'Request')
906
907                                 if (request == null) {
908                                         request = execution.getVariable('bpmnRequest')
909                                 }
910
911                                 setVariable(execution, processKey + 'Request', null);
912                                 setVariable(execution, 'bpmnRequest', null);
913                                 setVariable(execution, prefix + 'Request', request);
914                         }
915
916                         if (request == null) {
917                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
918                         }
919                         utils.logAudit("DoCreateVfModule Request: " + request)
920
921                         /*
922
923                         def requestId = execution.getVariable("mso-request-id")
924
925                         if (requestId == null) {
926                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id")
927                         }
928
929                         def serviceInstanceId = execution.getVariable("mso-service-instance-id")
930
931                         if (serviceInstanceId == null) {
932                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id")
933                         }
934
935                         utils.logContext(requestId, serviceInstanceId)
936                         */
937                         logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled)
938                         logDebug('Exited ' + method, isDebugLogEnabled)
939                         return request
940                 } catch (BpmnError e) {
941                         throw e;
942                 } catch (Exception e) {
943                         logError('Caught exception in ' + method, e)
944                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
945                 }
946         }
947
948         public boolean isVolumeGroupIdPresent(Execution execution) {
949
950                 def method = getClass().getSimpleName() + '.isVolumeGroupIdPresent(' +
951                         'execution=' + execution.getId() +
952                         ')'
953                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
954                 logDebug('Entered ' + method, isDebugLogEnabled)
955
956                 def request = execution.getVariable('DoCreateVfModuleRequest')
957                 String volumeGroupId = utils.getNodeText1(request, "volume-group-id")
958                 if (volumeGroupId == null || volumeGroupId.isEmpty()) {
959                         logDebug('No volume group id is present', isDebugLogEnabled)
960                         return false
961                 }
962                 else {
963                         logDebug('Volume group id is present', isDebugLogEnabled)
964                         return true
965                 }
966
967         }
968
969         public boolean isVolumeGroupNamePresent(Execution execution) {
970
971                 def method = getClass().getSimpleName() + '.isVolumeGroupNamePresent(' +
972                         'execution=' + execution.getId() +
973                         ')'
974                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
975                 logDebug('Entered ' + method, isDebugLogEnabled)
976
977                 def request = execution.getVariable('DoCreateVfModuleRequest')
978                 String volumeGroupName = utils.getNodeText1(request, "volume-group-name")
979                 if (volumeGroupName == null || volumeGroupName.isEmpty()) {
980                         logDebug('No volume group name is present', isDebugLogEnabled)
981                         return false
982                 }
983                 else {
984                         logDebug('Volume group name is present', isDebugLogEnabled)
985                         return true
986                 }
987
988         }
989
990         public String buildSDNCRequest(Execution execution, String svcInstId, String action){
991
992                 String uuid = execution.getVariable('testReqId') // for junits
993                 if(uuid==null){
994                         uuid = execution.getVariable("mso-request-id") + "-" +          System.currentTimeMillis()
995                 }
996                 def callbackURL = execution.getVariable("DCVFM_sdncCallbackUrl")
997                 def requestId = execution.getVariable("DCVFM_requestId")
998                 def serviceId = execution.getVariable("DCVFM_serviceId")
999                 def vnfType = execution.getVariable("DCVFM_vnfType")
1000                 def vnfName = execution.getVariable("DCVFM_vnfName")
1001                 def tenantId = execution.getVariable("DCVFM_tenantId")
1002                 def source = execution.getVariable("DCVFM_source")
1003                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
1004                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1005                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
1006                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
1007                 def vnfId = execution.getVariable("DCVFM_vnfId")
1008                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
1009                 def sdncVersion = execution.getVariable("DCVFM_sdncVersion")
1010                 def serviceModelInfo = execution.getVariable("serviceModelInfo")
1011                 def vnfModelInfo = execution.getVariable("vnfModelInfo")
1012                 def vfModuleModelInfo = execution.getVariable("vfModuleModelInfo")
1013                 String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo)
1014                 String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo)
1015                 String vfModuleEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vfModuleModelInfo)
1016                 def globalSubscriberId = execution.getVariable("DCVFM_globalSubscriberId")
1017                 boolean usePreload = execution.getVariable("DCVFM_usePreload")
1018                 String usePreloadToSDNC = usePreload ? "Y" : "N"
1019                 def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid")
1020                 def modelCustomizationUuidString = ""
1021                 if (!usePreload) {
1022                         modelCustomizationUuidString = "<model-customization-uuid>" + modelCustomizationUuid + "</model-customization-uuid>"
1023                 }
1024
1025                 String sdncVNFParamsXml = ""
1026
1027                 if(execution.getVariable("DCVFM_vnfParamsExistFlag") == true){
1028                         sdncVNFParamsXml = buildSDNCParamsXml(execution)
1029                 }else{
1030                         sdncVNFParamsXml = ""
1031                 }
1032                 
1033                 String sdncRequest = ""
1034                 
1035                 if (!sdncVersion.equals("1707")) {
1036
1037                         sdncRequest =
1038                 """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
1039                                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
1040                                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
1041            <sdncadapter:RequestHeader>
1042                                 <sdncadapter:RequestId>${uuid}</sdncadapter:RequestId>
1043                                 <sdncadapter:SvcInstanceId>${svcInstId}</sdncadapter:SvcInstanceId>
1044                                 <sdncadapter:SvcAction>${action}</sdncadapter:SvcAction>
1045                                 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
1046                                 <sdncadapter:CallbackUrl>${callbackURL}</sdncadapter:CallbackUrl>
1047                 </sdncadapter:RequestHeader>
1048         <sdncadapterworkflow:SDNCRequestData>
1049                 <request-information>
1050                         <request-id>${requestId}</request-id>
1051                         <request-action>VNFActivateRequest</request-action>
1052                         <source>${source}</source>
1053                         <notification-url/>
1054                 </request-information>
1055                 <service-information>
1056                         <service-id>${serviceId}</service-id>
1057                         <service-type>${serviceId}</service-type>
1058                         <service-instance-id>${svcInstId}</service-instance-id>
1059                         <subscriber-name>notsurewecare</subscriber-name>
1060                 </service-information>
1061                 <vnf-request-information>
1062                         <vnf-id>${vfModuleId}</vnf-id>
1063                         <vnf-type>${vfModuleModelName}</vnf-type>
1064                         <vnf-name>${vfModuleName}</vnf-name>
1065                         <generic-vnf-id>${vnfId}</generic-vnf-id>
1066                         <generic-vnf-name>${vnfName}</generic-vnf-name>
1067                         <generic-vnf-type>${vnfType}</generic-vnf-type>
1068                         <aic-cloud-region>${cloudSiteId}</aic-cloud-region>
1069                         <tenant>${tenantId}</tenant>
1070                         ${modelCustomizationUuidString}
1071                         <use-preload>${usePreloadToSDNC}</use-preload>
1072                 ${sdncVNFParamsXml}
1073                 </vnf-request-information>
1074         </sdncadapterworkflow:SDNCRequestData>
1075         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1076                 
1077                 }
1078                 else {  
1079                         
1080                         sdncRequest =
1081                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
1082                                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
1083                                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
1084            <sdncadapter:RequestHeader>
1085                                 <sdncadapter:RequestId>${uuid}</sdncadapter:RequestId>
1086                                 <sdncadapter:SvcInstanceId>${svcInstId}</sdncadapter:SvcInstanceId>
1087                                 <sdncadapter:SvcAction>${action}</sdncadapter:SvcAction>
1088                                 <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation>
1089                                 <sdncadapter:CallbackUrl>${callbackURL}</sdncadapter:CallbackUrl>
1090                                 <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
1091                 </sdncadapter:RequestHeader>
1092         <sdncadapterworkflow:SDNCRequestData>
1093                 <request-information>
1094                         <request-id>${requestId}</request-id>
1095                         <request-action>CreateVfModuleInstance</request-action>
1096                         <source>${source}</source>
1097                         <notification-url/>
1098                 </request-information>
1099                 <service-information>
1100                         <service-id>${serviceId}</service-id>
1101                         <subscription-service-type>${serviceId}</subscription-service-type>
1102                         ${serviceEcompModelInformation}
1103                         <service-instance-id>${svcInstId}</service-instance-id>
1104                         <global-customer-id>${globalSubscriberId}</global-customer-id>                  
1105                 </service-information>          
1106                 <vnf-information>
1107                         <vnf-id>${vnfId}</vnf-id>
1108                         <vnf-type>${vnfType}</vnf-type>
1109                         ${vnfEcompModelInformation}                     
1110                 </vnf-information>
1111                 <vf-module-information>
1112                         <vf-module-id>${vfModuleId}</vf-module-id>
1113                         <vf-module-type>${vfModuleModelName}</vf-module-type>
1114                         ${vfModuleEcompModelInformation}                        
1115                 </vf-module-information>
1116                 <vf-module-request-input>                       
1117                         <vf-module-name>${vfModuleName}</vf-module-name>
1118                         <tenant>${tenantId}</tenant>
1119                         <aic-cloud-region>${cloudSiteId}</aic-cloud-region>                     
1120                 ${sdncVNFParamsXml}
1121                 </vf-module-request-input>
1122           </sdncadapterworkflow:SDNCRequestData>
1123         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1124                         
1125                         
1126                         /*
1127                         sdncRequest =
1128                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
1129                                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
1130                                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
1131            <sdncadapter:RequestHeader>
1132                                 <sdncadapter:RequestId>${requestId}</sdncadapter:RequestId>
1133                                 <sdncadapter:SvcInstanceId>${svcInstId}</sdncadapter:SvcInstanceId>
1134                                 <sdncadapter:SvcAction>${action}</sdncadapter:SvcAction>
1135                                 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
1136                                 <sdncadapter:CallbackUrl>${callbackURL}</sdncadapter:CallbackUrl>
1137                 </sdncadapter:RequestHeader>
1138         <sdncadapterworkflow:SDNCRequestData>
1139                 <request-information>
1140                         <request-id>${requestId}</request-id>
1141                         <request-action>CreateVfModuleInstance</request-action>
1142                         <source>${source}</source>
1143                         <notification-url/>
1144                 </request-information>
1145                 <service-information>
1146                         <service-id>${serviceId}</service-id>
1147                         <service-type>${serviceId}</service-type>
1148                         ${serviceEcompModelInformation}                 
1149                         <service-instance-id>${svcInstId}</service-instance-id>
1150                         <global-customer-id>${globalSubscriberId}</global-customer-id>
1151                 </service-information>
1152                 <vnf-information>
1153                         <vnf-id>${vnfId}</vnf-id>
1154                         <vnf-type>${vnfType}</vnf-type>
1155                         ${vnfEcompModelInformation}                     
1156                 </vnf-information>
1157                 <vf-module-information>
1158                         <vf-module-id>${vfModuleId}</vf-module-id>
1159                         <vf-module-type>${vfModuleModelName}</vf-module-type>
1160                         ${vfModuleEcompModelInformation}                        
1161                 </vf-module-information>
1162                 <vf-module-request-input>                       
1163                         <vf-module-name>${vfModuleName}</vf-module-name>
1164                         <tenant>${tenantId}</tenant>
1165                         <aic-cloud-region>${cloudSiteId}</aic-cloud-region>                             
1166                 ${sdncVNFParamsXml}
1167                 </vf-module-request-input>              
1168         </sdncadapterworkflow:SDNCRequestData>
1169         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1170                         */
1171                         
1172                 }
1173
1174         utils.logAudit("sdncRequest:  " + sdncRequest)
1175         return sdncRequest
1176
1177         }
1178
1179         public void preProcessSDNCActivateRequest(Execution execution) {
1180                 def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' +
1181                         'execution=' + execution.getId() +
1182                         ')'
1183                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1184                 logDebug('Entered ' + method, isDebugLogEnabled)
1185                 execution.setVariable("prefix", Prefix)
1186                 logDebug(" ======== STARTED preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled)
1187                 try{
1188                         String vnfId = execution.getVariable("DCVFM_vnfId")
1189                         String vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1190                         String serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
1191
1192                         def svcInstId = ""
1193                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
1194                                 svcInstId = vfModuleId
1195                         }
1196                         else {
1197                                 svcInstId = serviceInstanceId
1198                         }
1199                         String activateSDNCRequest = buildSDNCRequest(execution, svcInstId, "activate")
1200
1201                         execution.setVariable("DCVFM_activateSDNCRequest", activateSDNCRequest)
1202                         logDebug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest, isDebugLogEnabled)
1203                         utils.logAudit("Outgoing CommitSDNCRequest is: \n"  + activateSDNCRequest)
1204
1205                 }catch(Exception e){
1206                         log.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e, isDebugLogEnabled)
1207                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during  preProcessSDNCActivateRequest Method:\n" + e.getMessage())
1208                 }
1209                 logDebug("======== COMPLETED  preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled)
1210         }
1211
1212         public void postProcessVNFAdapterRequest(Execution execution) {
1213                 def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' +
1214                         'execution=' + execution.getId() +
1215                         ')'
1216                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1217                 logDebug('Entered ' + method, isDebugLogEnabled)
1218                 execution.setVariable("prefix",Prefix)
1219                 try{
1220                 logDebug(" *** STARTED postProcessVNFAdapterRequest Process*** ", isDebugLogEnabled)
1221
1222                 String vnfResponse = execution.getVariable("DCVFM_createVnfAResponse")
1223                 logDebug("VNF Adapter Response is: " + vnfResponse, isDebugLogEnabled)
1224                 utils.logAudit("createVnfAResponse is: \n"  + vnfResponse)
1225
1226                 RollbackData rollbackData = execution.getVariable("rollbackData")
1227                 if(vnfResponse != null){
1228
1229                         if(vnfResponse.contains("createVfModuleResponse")){
1230                                 logDebug("Received a Good Response from VNF Adapter for CREATE_VF_MODULE Call.", isDebugLogEnabled)
1231                                 execution.setVariable("DCVFM_vnfVfModuleCreateCompleted", true)
1232                                 String heatStackId = utils.getNodeText1(vnfResponse, "vfModuleStackId")
1233                                 execution.setVariable("DCVFM_heatStackId", heatStackId)
1234                                 logDebug("Received heat stack id from VNF Adapter: " + heatStackId, isDebugLogEnabled)
1235                                 rollbackData.put("VFMODULE", "heatstackid", heatStackId)
1236                                 // Parse vnfOutputs for network_fqdn
1237                                 if (vnfResponse.contains("vfModuleOutputs")) {
1238                                         def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs")
1239                                         InputSource source = new InputSource(new StringReader(vfModuleOutputsXml));
1240                         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
1241                         docFactory.setNamespaceAware(true)
1242                         DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
1243                         Document outputsXml = docBuilder.parse(source)
1244
1245                                         NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry")
1246                                         List contrailNetworkPolicyFqdnList = []
1247                                         for (int i = 0; i< entries.getLength(); i++) {
1248                                                 Node node = entries.item(i)
1249                                                 if (node.getNodeType() == Node.ELEMENT_NODE) {
1250                                                         Element element = (Element) node
1251                                                         String key = element.getElementsByTagNameNS("*", "key").item(0).getTextContent()
1252                                                         if (key.equals("contrail-service-instance-fqdn")) {
1253                                                                 String contrailServiceInstanceFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1254                                                                 logDebug("Obtained contrailServiceInstanceFqdn: " + contrailServiceInstanceFqdn, isDebugLogEnabled)
1255                                                                 execution.setVariable("DCVFM_contrailServiceInstanceFqdn", contrailServiceInstanceFqdn)
1256                                                         }
1257                                                         else if (key.endsWith("contrail_network_policy_fqdn")) {
1258                                                                 String contrailNetworkPolicyFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1259                                                                 logDebug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn, isDebugLogEnabled)
1260                                                                 contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn)
1261                                                         }
1262                                                         else if (key.equals("oam_management_v4_address")) {
1263                                                                 String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1264                                                                 logDebug("Obtained oamManagementV4Address: " + oamManagementV4Address, isDebugLogEnabled)
1265                                                                 execution.setVariable("DCVFM_oamManagementV4Address", oamManagementV4Address)
1266                                                         }
1267                                                         else if (key.equals("oam_management_v6_address")) {
1268                                                                 String oamManagementV6Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1269                                                                 logDebug("Obtained oamManagementV6Address: " + oamManagementV6Address, isDebugLogEnabled)
1270                                                                 execution.setVariable("DCVFM_oamManagementV6Address", oamManagementV6Address)
1271                                                         }
1272
1273                                                 }
1274                                         }
1275                                         if (!contrailNetworkPolicyFqdnList.isEmpty()) {
1276                                                 execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList)
1277                                         }
1278                                 }
1279                         }else{
1280                                 logDebug("Received a BAD Response from VNF Adapter for CREATE_VF_MODULE Call.", isDebugLogEnabled)
1281                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
1282                         }
1283                 }else{
1284                         logDebug("Response from VNF Adapter is Null for CREATE_VF_MODULE Call.", isDebugLogEnabled)
1285                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter")
1286                 }
1287
1288                 rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "true")
1289                 execution.setVariable("rollbackData", rollbackData)
1290
1291                 }catch(BpmnError b){
1292                         throw b
1293                 }catch(Exception e){
1294                         logDebug("Internal Error Occured in PostProcess Method", isDebugLogEnabled)
1295                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method")
1296                 }
1297                 logDebug(" *** COMPLETED postProcessVnfAdapterResponse Process*** ", isDebugLogEnabled)
1298         }
1299
1300
1301         public void preProcessUpdateAAIVfModuleRequestOrch(Execution execution) {
1302                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestOrch(' +
1303                         'execution=' + execution.getId() +
1304                         ')'
1305                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1306                 logDebug('Entered ' + method, isDebugLogEnabled)
1307                 execution.setVariable("prefix", Prefix)
1308                 logDebug(" ======== STARTED preProcessUpdateAAIVfModuleRequestOrch ======== ", isDebugLogEnabled)
1309
1310                 try{
1311
1312                         //Build UpdateAAIVfModule Request
1313                         boolean setContrailServiceInstanceFqdn = false
1314                         def contrailServiceInstanceFqdn = execution.getVariable("DCVFM_contrailServiceInstanceFqdn")
1315                         if (!contrailServiceInstanceFqdn.equals("")) {
1316                                 setContrailServiceInstanceFqdn = true
1317                         }
1318
1319                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, false, true, true, setContrailServiceInstanceFqdn)
1320
1321                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1322                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1323                         logDebug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest, isDebugLogEnabled)
1324                         utils.logAudit("Outgoing UpdateAAIVfModuleRequest is: \n"  + updateAAIVfModuleRequest)
1325
1326                 }catch(Exception e){
1327                         utils.log("ERROR", "Exception Occured Processing preProcessUpdateAAIVfModuleRequestOrch. Exception is:\n" + e, isDebugLogEnabled)
1328                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestOrch Method:\n" + e.getMessage())
1329                 }
1330                 logDebug("======== COMPLETED preProcessUpdateAAIVfModuleRequestOrch ======== ", isDebugLogEnabled)
1331
1332         }
1333
1334         public void preProcessUpdateAAIVfModuleRequestGroup(Execution execution) {
1335                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestGroup(' +
1336                         'execution=' + execution.getId() +
1337                         ')'
1338                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1339                 logDebug('Entered ' + method, isDebugLogEnabled)
1340                 execution.setVariable("prefix", Prefix)
1341                 logDebug(" ======== STARTED preProcessUpdateAAIVfModuleRequestGroup ======== ", isDebugLogEnabled)
1342
1343                 try{
1344
1345                         //Build UpdateAAIVfModule Request
1346
1347                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, true, false, false, false)
1348
1349                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1350                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1351                         logDebug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest, isDebugLogEnabled)
1352                         utils.logAudit("Outgoing UpdateAAIVfModuleRequest is: \n"  + updateAAIVfModuleRequest)
1353
1354                 }catch(Exception e){
1355                         utils.log("ERROR", "Exception Occured Processing preProcessUpdateAAIVfModuleRequestGroup. Exception is:\n" + e, isDebugLogEnabled)
1356                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestGroup Method:\n" + e.getMessage())
1357                 }
1358                 logDebug("======== COMPLETED  preProcessUpdateAAIVfModuleRequestGroup ======== ", isDebugLogEnabled)
1359
1360         }
1361
1362         public void validateSDNCResponse(Execution execution, String response, String method){
1363                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
1364                 execution.setVariable("prefix",Prefix)
1365                 logDebug(" *** STARTED ValidateSDNCResponse Process*** ", isDebugLogEnabled)
1366
1367                 WorkflowException workflowException = execution.getVariable("WorkflowException")
1368                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
1369
1370                 utils.logAudit("workflowException: " + workflowException)
1371
1372                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
1373                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
1374
1375                 utils.logAudit("SDNCResponse: " + response)
1376
1377                 String sdncResponse = response
1378                 if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
1379                         logDebug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse, isDebugLogEnabled)
1380                         RollbackData rollbackData = execution.getVariable("rollbackData")
1381
1382                         if(method.equals("assign")){
1383                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "true")
1384                                 execution.setVariable("CRTGVNF_sdncAssignCompleted", true)
1385                         }
1386                         else if (method.equals("activate")) {
1387                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "true")
1388                         }
1389                         execution.setVariable("rollbackData", rollbackData)
1390                 }else{
1391                         logDebug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.", isDebugLogEnabled)
1392                         throw new BpmnError("MSOWorkflowException")
1393                 }
1394                 logDebug(" *** COMPLETED ValidateSDNCResponse Process*** ", isDebugLogEnabled)
1395         }
1396
1397         public void preProcessUpdateAfterCreateRequest(Execution execution){
1398                 def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled")
1399                 execution.setVariable("prefix", Prefix)
1400                 utils.log("DEBUG", " ======== STARTED preProcessRequest Process ======== ", isDebugLogEnabled)
1401                 try{
1402                         String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
1403                         utils.logAudit("DCVFM_assignSDNCAdapterResponse: " + response)
1404
1405                         String data = utils.getNodeXml(response, "response-data")
1406                         data = data.replaceAll("&lt;", "<")
1407                         data = data.replaceAll("&gt;", ">")
1408                         String vnfId = utils.getNodeText1(data, "vnf-id")
1409
1410                         String uuid = execution.getVariable('testReqId') // for junits
1411                         if(uuid==null){
1412                                 uuid = execution.getVariable("mso-request-id") + "-" +          System.currentTimeMillis()
1413                         }
1414
1415                         String serviceOperation = "/VNF-API:vnfs/vnf-list/" + vnfId
1416                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
1417                         utils.logAudit("callbackUrl: " + callbackUrl)
1418
1419                         String SDNCGetRequest =
1420                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
1421                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
1422                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
1423                                         <sdncadapter:RequestHeader>
1424                                         <sdncadapter:RequestId>${uuid}</sdncadapter:RequestId>
1425                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
1426                                         <sdncadapter:SvcOperation>${serviceOperation}</sdncadapter:SvcOperation>
1427                                         <sdncadapter:CallbackUrl>${callbackUrl}</sdncadapter:CallbackUrl>
1428                                         <sdncadapter:MsoAction>mobility</sdncadapter:MsoAction>
1429                                 </sdncadapter:RequestHeader>
1430                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
1431                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1432
1433                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
1434                         utils.log("DEBUG", "Outgoing GetSDNCRequest is: \n" + SDNCGetRequest, isDebugLogEnabled)
1435                         utils.logAudit("Outgoing GetSDNCRequest: " + SDNCGetRequest)
1436
1437                 }catch(Exception e){
1438                         utils.log("ERROR", "Exception Occured Processing preProcessSDNCGetRequest. Exception is:\n" + e, isDebugLogEnabled)
1439                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
1440                 }
1441                 utils.log("DEBUG", "======== COMPLETED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled)
1442         }
1443
1444         public String buildUpdateAAIVfModuleRequest(Execution execution, boolean updateVolumeGroupId,
1445                 boolean updateOrchestrationStatus, boolean updateHeatStackId, boolean updateContrailFqdn){
1446
1447                 def vnfId = execution.getVariable("DCVFM_vnfId")
1448                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1449                 def volumeGroupIdString = ""
1450                 if (updateVolumeGroupId) {
1451                         volumeGroupIdString = "<volume-group-id>" + execution.getVariable("DCVFM_volumeGroupId") +
1452                                         "</volume-group-id>"
1453                 }
1454                 def orchestrationStatusString = ""
1455                 if (updateOrchestrationStatus) {
1456                         orchestrationStatusString = "<orchestration-status>Created</orchestration-status>"
1457                 }
1458                 def heatStackIdString = ""
1459                 if (updateHeatStackId) {
1460                         heatStackIdString = "<heat-stack-id>" + execution.getVariable("DCVFM_heatStackId") + "</heat-stack-id>"
1461                 }
1462                 def contrailFqdnString = ""
1463                 if (updateContrailFqdn) {
1464                         contrailFqdnString = "<contrail-service-instance-fqdn>" + execution.getVariable("DCVFM_contrailServiceInstanceFqdn") +
1465                                 "</contrail-service-instance-fqdn>"
1466                 }
1467
1468                 String updateAAIVfModuleRequest =
1469                         """<UpdateAAIVfModuleRequest>
1470                                 <vnf-id>${vnfId}</vnf-id>
1471                                 <vf-module-id>${vfModuleId}</vf-module-id>
1472                                 ${heatStackIdString}
1473                                 ${orchestrationStatusString}
1474                                 ${volumeGroupIdString}
1475                                 ${contrailFqdnString}
1476                         </UpdateAAIVfModuleRequest>"""
1477
1478         utils.logAudit("updateAAIVfModule Request: " + updateAAIVfModuleRequest)
1479         return updateAAIVfModuleRequest
1480
1481         }
1482
1483         public String buildSDNCParamsXml(Execution execution){
1484
1485                 String params = ""
1486                 StringBuilder sb = new StringBuilder()
1487                 Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
1488
1489                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
1490                         String paramsXml
1491                         String key = entry.getKey();
1492                         if(key.endsWith("_network")){
1493                                 String requestKey = key.substring(0, key.indexOf("_network"))
1494                                 String requestValue = entry.getValue()
1495                                 paramsXml =
1496 """<vnf-networks>
1497         <network-role>{ functx:substring-before-match(data($param/@name), '_network') }</network-role>
1498         <network-name>{ $param/text() }</network-name>
1499 </vnf-networks>"""
1500                         }else{
1501                         paramsXml = ""
1502                         }
1503                         params = sb.append(paramsXml)
1504                 }
1505                 return params
1506         }
1507
1508    public void queryCloudRegion (Execution execution) {
1509                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
1510                 execution.setVariable("prefix", Prefix)
1511                 utils.log("DEBUG", " ======== STARTED queryCloudRegion ======== ", isDebugLogEnabled)
1512
1513                 try {
1514                         String cloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1515
1516                         // Prepare AA&I url
1517                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
1518                         AaiUtil aaiUtil = new AaiUtil(this)
1519                         String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution)
1520                         String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion
1521                         utils.logAudit("CloudRegion Request: " + queryCloudRegionRequest)
1522
1523                         execution.setVariable("DCVFM_queryCloudRegionRequest", queryCloudRegionRequest)
1524                         utils.log("DEBUG", "DCVFM_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest, isDebugLogEnabled)
1525
1526                         cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion)
1527
1528                         if ((cloudRegion != "ERROR")) {
1529                                 if(execution.getVariable("DCVFM_queryCloudRegionReturnCode") == "404"){
1530                                         execution.setVariable("DCVFM_cloudRegionForVolume", "AAIAIC25")
1531                                 }else{
1532                                 execution.setVariable("DCVFM_cloudRegionForVolume", cloudRegion)
1533                                 }
1534                                 execution.setVariable("DCVFM_isCloudRegionGood", true)
1535                         } else {
1536                                 String errorMessage = "AAI Query Cloud Region Unsuccessful. AAI Response Code: " + execution.getVariable("DCVFM_queryCloudRegionReturnCode")
1537                                 utils.log("DEBUG", errorMessage, isDebugLogEnabled)
1538                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1539                                 execution.setVariable("DCVFM_isCloudRegionGood", false)
1540                         }
1541                         utils.log("DEBUG", " is Cloud Region Good: " + execution.getVariable("DCVFM_isCloudRegionGood"), isDebugLogEnabled)
1542
1543                 } catch(BpmnError b){
1544                         utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugLogEnabled)
1545                         throw b
1546                 }catch (Exception ex) {
1547                         // try error
1548                         String errorMessage = "Bpmn error encountered in CreateVfModule flow. Unexpected Response from AAI - " + ex.getMessage()
1549                         utils.log("ERROR", " AAI Query Cloud Region Failed.  Exception - " + "\n" + errorMessage, isDebugLogEnabled)
1550                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during queryCloudRegion method")
1551                 }
1552         }
1553
1554    /**
1555     *
1556     *This method occurs when an MSOWorkflowException is caught.  It logs the
1557     *variables and ensures that the "WorkflowException" Variable is set.
1558     *
1559     */
1560    public void processBPMNException(Execution execution){
1561            def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1562            execution.setVariable("prefix",Prefix)
1563            try{
1564                    utils.log("DEBUG", "Caught a BPMN Exception", isDebugEnabled)
1565                    utils.log("DEBUG", "Started processBPMNException Method", isDebugEnabled)
1566                    utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled)
1567                    if(execution.getVariable("WorkflowException") == null){
1568                            exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during DoCreateVfModule Sub Process")
1569                    }
1570
1571            }catch(Exception e){
1572                    utils.log("DEBUG", "Caught Exception during processBPMNException Method: " + e, isDebugEnabled)
1573            }
1574            utils.log("DEBUG", "Completed processBPMNException Method", isDebugEnabled)
1575    }
1576
1577    public void prepareCreateAAIVfModuleVolumeGroupRequest(Execution execution) {
1578                 def method = getClass().getSimpleName() + '.prepareCreateAAIVfModuleVolumeGroupRequest(' +
1579                         'execution=' + execution.getId() +
1580                         ')'
1581                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1582                 logDebug('Entered ' + method, isDebugLogEnabled)
1583                 execution.setVariable("prefix", Prefix)
1584                 logDebug(" ======== STARTED prepareCreateAAIVfModuleVolumeGroupRequest ======== ", isDebugLogEnabled)
1585
1586                 try{
1587
1588                         //Build CreateAAIVfModuleVolumeGroup Request
1589
1590                         def vnfId = execution.getVariable("DCVFM_vnfId")
1591                         def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1592                         def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
1593                         //def aicCloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1594                         def aicCloudRegion = execution.getVariable("DCVFM_cloudRegionForVolume")
1595                         String createAAIVfModuleVolumeGroupRequest =
1596                         """<CreateAAIVfModuleVolumeGroupRequest>
1597                                 <vnf-id>${vnfId}</vnf-id>
1598                                 <vf-module-id>${vfModuleId}</vf-module-id>
1599                                 <volume-group-id>${volumeGroupId}</volume-group-id>
1600                                 <aic-cloud-region>${aicCloudRegion}</aic-cloud-region>
1601                         </CreateAAIVfModuleVolumeGroupRequest>"""
1602
1603                         createAAIVfModuleVolumeGroupRequest = utils.formatXml(createAAIVfModuleVolumeGroupRequest)
1604                         execution.setVariable("DCVFM_createAAIVfModuleVolumeGroupRequest", createAAIVfModuleVolumeGroupRequest)
1605                         logDebug("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n" + createAAIVfModuleVolumeGroupRequest, isDebugLogEnabled)
1606                         utils.logAudit("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n"  + createAAIVfModuleVolumeGroupRequest)
1607
1608                 }catch(Exception e){
1609                         utils.log("ERROR", "Exception Occured Processing prepareCreateAAIVfModuleVolumeGroupRequest. Exception is:\n" + e, isDebugLogEnabled)
1610                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareCreateAAIVfModuleVolumeGroupRequest Method:\n" + e.getMessage())
1611                 }
1612                 logDebug("======== COMPLETED  prepareCreateAAIVfModuleVolumeGroupRequest ======== ", isDebugLogEnabled)
1613
1614         }
1615
1616    public void createNetworkPoliciesInAAI(Execution execution) {
1617            def method = getClass().getSimpleName() + '.createNetworkPoliciesInAAI(' +
1618            'execution=' + execution.getId() +
1619            ')'
1620            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1621            logDebug('Entered ' + method, isDebugLogEnabled)
1622            execution.setVariable("prefix", Prefix)
1623            logDebug(" ======== STARTED createNetworkPoliciesInAAI ======== ", isDebugLogEnabled)
1624
1625            try {
1626                    // get variables
1627                    List fqdnList = execution.getVariable("DCVFM_contrailNetworkPolicyFqdnList")
1628                    int fqdnCount = fqdnList.size()
1629                    def rollbackData = execution.getVariable("rollbackData")
1630
1631                    execution.setVariable("DCVFM_networkPolicyFqdnCount", fqdnCount)
1632                    logDebug("DCVFM_networkPolicyFqdnCount - " + fqdnCount, isDebugLogEnabled)
1633
1634                    String aai_endpoint = execution.getVariable("URN_aai_endpoint")
1635                    AaiUtil aaiUriUtil = new AaiUtil(this)
1636                    String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution)
1637
1638                    if (fqdnCount > 0) {
1639
1640                            // AII loop call over contrail network policy fqdn list
1641                            for (i in 0..fqdnCount-1) {
1642
1643                                    int counting = i+1
1644                                    String fqdn = fqdnList[i]
1645
1646                                    // Query AAI for this network policy FQDN
1647
1648                                    String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8")
1649                                    utils.logAudit("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest)
1650
1651                                    def aaiRequestId = UUID.randomUUID().toString()
1652                                    RESTConfig config = new RESTConfig(queryNetworkPolicyByFqdnAAIRequest);
1653                                    RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId)
1654                                                                                                                          .addHeader("X-FromAppId", "MSO")
1655                                                                                                                          .addHeader("Content-Type", "application/xml")
1656                                                                                                                          .addHeader("Accept","application/xml");
1657                                    APIResponse response = client.get()
1658                                    int returnCode = response.getStatusCode()
1659                                    execution.setVariable("DCVFM_aaiQqueryNetworkPolicyByFqdnReturnCode", returnCode)
1660                                    logDebug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode, isDebugLogEnabled)
1661
1662                                    String aaiResponseAsString = response.getResponseBodyAsString()
1663
1664                                    if (isOneOf(returnCode, 200, 201)) {
1665                                            logDebug("The return code is: "  + returnCode, isDebugLogEnabled)
1666                                            // This network policy FQDN already exists in AAI
1667                                            utils.logAudit(aaiResponseAsString)
1668                                            execution.setVariable("DCVFM_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString)
1669                                            logDebug(" QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString, isDebugLogEnabled)
1670
1671                                    } else {
1672                                            if (returnCode == 404) {
1673                                                    // This network policy FQDN is not in AAI yet. Add it now
1674                                                    logDebug("The return code is: "  + returnCode, isDebugLogEnabled)
1675                                                    logDebug("This network policy FQDN is not in AAI yet: " + fqdn, isDebugLogEnabled)
1676                                                    utils.logAudit("Network policy FQDN is not in AAI yet")
1677                                                    // Add the network policy with this FQDN to AAI
1678                                                    def networkPolicyId = UUID.randomUUID().toString()
1679                                                    logDebug("Adding network-policy with network-policy-id " + networkPolicyId, isDebugLogEnabled)
1680
1681                                                    String aaiNamespace = aaiUriUtil.getNamespaceFromUri(execution, aai_uri)
1682                                                    logDebug('AAI namespace is: ' + aaiNamespace, isDebugLogEnabled)
1683                                                    String payload = """<network-policy xmlns="${aaiNamespace}">
1684                                                                 <network-policy-id>${networkPolicyId}</network-policy-id>
1685                                                                 <network-policy-fqdn>${fqdn}</network-policy-fqdn>
1686                                                                 <heat-stack-id>${execution.getVariable("DCVFM_heatStackId")}</heat-stack-id>
1687                                                                 </network-policy>""" as String
1688
1689                                                    execution.setVariable("DCVFM_addNetworkPolicyAAIRequestBody", payload)
1690
1691                                                    String addNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8")
1692                                                    utils.logAudit("AAI request endpoint: " + addNetworkPolicyAAIRequest)
1693                                                    logDebug("AAI request endpoint: " + addNetworkPolicyAAIRequest, isDebugLogEnabled)
1694
1695                                                    def aaiRequestIdPut = UUID.randomUUID().toString()
1696                                                    RESTConfig configPut = new RESTConfig(addNetworkPolicyAAIRequest);
1697                                                    RESTClient clientPut = new RESTClient(configPut).addHeader("X-TransactionId", aaiRequestIdPut)
1698                                                                                                                                          .addHeader("X-FromAppId", "MSO")
1699                                                                                                                                          .addHeader("Content-Type", "application/xml")
1700                                                                                                                                          .addHeader("Accept","application/xml");
1701                                                    logDebug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload, isDebugLogEnabled)
1702                                                    utils.logAudit("Sending PUT call to AAI with Endpoint /n" + addNetworkPolicyAAIRequest + " with payload /n" + payload)
1703                                                    APIResponse responsePut = clientPut.httpPut(payload)
1704                                                    int returnCodePut = responsePut.getStatusCode()
1705                                                    execution.setVariable("DCVFM_aaiAddNetworkPolicyReturnCode", returnCodePut)
1706                                                    logDebug(" ***** AAI add network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodePut, isDebugLogEnabled)
1707
1708                                                    String aaiResponseAsStringPut = responsePut.getResponseBodyAsString()
1709                                                    if (isOneOf(returnCodePut, 200, 201)) {
1710                                                            logDebug("The return code from adding network policy is: "  + returnCodePut, isDebugLogEnabled)
1711                                                            // This network policy was created in AAI successfully
1712                                                            utils.logAudit(aaiResponseAsStringPut)
1713                                                            execution.setVariable("DCVFM_addNetworkPolicyAAIResponse", aaiResponseAsStringPut)
1714                                                            logDebug(" AddAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsStringPut, isDebugLogEnabled)
1715                                                            rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true")
1716                                                            rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn)
1717                                                            execution.setVariable("rollbackData", rollbackData)
1718
1719                                                    } else {
1720                                                                 // aai all errors
1721                                                                 String putErrorMessage = "Unable to add network-policy to AAI createNetworkPoliciesInAAI - " + returnCodePut
1722                                                                 logDebug(putErrorMessage, isDebugLogEnabled)
1723                                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, putErrorMessage)
1724                                                    }
1725
1726                                            } else {
1727                                                   if (aaiResponseAsString.contains("RESTFault")) {
1728                                                           WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
1729                                                           execution.setVariable("WorkflowException", exceptionObject)
1730                                                           throw new BpmnError("MSOWorkflowException")
1731
1732                                                           } else {
1733                                                                    // aai all errors
1734                                                                    String dataErrorMessage = "Unexpected Response from createNetworkPoliciesInAAI - " + returnCode
1735                                                                    logDebug(dataErrorMessage, isDebugLogEnabled)
1736                                                                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
1737
1738                                                          }
1739                                            }
1740                                    }
1741
1742                            } // end loop
1743
1744
1745                    } else {
1746                            logDebug("No contrail network policies to query/create", isDebugLogEnabled)
1747
1748                    }
1749
1750            } catch (BpmnError e) {
1751                    throw e;
1752
1753            } catch (Exception ex) {
1754                    String exceptionMessage = "Bpmn error encountered in DoCreateVfModule flow. createNetworkPoliciesInAAI() - " + ex.getMessage()
1755                    logDebug(exceptionMessage, isDebugLogEnabled)
1756                    exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1757            }
1758
1759    }
1760
1761    /**
1762         * Prepare a Request for invoking the UpdateAAIGenericVnf subflow.
1763         *
1764         * @param execution The flow's execution instance.
1765         */
1766    public void prepUpdateAAIGenericVnf(Execution execution) {
1767            def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' +
1768                    'execution=' + execution.getId() +
1769                    ')'
1770            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1771            logDebug('Entered ' + method, isDebugLogEnabled)
1772
1773            try {
1774                    def rollbackData = execution.getVariable("rollbackData")
1775                    def vnfId = execution.getVariable('DCVFM_vnfId')
1776                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
1777                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
1778                    def ipv4OamAddressElement = ''
1779                    def managementV6AddressElement = ''
1780
1781                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {
1782                            ipv4OamAddressElement = '<ipv4-oam-address>' + oamManagementV4Address + '</ipv4-oam-address>'
1783                    }
1784
1785                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
1786                            managementV6AddressElement = '<management-v6-address>' + oamManagementV6Address + '</management-v6-address>'
1787                    }
1788
1789                    rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
1790
1791
1792                    String updateAAIGenericVnfRequest = """
1793                                         <UpdateAAIGenericVnfRequest>
1794                                                 <vnf-id>${vnfId}</vnf-id>
1795                                                 ${ipv4OamAddressElement}
1796                                                 ${managementV6AddressElement}
1797                                         </UpdateAAIGenericVnfRequest>
1798                                 """
1799                            updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest)
1800                            execution.setVariable('DCVM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest)
1801                            utils.logAudit("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest)
1802                            logDebug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest, isDebugLogEnabled)
1803
1804
1805                    logDebug('Exited ' + method, isDebugLogEnabled)
1806            } catch (BpmnError e) {
1807                    throw e;
1808            } catch (Exception e) {
1809                    logError('Caught exception in ' + method, e)
1810                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage())
1811            }
1812    }
1813
1814    /**
1815         * Post process a result from invoking the UpdateAAIGenericVnf subflow.
1816         *
1817         * @param execution The flow's execution instance.
1818         */
1819    public void postProcessUpdateAAIGenericVnf(Execution execution) {
1820            def method = getClass().getSimpleName() + '.postProcessUpdateAAIGenericVnf(' +
1821                    'execution=' + execution.getId() +
1822                    ')'
1823            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1824            logDebug('Entered ' + method, isDebugLogEnabled)
1825
1826            try {
1827                    def rollbackData = execution.getVariable("RollbackData")
1828
1829                    rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "true")
1830
1831                    def vnfId = execution.getVariable('DCVFM_vnfId')
1832                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
1833                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
1834                    def ipv4OamAddressElement = ''
1835                    def managementV6AddressElement = ''
1836
1837                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {
1838                            rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
1839                    }
1840
1841                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
1842                            rollbackData.put("VFMODULE", "oamManagementV6Address", oamManagementV6Address)
1843                    }
1844
1845                    execution.setVariable("RollbackData", rollbackData)
1846
1847                    logDebug('Exited ' + method, isDebugLogEnabled)
1848            } catch (BpmnError e) {
1849                    throw e;
1850            } catch (Exception e) {
1851                    logError('Caught exception in ' + method, e)
1852                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in postProcessUpdateAAIGenericVnf(): ' + e.getMessage())
1853            }
1854    }
1855    
1856    public void preProcessRollback (Execution execution) {
1857            def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1858            utils.log("DEBUG"," ***** preProcessRollback ***** ", isDebugEnabled)
1859            try {
1860                    
1861                    Object workflowException = execution.getVariable("WorkflowException");
1862
1863                    if (workflowException instanceof WorkflowException) {
1864                            utils.log("DEBUG", "Prev workflowException: " + workflowException.getErrorMessage(), isDebugEnabled)
1865                            execution.setVariable("prevWorkflowException", workflowException);
1866                            //execution.setVariable("WorkflowException", null);
1867                    }
1868            } catch (BpmnError e) {
1869                    utils.log("DEBUG", "BPMN Error during preProcessRollback", isDebugEnabled)
1870            } catch(Exception ex) {
1871                    String msg = "Exception in preProcessRollback. " + ex.getMessage()
1872                    utils.log("DEBUG", msg, isDebugEnabled)
1873            }
1874            utils.log("DEBUG"," *** Exit preProcessRollback *** ", isDebugEnabled)
1875    }
1876
1877    public void postProcessRollback (Execution execution) {
1878            def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1879            utils.log("DEBUG"," ***** postProcessRollback ***** ", isDebugEnabled)
1880            String msg = ""
1881            try {
1882                    Object workflowException = execution.getVariable("prevWorkflowException");
1883                    if (workflowException instanceof WorkflowException) {
1884                            utils.log("DEBUG", "Setting prevException to WorkflowException: ", isDebugEnabled)
1885                            execution.setVariable("WorkflowException", workflowException);
1886                    }
1887                    execution.setVariable("rollbackData", null)
1888            } catch (BpmnError b) {
1889                    utils.log("DEBUG", "BPMN Error during postProcessRollback", isDebugEnabled)
1890                    throw b;
1891            } catch(Exception ex) {
1892                    msg = "Exception in postProcessRollback. " + ex.getMessage()
1893                    utils.log("DEBUG", msg, isDebugEnabled)
1894            }
1895            utils.log("DEBUG"," *** Exit postProcessRollback *** ", isDebugEnabled)
1896    }
1897
1898 }