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