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