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