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