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