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