58b90a1bf21365ceac38a08c022c5aa423fb094c
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateVfModule.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import javax.xml.parsers.DocumentBuilder
24 import javax.xml.parsers.DocumentBuilderFactory
25
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.delegate.DelegateExecution
28 import org.json.JSONArray
29 import org.json.JSONObject
30 import org.onap.aai.domain.yang.GenericVnf
31 import org.onap.so.bpmn.common.scripts.AaiUtil
32 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
33 import org.onap.so.bpmn.common.scripts.ExceptionUtil
34 import org.onap.so.bpmn.common.scripts.MsoUtils
35 import org.onap.so.bpmn.common.scripts.NetworkUtils
36 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
37 import org.onap.so.bpmn.common.scripts.VfModuleBase
38 import org.onap.so.bpmn.core.RollbackData
39 import org.onap.so.bpmn.core.UrnPropertiesReader
40 import org.onap.so.bpmn.core.WorkflowException
41
42 import org.onap.so.bpmn.core.domain.VnfResource
43 import org.onap.so.bpmn.core.json.DecomposeJsonUtil
44 import org.onap.so.bpmn.core.json.JsonUtils
45 import org.onap.so.client.graphinventory.entities.uri.Depth
46 import org.onap.so.client.aai.AAIObjectPlurals
47 import org.onap.so.client.aai.AAIObjectType;
48 import org.onap.so.client.aai.AAIResourcesClient
49 import org.onap.so.client.aai.entities.AAIResultWrapper
50 import org.onap.so.client.aai.entities.uri.AAIResourceUri
51 import org.onap.so.client.aai.entities.uri.AAIUri
52 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
53 import org.onap.so.constants.Defaults
54 import org.onap.so.logger.MessageEnum
55 import org.onap.so.logger.MsoLogger
56 import org.onap.so.rest.APIResponse
57 import org.onap.so.rest.RESTClient
58 import org.onap.so.rest.RESTConfig
59 import org.springframework.web.util.UriUtils
60 import org.w3c.dom.Document
61 import org.w3c.dom.Element
62 import org.w3c.dom.NamedNodeMap
63 import org.w3c.dom.Node
64 import org.w3c.dom.NodeList
65 import org.xml.sax.InputSource
66
67 import com.fasterxml.jackson.databind.ObjectMapper
68
69
70
71 public class DoCreateVfModule extends VfModuleBase {
72         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModule.class);
73
74         String Prefix="DCVFM_"
75         ExceptionUtil exceptionUtil = new ExceptionUtil()
76         JsonUtils jsonUtil = new JsonUtils()
77         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
78         CatalogDbUtils catalog = new CatalogDbUtils()
79         DecomposeJsonUtil decomposeJsonUtils = new DecomposeJsonUtil()
80
81         /**
82          * Validates the request message and sets up the workflow.
83          * @param execution the execution
84          */
85         public void preProcessRequest(DelegateExecution execution) {
86                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
87                         'execution=' + execution.getId() +
88                         ')'
89
90                 msoLogger.trace('Entered ' + method)
91
92                 execution.setVariable('prefix', Prefix)
93                 try{
94                         def rollbackData = execution.getVariable("rollbackData")
95                         if (rollbackData == null) {
96                                 rollbackData = new RollbackData()
97                         }
98
99                         execution.setVariable("DCVFM_vnfParamsExistFlag", false)
100                         execution.setVariable("DCVFM_oamManagementV4Address", "")
101                         execution.setVariable("DCVFM_oamManagementV6Address", "")
102
103                         String request = execution.getVariable("DoCreateVfModuleRequest")
104
105                         if (request == null || request.isEmpty()) {
106                                 // Building Block-type request
107
108                                 String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo")
109
110                                 def serviceModelInfo = execution.getVariable("serviceModelInfo")
111                                 msoLogger.debug("serviceModelInfo: " + serviceModelInfo)
112                                 String modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid")
113                                 msoLogger.debug("modelInvariantUuid: " + modelInvariantUuid)
114
115                                 def vnfModelInfo = execution.getVariable("vnfModelInfo")
116
117                                 //tenantId
118                                 def tenantId = execution.getVariable("tenantId")
119                                 execution.setVariable("DCVFM_tenantId", tenantId)
120                                 rollbackData.put("VFMODULE", "tenantid", tenantId)
121                                 //volumeGroupId
122                                 def volumeGroupId = execution.getVariable("volumeGroupId")
123                                 execution.setVariable("DCVFM_volumeGroupId", volumeGroupId)
124                                 //volumeGroupName
125                                 def volumeGroupName = execution.getVariable("volumeGroupName")
126                                 execution.setVariable("DCVFM_volumeGroupName", volumeGroupName)
127                                 //cloudSiteId
128                                 def cloudSiteId = execution.getVariable("lcpCloudRegionId")
129                                 execution.setVariable("DCVFM_cloudSiteId", cloudSiteId)
130                                 rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId)
131                                 msoLogger.debug("cloudSiteId: " + cloudSiteId)
132                                 //cloudOwner
133                                 def cloudOwner = execution.getVariable("cloudOwner")
134                                 execution.setVariable("DCVFM_cloudOwner", cloudOwner)
135                                 rollbackData.put("VFMODULE", "cloudOwner", cloudOwner)
136                                 msoLogger.debug("cloudOwner: " + cloudOwner)
137                                 //vnfType
138                                 def vnfType = execution.getVariable("vnfType")
139                                 execution.setVariable("DCVFM_vnfType", vnfType)
140                                 rollbackData.put("VFMODULE", "vnftype", vnfType)
141                                 msoLogger.debug("vnfType: " + vnfType)
142                                 //vnfName
143                                 def vnfName = execution.getVariable("vnfName")
144                                 execution.setVariable("DCVFM_vnfName", vnfName)
145                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
146                                 msoLogger.debug("vnfName: " + vnfName)
147                                 //vnfId
148                                 def vnfId = execution.getVariable("vnfId")
149                                 execution.setVariable("DCVFM_vnfId", vnfId)
150                                 rollbackData.put("VFMODULE", "vnfid", vnfId)
151                                 msoLogger.debug("vnfId: " + vnfId)
152                                 //vfModuleName
153                                 def vfModuleName = execution.getVariable("vfModuleName")
154                                 execution.setVariable("DCVFM_vfModuleName", vfModuleName)
155                                 rollbackData.put("VFMODULE", "vfmodulename", vfModuleName)
156                                 msoLogger.debug("vfModuleName: " + vfModuleName)
157                                 //vfModuleModelName
158                                 def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName")
159                                 execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName)
160                                 rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName)
161                                 msoLogger.debug("vfModuleModelName: " + vfModuleModelName)
162                                 //modelCustomizationUuid
163                                 def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelCustomizationUuid")
164                                 execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid)
165                                 rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid)
166                                 msoLogger.debug("modelCustomizationUuid: " + modelCustomizationUuid)
167                                 //vfModuleId
168                                 def vfModuleId = execution.getVariable("vfModuleId")
169                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
170                                 msoLogger.debug("vfModuleId: " + vfModuleId)
171                                 def requestId = execution.getVariable("msoRequestId")
172                                 execution.setVariable("DCVFM_requestId", requestId)
173                                 msoLogger.debug("requestId: " + requestId)
174                                 rollbackData.put("VFMODULE", "msorequestid", requestId)
175                                 // Set mso-request-id to request-id for VNF Adapter interface
176                                 execution.setVariable("mso-request-id", requestId)
177                                 //serviceId
178                                 def serviceId = execution.getVariable("serviceId")
179                                 execution.setVariable("DCVFM_serviceId", serviceId)
180                                 msoLogger.debug("serviceId: " + serviceId)
181                                 //serviceInstanceId
182                                 def serviceInstanceId = execution.getVariable("serviceInstanceId")
183                                 execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId)
184                                 rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId)
185                                 msoLogger.debug("serviceInstanceId: " + serviceInstanceId)
186                                 //source - HARDCODED
187                                 def source = "VID"
188                                 execution.setVariable("DCVFM_source", source)
189                                 rollbackData.put("VFMODULE", "source", source)
190                                 msoLogger.debug("source: " + source)
191                                 //backoutOnFailure
192                                 def disableRollback = execution.getVariable("disableRollback")
193                                 def backoutOnFailure = true
194                                 if (disableRollback != null && disableRollback == true) {
195                                         backoutOnFailure = false
196                                 }
197                                 execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure)
198                                 msoLogger.debug("backoutOnFailure: " + backoutOnFailure)
199                                 //isBaseVfModule
200                                 def isBaseVfModule = execution.getVariable("isBaseVfModule")
201                                 execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule)
202                                 msoLogger.debug("isBaseVfModule: " + isBaseVfModule)
203                                 //asdcServiceModelVersion
204                                 def asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion")
205                                 execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion)
206                                 msoLogger.debug("asdcServiceModelVersion: " + asdcServiceModelVersion)
207                                 //personaModelId
208                                 execution.setVariable("DCVFM_personaModelId", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInvariantUuid"))
209                                 //personaModelVersion
210                                 execution.setVariable("DCVFM_personaModelVersion", jsonUtil.getJsonValue(vfModuleModelInfo, "modelUuid"))
211                                 //vfModuleLabel
212                                 def vfModuleLabel = execution.getVariable("vfModuleLabel")
213                                 if (vfModuleLabel != null) {
214                                         execution.setVariable("DCVFM_vfModuleLabel", vfModuleLabel)
215                                         msoLogger.debug("vfModuleLabel: " + vfModuleLabel)
216                                 }
217                                 //Get or Generate UUID
218                                 String uuid = execution.getVariable("DCVFM_uuid")
219                                 if(uuid == null){
220                                         uuid = UUID.randomUUID()
221                                         msoLogger.debug("Generated messageId (UUID) is: " + uuid)
222                                 }else{
223                                         msoLogger.debug("Found messageId (UUID) is: " + uuid)
224                                 }
225                                 //isVidRequest
226                                 String isVidRequest = execution.getVariable("isVidRequest")
227                                 // default to true
228                                 if (isVidRequest == null || isVidRequest.isEmpty()) {
229                                         execution.setVariable("isVidRequest", "true")
230                                 }
231                                 //globalSubscriberId
232                                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
233                                 execution.setVariable("DCVFM_globalSubscriberId", globalSubscriberId)
234                                 msoLogger.debug("globalSubsrciberId: " + globalSubscriberId)
235                                 //OofDirectives
236                                 String oofDirectives = execution.getVariable("oofDirectives")
237                                 Map<String,String> vfModuleInputParams = execution.getVariable("vfModuleInputParams")
238                                 if (oofDirectives != null) {
239                                         vfModuleInputParams.put("oofDirectives", oofDirectives)
240                                         logDebug("OofDirectives are: " + oofDirectives, isDebugLogEnabled)
241                                 }
242                                 if (vfModuleInputParams != null) {
243                                         execution.setVariable("DCVFM_vnfParamsMap", vfModuleInputParams)
244                                         execution.setVariable("DCVFM_vnfParamsExistFlag", true)
245                                 }
246                                 //usePreload
247                                 def usePreload = execution.getVariable("usePreload")
248                                 execution.setVariable("DCVFM_usePreload", usePreload)
249                                 msoLogger.debug("usePreload: " + usePreload)
250                                 //aLaCarte
251                                 def aLaCarte = execution.getVariable("aLaCarte")
252                                 execution.setVariable("DCVFM_aLaCarte", aLaCarte)
253                                 msoLogger.debug("aLaCarte: " + aLaCarte)
254
255                                 //get workload and environment context from parent SI
256                                 String environmentContext = ""
257                                 String workloadContext =""
258                                 String serviceType =""
259
260                                 try{
261                                         String json = catalog.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid )
262                                         serviceType = jsonUtil.getJsonValue(json, "serviceResources.serviceType")
263                                 }catch(BpmnError e){
264                                         throw e
265                                 } catch (Exception ex){
266                                         String msg = "Exception in preProcessRequest " + ex.getMessage()
267                                         msoLogger.debug(msg)
268                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
269                                 }
270
271                                 try{
272                                         AAIUri serviceInstanceURI = AAIUriFactory.create(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId,serviceType,serviceInstanceId)
273                                         AAIResourcesClient aaiRC = new AAIResourcesClient()
274                                         AAIResultWrapper aaiRW = aaiRC.get(serviceInstanceURI)
275                                         Map<String, Object> aaiJson = aaiRW.asMap()
276                                         environmentContext = aaiJson.getOrDefault("environment-context","")
277                                         workloadContext = aaiJson.getOrDefault("workload-context","")
278
279                                 }catch (Exception ex) {
280                                         msoLogger.debug("Error retreiving parent service instance information")
281                                 }
282
283                                 execution.setVariable("DCVFM_environmentContext",environmentContext)
284                                 execution.setVariable("DCVFM_workloadContext",workloadContext)
285
286                         }
287                         else {
288                                 // The info is inside the request - DEAD CODE
289                                 msoLogger.debug("DoCreateVfModule request: " + request)
290
291                                 //tenantId
292                                 def tenantId = ""
293                                 if (utils.nodeExists(request, "tenant-id")) {
294                                         tenantId = utils.getNodeText(request, "tenant-id")
295                                 }
296                                 execution.setVariable("DCVFM_tenantId", tenantId)
297                                 rollbackData.put("VFMODULE", "tenantid", tenantId)
298                                 //volumeGroupId
299                                 def volumeGroupId = ""
300                                 if (utils.nodeExists(request, "volume-group-id")) {
301                                         volumeGroupId = utils.getNodeText(request, "volume-group-id")
302                                 }
303                                 execution.setVariable("DCVFM_volumeGroupId", volumeGroupId)
304                                 //volumeGroupId
305                                 def volumeGroupName = ""
306                                 if (utils.nodeExists(request, "volume-group-name")) {
307                                         volumeGroupName = utils.getNodeText(request, "volume-group-name")
308                                 }
309                                 execution.setVariable("DCVFM_volumeGroupName", volumeGroupName)
310                                 //cloudSiteId
311                                 def cloudSiteId = ""
312                                 if (utils.nodeExists(request, "aic-cloud-region")) {
313                                         cloudSiteId = utils.getNodeText(request, "aic-cloud-region")
314                                 }
315                                 execution.setVariable("DCVFM_cloudSiteId", cloudSiteId)
316                                 rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId)
317                                 msoLogger.debug("cloudSiteId: " + cloudSiteId)
318                                 //vnfType
319                                 def vnfType = ""
320                                 if (utils.nodeExists(request, "vnf-type")) {
321                                         vnfType = utils.getNodeText(request, "vnf-type")
322                                 }
323                                 execution.setVariable("DCVFM_vnfType", vnfType)
324                                 rollbackData.put("VFMODULE", "vnftype", vnfType)
325                                 msoLogger.debug("vnfType: " + vnfType)
326                                 //vnfName
327                                 def vnfName = ""
328                                 if (utils.nodeExists(request, "vnf-name")) {
329                                         vnfName = utils.getNodeText(request, "vnf-name")
330                                 }
331                                 execution.setVariable("DCVFM_vnfName", vnfName)
332                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
333                                 msoLogger.debug("vnfName: " + vnfName)
334                                 //vnfId
335                                 def vnfId = ""
336                                 if (utils.nodeExists(request, "vnf-id")) {
337                                         vnfId = utils.getNodeText(request, "vnf-id")
338                                 }
339                                 execution.setVariable("DCVFM_vnfId", vnfId)
340                                 rollbackData.put("VFMODULE", "vnfid", vnfId)
341                                 msoLogger.debug("vnfId: " + vnfId)
342                                 //vfModuleName
343                                 def vfModuleName = ""
344                                 if (utils.nodeExists(request, "vf-module-name")) {
345                                         vfModuleName = utils.getNodeText(request, "vf-module-name")
346                                 }
347                                 execution.setVariable("DCVFM_vfModuleName", vfModuleName)
348                                 rollbackData.put("VFMODULE", "vfmodulename", vfModuleName)
349                                 msoLogger.debug("vfModuleName: " + vfModuleName)
350                                 //vfModuleModelName
351                                 def vfModuleModelName = ""
352                                 if (utils.nodeExists(request, "vf-module-model-name")) {
353                                         vfModuleModelName = utils.getNodeText(request, "vf-module-model-name")
354                                 }
355                                 execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName)
356                                 rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName)
357                                 msoLogger.debug("vfModuleModelName: " + vfModuleModelName)
358                                 //modelCustomizationUuid
359                                 def modelCustomizationUuid = ""
360                                 if (utils.nodeExists(request, "model-customization-id")) {
361                                         modelCustomizationUuid = utils.getNodeText(request, "model-customization-id")
362                                 }
363                                 execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid)
364                                 rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid)
365                                 msoLogger.debug("modelCustomizationUuid: " + modelCustomizationUuid)
366                                 //vfModuleId
367                                 def vfModuleId = ""
368                                 if (utils.nodeExists(request, "vf-module-id")) {
369                                         vfModuleId = utils.getNodeText(request, "vf-module-id")
370                                 }
371                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
372                                 msoLogger.debug("vfModuleId: " + vfModuleId)
373                                 def requestId = ""
374                                 if (utils.nodeExists(request, "request-id")) {
375                                         requestId = utils.getNodeText(request, "request-id")
376                                 }
377                                 execution.setVariable("DCVFM_requestId", requestId)
378                                 msoLogger.debug("requestId: " + requestId)
379                                 //serviceId
380                                 def serviceId = ""
381                                 if (utils.nodeExists(request, "service-id")) {
382                                         serviceId = utils.getNodeText(request, "service-id")
383                                 }
384                                 execution.setVariable("DCVFM_serviceId", serviceId)
385                                 msoLogger.debug("serviceId: " + serviceId)
386                                 //serviceInstanceId
387                                 def serviceInstanceId = ""
388                                 if (utils.nodeExists(request, "service-instance-id")) {
389                                         serviceInstanceId = utils.getNodeText(request, "service-instance-id")
390                                 }
391                                 execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId)
392                                 rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId)
393                                 msoLogger.debug("serviceInstanceId: " + serviceInstanceId)
394                                 //source
395                                 def source = ""
396                                 if (utils.nodeExists(request, "source")) {
397                                         source = utils.getNodeText(request, "source")
398                                 }
399                                 execution.setVariable("DCVFM_source", source)
400                                 rollbackData.put("VFMODULE", "source", source)
401                                 msoLogger.debug("source: " + source)
402                                 //backoutOnFailure
403                                 NetworkUtils networkUtils = new NetworkUtils()
404                                 def backoutOnFailure = networkUtils.isRollbackEnabled(execution,request)
405                                 execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure)
406                                 msoLogger.debug("backoutOnFailure: " + backoutOnFailure)
407                                 //isBaseVfModule
408                                 def isBaseVfModule = "false"
409                                 if (utils.nodeExists(request, "is-base-vf-module")) {
410                                         isBaseVfModule = utils.getNodeText(request, "is-base-vf-module")
411                                 }
412                                 execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule)
413                                 msoLogger.debug("isBaseVfModule: " + isBaseVfModule)
414                                 //asdcServiceModelVersion
415                                 def asdcServiceModelVersion = ""
416                                 if (utils.nodeExists(request, "asdc-service-model-version")) {
417                                         asdcServiceModelVersion = utils.getNodeText(request, "asdc-service-model-version")
418                                 }
419                                 execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion)
420                                 msoLogger.debug("asdcServiceModelVersion: " + asdcServiceModelVersion)
421
422                                 //personaModelId
423                                 def personaModelId = ""
424                                 if (utils.nodeExists(request, "persona-model-id")) {
425                                         personaModelId = utils.getNodeText(request, "persona-model-id")
426                                 }
427                                 execution.setVariable("DCVFM_personaModelId", personaModelId)
428                                 msoLogger.debug("personaModelId: " + personaModelId)
429
430                                 //personaModelVersion
431                                 def personaModelVersion = ""
432                                 if (utils.nodeExists(request, "persona-model-version")) {
433                                         personaModelVersion = utils.getNodeText(request, "persona-model-version")
434                                 }
435                                 execution.setVariable("DCVFM_personaModelVersion", personaModelVersion)
436                                 msoLogger.debug("personaModelVersion: " + personaModelVersion)
437
438                                 // Process the parameters
439
440                                                 String vnfParamsChildNodes = utils.getChildNodes(request, "vnf-params")
441                                                 if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){
442                                                                 msoLogger.debug("Request contains NO VNF Params")
443                                                 }else{
444                                                                 msoLogger.debug("Request does contain VNF Params")
445                                                                 execution.setVariable("DCVFM_vnfParamsExistFlag", true)
446
447                                                                 InputSource xmlSource = new InputSource(new StringReader(request));
448                                                                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
449                                                                 docFactory.setNamespaceAware(true)
450                                                                 DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
451                                                                 Document xml = docBuilder.parse(xmlSource)
452                                                                 //Get params, build map
453                                                                 Map<String, String> paramsMap = new HashMap<String, String>()
454                                                                 NodeList paramsList = xml.getElementsByTagNameNS("*", "param")
455
456                                                                 for (int z = 0; z < paramsList.getLength(); z++) {
457                                                                         Node node = paramsList.item(z)
458                                                                         String paramValue = node.getTextContent()
459                                                                         NamedNodeMap e = node.getAttributes()
460                                                                         String paramName = e.getNamedItem("name").getTextContent()
461                                                                         paramsMap.put(paramName, paramValue)
462                                                                 }
463                                                                 execution.setVariable("DCVFM_vnfParamsMap", paramsMap)
464                                                         }
465
466                                 //OofDirectives
467                                 String oofDirectives = execution.getVariable("oofDirectives")
468                                 if (oofDirectives != null) {
469                                         Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
470                                         paramsMap.put("oofDirectives", oofDirectives)
471                                         logDebug("OofDirectives are: " + oofDirectives, isDebugLogEnabled)
472                                         execution.setVariable("DCVFM_vnfParamsMap", paramsMap)
473                                 }
474                         }
475
476
477                         //Get or Generate UUID
478                         String uuid = execution.getVariable("DCVFM_uuid")
479                         if(uuid == null){
480                                 uuid = UUID.randomUUID()
481                                 msoLogger.debug("Generated messageId (UUID) is: " + uuid)
482                         }else{
483                                 msoLogger.debug("Found messageId (UUID) is: " + uuid)
484                         }
485                         // Get sdncVersion, default to empty
486                         String sdncVersion = execution.getVariable("sdncVersion")
487                         if (sdncVersion == null) {
488                                 sdncVersion = ""
489                         }
490                         msoLogger.debug("sdncVersion: " + sdncVersion)
491                         execution.setVariable("DCVFM_sdncVersion", sdncVersion)
492
493                         execution.setVariable("DCVFM_uuid", uuid)
494                         execution.setVariable("DCVFM_baseVfModuleId", "")
495                         execution.setVariable("DCVFM_baseVfModuleHeatStackId", "")
496                         execution.setVariable("DCVFM_heatStackId", "")
497                         execution.setVariable("DCVFM_contrailServiceInstanceFqdn", "")
498                         execution.setVariable("DCVFM_volumeGroupStackId", "")
499                         execution.setVariable("DCVFM_cloudRegionForVolume", "")
500                         execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", "")
501                         execution.setVariable("DCVFM_vnfTypeToQuery", "generic-vnf")
502                         rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "false")
503                         rollbackData.put("VFMODULE", "rollbackUpdateAAIVfModule", "false")
504                         rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "false")
505                         rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "false")
506                         rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "false")
507                         rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "false")
508                         rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "false")
509                         rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "false")
510                         rollbackData.put("VFMODULE", "heatstackid", "")
511
512                         String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution)
513                                 if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) {
514                                         def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing'
515                                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, msg);
516
517                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
518                                 }
519                                 execution.setVariable("DCVFM_sdncCallbackUrl", sdncCallbackUrl)
520                             msoLogger.debug("SDNC Callback URL is: " + sdncCallbackUrl)
521
522
523                         execution.setVariable("rollbackData", rollbackData)
524                 }catch(BpmnError b){
525             msoLogger.error(b);
526                         throw b
527                 }catch(Exception e){
528             msoLogger.error(e);
529                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!")
530                 }
531
532                 msoLogger.trace('Exited ' + method)
533         }
534
535         /**
536          * Validates a workflow response.
537          * @param execution the execution
538          * @param responseVar the execution variable in which the response is stored
539          * @param responseCodeVar the execution variable in which the response code is stored
540          * @param errorResponseVar the execution variable in which the error response is stored
541          */
542         public void validateWorkflowResponse(DelegateExecution execution, String responseVar,
543                         String responseCodeVar, String errorResponseVar) {
544                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
545                 sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar)
546         }
547
548
549         /**
550          * Sends the empty, synchronous response back to the API Handler.
551          * @param execution the execution
552          */
553         public void sendResponse(DelegateExecution execution) {
554                 def method = getClass().getSimpleName() + '.sendResponse(' +
555                         'execution=' + execution.getId() +
556                         ')'
557
558                 msoLogger.trace('Entered ' + method)
559
560                 try {
561                         sendWorkflowResponse(execution, 200, "")
562                         msoLogger.trace('Exited ' + method)
563                 } catch (BpmnError e) {
564                         throw e;
565                 } catch (Exception e) {
566                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
567
568                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Internal Error')
569                 }
570         }
571
572         /**
573          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
574          * A 200 response is expected with the VNF info in the response body. Will find out the base module info
575          * and existing VNF's name for add-on modules
576          *
577          * @param execution The flow's execution instance.
578          */
579         public void postProcessCreateAAIVfModule(DelegateExecution execution) {
580                 def method = getClass().getSimpleName() + '.getVfModule(' +
581                         'execution=' + execution.getId() +
582                         ')'
583
584                 msoLogger.trace('Entered ' + method)
585
586                 try {
587                         def createResponse = execution.getVariable('DCVFM_createVfModuleResponse')
588                         msoLogger.debug("createVfModule Response: " + createResponse)
589
590                         def rollbackData = execution.getVariable("rollbackData")
591                         String vnfName = utils.getNodeText(createResponse, 'vnf-name')
592                         if (vnfName != null) {
593                                 execution.setVariable('DCVFM_vnfName', vnfName)
594                                 msoLogger.debug("vnfName retrieved from AAI is: " + vnfName)
595                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
596                         }
597                         String vnfId = utils.getNodeText(createResponse, 'vnf-id')
598                         execution.setVariable('DCVFM_vnfId', vnfId)
599                         msoLogger.debug("vnfId is: " + vnfId)
600                         String vfModuleId = utils.getNodeText(createResponse, 'vf-module-id')
601                         execution.setVariable('DCVFM_vfModuleId', vfModuleId)
602                         msoLogger.debug("vfModuleId is: " + vfModuleId)
603                         String vfModuleIndex= utils.getNodeText(createResponse, 'vf-module-index')
604                         execution.setVariable('DCVFM_vfModuleIndex', vfModuleIndex)
605                         msoLogger.debug("vfModuleIndex is: " + vfModuleIndex)
606                         rollbackData.put("VFMODULE", "vnfid", vnfId)
607                         rollbackData.put("VFMODULE", "vfmoduleid", vfModuleId)
608                         rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "true")
609                         rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "true")
610                         execution.setVariable("rollbackData", rollbackData)
611                 } catch (Exception ex) {
612                                 ex.printStackTrace()
613                                 msoLogger.debug('Exception occurred while postProcessing CreateAAIVfModule request:' + ex.getMessage())
614                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Bad response from CreateAAIVfModule' + ex.getMessage())
615                 }
616                 msoLogger.trace('Exited ' + method)
617         }
618
619
620         /**
621          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
622          * A 200 response is expected with the VNF info in the response body. Will find out the base module info.
623          *
624          * @param execution The flow's execution instance.
625          */
626         public void queryAAIVfModule(DelegateExecution execution) {
627
628                 def method = getClass().getSimpleName() + '.getVfModule(' +
629                         'execution=' + execution.getId() +
630                         ')'
631                 msoLogger.trace('Entered ' + method)
632
633                 try {
634                         def vnfId = execution.getVariable('DCVFM_vnfId')
635                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
636
637                         AaiUtil aaiUriUtil = new AaiUtil(this)
638                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE)
639                         String endPoint = aaiUriUtil.createAaiUri(uri)
640
641                         try {
642                                 RESTConfig config = new RESTConfig(endPoint);
643                                 def responseData = ''
644                                 def aaiRequestId = UUID.randomUUID().toString()
645                                 RESTClient client = new RESTClient(config).
646                                         addHeader('X-TransactionId', aaiRequestId).
647                                         addHeader('X-FromAppId', 'MSO').
648                                         addHeader('Content-Type', 'application/xml').
649                                         addHeader('Accept','application/xml');
650                                 msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
651                                 APIResponse response = client.httpGet()
652
653                                 responseData = response.getResponseBodyAsString()
654                                 if (responseData != null) {
655                                         msoLogger.debug("Received generic VNF data: " + responseData)
656
657                                 }
658
659                                 execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode())
660                                 execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData)
661                                 msoLogger.debug('Response code:' + response.getStatusCode())
662                                 msoLogger.debug('Response:' + System.lineSeparator() + responseData)
663                                 if (response.getStatusCode() == 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                         try {
727                                 RESTConfig config = new RESTConfig(endPoint);
728                                 def responseData = ''
729                                 def aaiRequestId = UUID.randomUUID().toString()
730                                 RESTClient client = new RESTClient(config).
731                                         addHeader('X-TransactionId', aaiRequestId).
732                                         addHeader('X-FromAppId', 'MSO').
733                                         addHeader('Content-Type', 'application/xml').
734                                         addHeader('Accept','application/xml');
735                                 msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
736                                 APIResponse response = client.httpGet()
737                                 msoLogger.debug("createVfModule - invoking httpGet() to AAI")
738
739                                 responseData = response.getResponseBodyAsString()
740                                 if (responseData != null) {
741                                         msoLogger.debug("Received generic VNF data: " + responseData)
742
743                                 }
744
745                                 execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatusCode())
746                                 execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponse', responseData)
747                                 msoLogger.debug('Response code:' + response.getStatusCode())
748                                 msoLogger.debug('Response:' + System.lineSeparator() + responseData)
749                                 // Retrieve VF Module info and its orchestration status; if not found, do nothing
750                                 if (response.getStatusCode() == 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                                                 String aaiNamespace = aaiUriUtil.getNamespace()
1865                                                 msoLogger.debug('AAI namespace is: ' + aaiNamespace)
1866                                                 String payload = """<network-policy xmlns="${aaiNamespace}">
1867                                                                 <network-policy-id>${MsoUtils.xmlEscape(networkPolicyId)}</network-policy-id>
1868                                                                 <network-policy-fqdn>${MsoUtils.xmlEscape(fqdn)}</network-policy-fqdn>
1869                                                                 <heat-stack-id>${MsoUtils.xmlEscape(execution.getVariable("DCVFM_heatStackId"))}</heat-stack-id>
1870                                                                 </network-policy>""" as String
1871
1872                                                 execution.setVariable("DCVFM_addNetworkPolicyAAIRequestBody", payload)
1873
1874                                                 AAIResourceUri addUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId)
1875                                                 String addNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(addUri)
1876
1877                                                 msoLogger.debug("AAI request endpoint: " + addNetworkPolicyAAIRequest)
1878
1879                                                 def aaiRequestIdPut = UUID.randomUUID().toString()
1880                                                 RESTConfig configPut = new RESTConfig(addNetworkPolicyAAIRequest);
1881                                                 RESTClient clientPut = new RESTClient(configPut).addHeader("X-TransactionId", aaiRequestIdPut)
1882                                                                 .addHeader("X-FromAppId", "MSO")
1883                                                                 .addHeader("Content-Type", "application/xml")
1884                                                                 .addHeader("Accept","application/xml");
1885                                                 msoLogger.debug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload)
1886                                                 APIResponse responsePut = clientPut.httpPut(payload)
1887                                                 int returnCodePut = responsePut.getStatusCode()
1888                                                 execution.setVariable("DCVFM_aaiAddNetworkPolicyReturnCode", returnCodePut)
1889                                                 msoLogger.debug(" ***** AAI add network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodePut)
1890
1891                                                 String aaiResponseAsStringPut = responsePut.getResponseBodyAsString()
1892                                                 if (isOneOf(returnCodePut, 200, 201)) {
1893                                                         msoLogger.debug("The return code from adding network policy is: "  + returnCodePut)
1894                                                         // This network policy was created in AAI successfully
1895                                                         execution.setVariable("DCVFM_addNetworkPolicyAAIResponse", aaiResponseAsStringPut)
1896                                                         msoLogger.debug(" AddAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsStringPut)
1897                                                         rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true")
1898                                                         rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn)
1899                                                         execution.setVariable("rollbackData", rollbackData)
1900
1901                                                 } else {
1902                                                         // aai all errors
1903                                                         String putErrorMessage = "Unable to add network-policy to AAI createNetworkPoliciesInAAI - " + returnCodePut
1904                                                         msoLogger.debug(putErrorMessage)
1905                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, putErrorMessage)
1906                                                 }
1907
1908                                         }
1909
1910                                 } // end loop
1911
1912
1913                    } else {
1914                            msoLogger.debug("No contrail network policies to query/create")
1915
1916                    }
1917
1918            } catch (BpmnError e) {
1919                    throw e;
1920
1921            } catch (Exception ex) {
1922                    String exceptionMessage = "Bpmn error encountered in DoCreateVfModule flow. createNetworkPoliciesInAAI() - " + ex.getMessage()
1923                    msoLogger.debug(exceptionMessage)
1924                    exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1925            }
1926
1927    }
1928
1929    /**
1930         * Prepare a Request for invoking the UpdateAAIGenericVnf subflow.
1931         *
1932         * @param execution The flow's execution instance.
1933         */
1934    public void prepUpdateAAIGenericVnf(DelegateExecution execution) {
1935            def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' +
1936                    'execution=' + execution.getId() +
1937                    ')'
1938
1939            msoLogger.trace('Entered ' + method)
1940
1941            try {
1942                    def rollbackData = execution.getVariable("rollbackData")
1943                    def vnfId = execution.getVariable('DCVFM_vnfId')
1944                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
1945                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
1946                    def ipv4OamAddressElement = ''
1947                    def managementV6AddressElement = ''
1948
1949                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {
1950                            ipv4OamAddressElement = '<ipv4-oam-address>' + oamManagementV4Address + '</ipv4-oam-address>'
1951                    }
1952
1953                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
1954                            managementV6AddressElement = '<management-v6-address>' + oamManagementV6Address + '</management-v6-address>'
1955                    }
1956
1957                    rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
1958
1959
1960                    String updateAAIGenericVnfRequest = """
1961                                         <UpdateAAIGenericVnfRequest>
1962                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1963                                                 ${ipv4OamAddressElement}
1964                                                 ${managementV6AddressElement}
1965                                         </UpdateAAIGenericVnfRequest>
1966                                 """
1967                            updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest)
1968                            execution.setVariable('DCVM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest)
1969                            msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest)
1970
1971
1972                    msoLogger.trace('Exited ' + method)
1973            } catch (BpmnError e) {
1974                    throw e;
1975            } catch (Exception e) {
1976                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered in " + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
1977
1978                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage())
1979            }
1980    }
1981
1982    /**
1983         * Post process a result from invoking the UpdateAAIGenericVnf subflow.
1984         *
1985         * @param execution The flow's execution instance.
1986         */
1987    public void postProcessUpdateAAIGenericVnf(DelegateExecution execution) {
1988            def method = getClass().getSimpleName() + '.postProcessUpdateAAIGenericVnf(' +
1989                    'execution=' + execution.getId() +
1990                    ')'
1991
1992            msoLogger.trace('Entered ' + method)
1993
1994            try {
1995                    def rollbackData = execution.getVariable("rollbackData")
1996
1997                    rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "true")
1998
1999                    def vnfId = execution.getVariable('DCVFM_vnfId')
2000                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
2001                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
2002                    def ipv4OamAddressElement = ''
2003                    def managementV6AddressElement = ''
2004
2005                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {
2006                            rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
2007                    }
2008
2009                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
2010                            rollbackData.put("VFMODULE", "oamManagementV6Address", oamManagementV6Address)
2011                    }
2012
2013                    execution.setVariable("rollbackData", rollbackData)
2014
2015                    msoLogger.trace('Exited ' + method)
2016            } catch (BpmnError e) {
2017                    throw e;
2018            } catch (Exception e) {
2019                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
2020                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in postProcessUpdateAAIGenericVnf(): ' + e.getMessage())
2021            }
2022    }
2023
2024    public void queryCatalogDB (DelegateExecution execution) {
2025
2026            String msg = ""
2027            msoLogger.trace("queryCatalogDB ")
2028
2029            try {
2030                    boolean twoPhaseDesign = false
2031                    // check for input
2032
2033                    String vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
2034                    msoLogger.debug("vfModuleModelName: " + vfModuleModelName)
2035                    def vnfModelInfo = execution.getVariable("vnfModelInfo")
2036                    def vnfModelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid")
2037
2038                    msoLogger.debug("vnfModelCustomizationUuid: " + vnfModelCustomizationUuid)
2039
2040                    JSONArray vnfs = catalog.getAllVnfsByVnfModelCustomizationUuid(execution, vnfModelCustomizationUuid, "v2")
2041
2042                    msoLogger.debug("Incoming Query Catalog DB for Vnf Response is: " + vnfModelCustomizationUuid)
2043                    // Only one match here
2044                    if (vnfs != null) {
2045                            JSONObject vnfObject = vnfs.get(0)
2046                            if (vnfObject != null) {
2047                                    String vnfJson = vnfObject.toString()
2048                                    //
2049                                    ObjectMapper om = new ObjectMapper();
2050                                    VnfResource vnf = om.readValue(vnfJson, VnfResource.class);
2051
2052                                    // Get multiStageDesign flag
2053
2054                                    String multiStageDesignValue = vnf.getMultiStageDesign()
2055                                    msoLogger.debug("multiStageDesign value from Catalog DB is: " + multiStageDesignValue)
2056                                    if (multiStageDesignValue != null) {
2057                                            if (multiStageDesignValue.equalsIgnoreCase("true")) {
2058                                                         twoPhaseDesign = true
2059                                            }
2060                                    }
2061                            }
2062                    }
2063
2064                    msoLogger.debug("setting twoPhaseDesign flag to: " + twoPhaseDesign)
2065
2066                    execution.setVariable("DCVFM_twoPhaseDesign", twoPhaseDesign)
2067            } catch (BpmnError e) {
2068                    throw e;
2069            } catch (Exception e) {
2070                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in queryCatalogDB', "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
2071                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryCatalogDB(): ' + e.getMessage())
2072            }
2073    }
2074
2075
2076    public void preProcessRollback (DelegateExecution execution) {
2077
2078            msoLogger.trace("preProcessRollback")
2079            try {
2080
2081                    Object workflowException = execution.getVariable("WorkflowException");
2082
2083                    if (workflowException instanceof WorkflowException) {
2084                            msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage())
2085                            execution.setVariable("prevWorkflowException", workflowException);
2086                            //execution.setVariable("WorkflowException", null);
2087                    }
2088            } catch (BpmnError e) {
2089                    msoLogger.debug("BPMN Error during preProcessRollback")
2090            } catch(Exception ex) {
2091                    String msg = "Exception in preProcessRollback. " + ex.getMessage()
2092                    msoLogger.debug(msg)
2093            }
2094            msoLogger.trace("Exit preProcessRollback")
2095    }
2096
2097    public void postProcessRollback (DelegateExecution execution) {
2098
2099            msoLogger.trace("postProcessRollback")
2100            String msg = ""
2101            try {
2102                    Object workflowException = execution.getVariable("prevWorkflowException");
2103                    if (workflowException instanceof WorkflowException) {
2104                            msoLogger.debug("Setting prevException to WorkflowException: ")
2105                            execution.setVariable("WorkflowException", workflowException);
2106                    }
2107                    execution.setVariable("rollbackData", null)
2108            } catch (BpmnError b) {
2109                    msoLogger.debug("BPMN Error during postProcessRollback")
2110                    throw b;
2111            } catch(Exception ex) {
2112                    msg = "Exception in postProcessRollback. " + ex.getMessage()
2113                    msoLogger.debug(msg)
2114            }
2115            msoLogger.trace("Exit postProcessRollback")
2116    }
2117
2118 }