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