Catchup commits for Dublin
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / NetworkUtils.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.common.scripts
22
23 import groovy.xml.XmlUtil
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.aai.domain.yang.L3Network
26 import org.onap.aai.domain.yang.Subnet
27 import org.onap.aai.domain.yang.Subnets
28 import org.onap.so.bpmn.core.UrnPropertiesReader
29 import org.onap.so.logger.MsoLogger
30 import org.w3c.dom.Document
31 import org.w3c.dom.Element
32 import org.w3c.dom.Node
33 import org.w3c.dom.NodeList
34 import org.xml.sax.InputSource
35
36 import javax.xml.parsers.DocumentBuilder
37 import javax.xml.parsers.DocumentBuilderFactory
38 import javax.xml.transform.Transformer
39 import javax.xml.transform.TransformerFactory
40 import javax.xml.transform.dom.DOMSource
41 import javax.xml.transform.stream.StreamResult
42
43 /**
44  * This groovy class supports the any Network processes that need the methods defined here.
45  */
46 class NetworkUtils {
47         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, NetworkUtils.class);
48
49
50         public MsoUtils utils = new MsoUtils()
51         private AbstractServiceTaskProcessor taskProcessor
52
53         public NetworkUtils(AbstractServiceTaskProcessor taskProcessor) {
54                 this.taskProcessor = taskProcessor
55         }
56
57         /**
58          * This method returns the string for Network request
59          * V2 for Contrail 3.x will populate cloud-region data in same cloudSiteId filed
60          * Network adapter will handle it properly
61          * @param requestId either 'request-id' or 'mso-request-id'
62          * @param requestInput the request in the process
63          * @param queryIdResponse the response of REST AAI query by Id
64          * @param routeCollection the collection
65          * @param policyFqdns the policy
66          * @param tableCollection the collection
67          * @param cloudRegionId the cloud-region-region
68          * @return String request
69          */
70         def CreateNetworkRequestV2(execution, requestId, messageId, requestInput,L3Network queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) {
71                 String createNetworkRequest = null
72                 if(requestInput!=null && queryIdResponse!=null) {
73                                 String serviceInstanceId = ""
74                                 String sharedValue = ""
75                                 String externalValue = ""
76
77                                 if (source == "VID") {
78                                         sharedValue = queryIdResponse.isIsSharedNetwork() != null ? queryIdResponse.isIsSharedNetwork() : "false"
79                                         externalValue = queryIdResponse.isIsExternalNetwork() != null ? queryIdResponse.isIsExternalNetwork() : "false"
80                                         serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id")
81
82                                 } else { // source = 'PORTAL'
83                                         sharedValue = getParameterValue(requestInput, "shared")
84                                         externalValue = getParameterValue(requestInput, "external")
85                                         serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") != null ? utils.getNodeText(requestInput, "service-instance-id") : ""
86                                 }
87
88                                 String networkParams = ""
89                                 if (utils.nodeExists(requestInput, "network-params")) {
90                                         String netParams = utils.getNodeXml(requestInput, "network-params", false).replace("tag0:","").replace(":tag0","")
91                                         networkParams = buildParams(netParams)
92                                 }
93
94                                 String failIfExists = "false"
95                                 // requestInput
96                                 String cloudRegion = cloudRegionId
97                                 String tenantId = utils.getNodeText(requestInput, "tenant-id")
98
99                                 String networkType = ""
100                                 String modelCustomizationUuid = ""
101                                 if (utils.nodeExists(requestInput, "networkModelInfo")) {
102                                         String networkModelInfo = utils.getNodeXml(requestInput, "networkModelInfo", false).replace("tag0:","").replace(":tag0","")
103                                         networkType = utils.getNodeText(networkModelInfo, "modelName")
104                                         modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid")
105                                 } else {
106                                         networkType = queryIdResponse.getNetworkType()
107                                         modelCustomizationUuid = utils.getNodeText(requestInput, "modelCustomizationId")
108                                 }
109
110                                 // queryIdResponse
111                                 String networkName = queryIdResponse.getNetworkName()
112                                 String networkId = queryIdResponse.getNetworkId()
113                                 String networkTechnology = queryIdResponse.getNetworkTechnology()
114
115                                 // contrailNetwork - networkTechnology = 'Contrail' vs. 'AIC_SR_IOV')
116                                 String contrailNetwork = ""
117                                 if (networkTechnology.contains('Contrail') || networkTechnology.contains('contrail') || networkTechnology.contains('CONTRAIL')) {
118                                         contrailNetwork = """<contrailNetwork>
119                                                                <shared>${MsoUtils.xmlEscape(sharedValue)}</shared>
120                                                                <external>${MsoUtils.xmlEscape(externalValue)}</external>
121                                                                ${routeCollection}
122                                                                ${policyFqdns}
123                                                                ${tableCollection}
124                                                          </contrailNetwork>"""
125                                         networkTechnology = "CONTRAIL"    // replace
126                             }
127
128                                 // rebuild subnets
129                                 String subnets = ""
130                                 if (queryIdResponse.getSubnets() != null) {
131                                         subnets = buildSubnets(queryIdResponse)
132                                 }
133
134                                 String physicalNetworkName = ""
135                                 physicalNetworkName = queryIdResponse.getPhysicalNetworkName()
136
137                                 String vlansCollection = buildVlans(queryIdResponse)
138
139                                 String notificationUrl = ""                                   //TODO - is this coming from URN? What variable/value to use?
140                                 //String notificationUrl = execution.getVariable("URN_?????") //TODO - is this coming from URN? What variable/value to use?
141
142                                 createNetworkRequest = """
143                                                                 <createNetworkRequest>
144                                                                         <cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId>
145                                                                         <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
146                                                                         <networkId>${MsoUtils.xmlEscape(networkId)}</networkId>
147                                                                         <networkName>${MsoUtils.xmlEscape(networkName)}</networkName>
148                                                                         <networkType>${MsoUtils.xmlEscape(networkType)}</networkType>
149                                                                         <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid>
150                                                                         <networkTechnology>${MsoUtils.xmlEscape(networkTechnology)}</networkTechnology>
151                                                                         <providerVlanNetwork>
152                                                                                 <physicalNetworkName>${MsoUtils.xmlEscape(physicalNetworkName)}</physicalNetworkName >
153                                                                                 ${vlansCollection}
154                                                                         </providerVlanNetwork>
155                                     ${contrailNetwork}
156                                                                         ${subnets}
157                                                                         <skipAAI>true</skipAAI>
158                                                                         <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout>
159                                                                         <failIfExists>${MsoUtils.xmlEscape(failIfExists)}</failIfExists>
160                                                                         ${networkParams}
161                                                                         <msoRequest>
162                                                                                 <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
163                                                                                 <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
164                                                                 </msoRequest>
165                                                                         <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
166                                                                         <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
167                                                                 </createNetworkRequest>
168                                                                 """.trim()
169                 }
170                 return createNetworkRequest
171
172         }
173
174         /**
175          * This method returns the string for Network request
176          * V2 for Contrail 3.x will populate cloud-region data in same cloudSiteId filed
177          * Network adapter will handle it properly
178          * @param requestId either 'request-id' or 'mso-request-id'
179          * @param requestInput the request in the process
180          * @param queryIdResponse the response of REST AAI query by Id
181          * @param routeCollection the collection
182          * @param policyFqdns the policy
183          * @param cloudRegionId the cloud-region-region
184          * @return String request
185          */
186         def UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, L3Network queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) {
187                 String updateNetworkRequest = null
188                 if(requestInput!=null && queryIdResponse!=null) {
189                                 String serviceInstanceId = ""
190                                 String sharedValue = ""
191                                 String externalValue = ""
192
193                                 if (source == "VID") {
194                                         sharedValue = queryIdResponse.isIsSharedNetwork() != null ? queryIdResponse.isIsSharedNetwork() : "false"
195                                         externalValue = queryIdResponse.isIsExternalNetwork() != null ? queryIdResponse.isIsExternalNetwork() : "false"
196                                         serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id")
197
198                                 } else { // source = 'PORTAL'
199                                         sharedValue = getParameterValue(requestInput, "shared")
200                                         externalValue = getParameterValue(requestInput, "external")
201                                         serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") != null ? utils.getNodeText(requestInput, "service-instance-id") : ""
202                                 }
203
204                                 String failIfExists = "false"
205                                 // requestInput
206                                 String cloudRegion = cloudRegionId
207                                 String tenantId = utils.getNodeText(requestInput, "tenant-id")
208
209                                 // queryIdResponse
210                                 String networkName = queryIdResponse.getNetworkName()
211                                 String networkId = queryIdResponse.getNetworkId()
212
213                                 String networkType = ""
214                                 String modelCustomizationUuid = ""
215                                 if (utils.nodeExists(requestInput, "networkModelInfo")) {
216                                         String networkModelInfo = utils.getNodeXml(requestInput, "networkModelInfo", false).replace("tag0:","").replace(":tag0","")
217                                         networkType = utils.getNodeText(networkModelInfo, "modelName")
218                                         modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid")
219                                 } else {
220                                         networkType = queryIdResponse.getNetworkType()
221                                         modelCustomizationUuid = utils.getNodeText(requestInput, "modelCustomizationId")
222                                 }
223
224                                 // rebuild subnets
225                                 String subnets = ""
226                                 if (queryIdResponse.getSubnets() != null) {
227                                         subnets = buildSubnets(queryIdResponse)
228                                 }
229
230                                 String networkParams = ""
231                                 if (utils.nodeExists(requestInput, "network-params")) {
232                                         String netParams = utils.getNodeXml(requestInput, "network-params", false).replace("tag0:","").replace(":tag0","")
233                                         networkParams = buildParams(netParams)
234                                 }
235
236                                 String networkStackId = queryIdResponse.getHeatStackId()
237                                 if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) {
238                                         networkStackId = "force_update"
239                                 }
240
241                                 String physicalNetworkName = queryIdResponse.getPhysicalNetworkName()
242                                 String vlansCollection = buildVlans(queryIdResponse)
243
244                                 updateNetworkRequest =
245                          """<updateNetworkRequest>
246                                                                 <cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId>
247                                                                 <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
248                                                                 <networkId>${MsoUtils.xmlEscape(networkId)}</networkId>
249                                                         <networkStackId>${MsoUtils.xmlEscape(networkStackId)}</networkStackId>
250                                                                 <networkName>${MsoUtils.xmlEscape(networkName)}</networkName>
251                                                                 <networkType>${MsoUtils.xmlEscape(networkType)}</networkType>
252                                                                 <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid>
253                                                                 <networkTypeVersion/>
254                                                                 <networkTechnology>CONTRAIL</networkTechnology>
255                                                                 <providerVlanNetwork>
256                                                                         <physicalNetworkName>${MsoUtils.xmlEscape(physicalNetworkName)}</physicalNetworkName>
257                                                                         ${vlansCollection}
258                                                                 </providerVlanNetwork>
259                                                                 <contrailNetwork>
260                                                                         <shared>${MsoUtils.xmlEscape(sharedValue)}</shared>
261                                                                         <external>${MsoUtils.xmlEscape(externalValue)}</external>
262                                                                         ${routeCollection}
263                                                                         ${policyFqdns}
264                                                                         ${tableCollection}
265                                                                 </contrailNetwork>
266                                                                 ${subnets}
267                                                                 <skipAAI>true</skipAAI>
268                                                                 <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout>
269                                                                 <failIfExists>${MsoUtils.xmlEscape(failIfExists)}</failIfExists>
270                                                                         ${networkParams}
271
272                                                                 <msoRequest>
273                                                                   <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
274                                                                   <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
275                                                                 </msoRequest>
276                                                                 <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
277                                                                 <notificationUrl></notificationUrl>
278                                                         </updateNetworkRequest>""".trim()
279
280                 }
281                 return updateNetworkRequest
282
283         }
284
285         /**
286          * This method returns the string for Create Volume Request payload
287          * @param groupId the volume-group-id
288          * @param volumeName the volume-group-name
289          * @param vnfType the vnf-type
290          * @param tenantId the value of relationship-key 'tenant.tenant-id'
291          * @return String request payload
292          */
293         def String CreateNetworkVolumeRequest(groupId, volumeName, vnfType, tenantId) {
294
295                 String requestPayload =
296                 """<volume-group xmlns="http://org.onap.so/v6">
297                                 <volume-group-id>${MsoUtils.xmlEscape(groupId)}</volume-group-id>
298                                 <volume-group-name>${MsoUtils.xmlEscape(volumeName)}</volume-group-name>
299                                 <heat-stack-id></heat-stack-id>
300                                 <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
301                                 <orchestration-status>Pending</orchestration-status>
302                                 <relationship-list>
303                                    <relationship>
304                                            <related-to>tenant</related-to>
305                                            <relationship-data>
306                                                    <relationship-key>tenant.tenant-id</relationship-key>
307                                                    <relationship-value>${MsoUtils.xmlEscape(tenantId)}</relationship-value>
308                                            </relationship-data>
309                                    </relationship>
310                            </relationship-list>
311                    </volume-group>"""
312
313                 return requestPayload
314         }
315
316         /**
317          * This method returns the string for Update Volume Request payload
318          * @param requeryAAIVolGrpNameResponse the response of query volume group name (in AAI)
319           * @param heatStackId the value of heat stack id
320          * @return String request payload
321          */
322         def String updateCloudRegionVolumeRequest(requeryAAIVolGrpNameResponse, heatStackId, namespace, modelCustomizationId) {
323                 String requestPayload = ""
324                 if (requeryAAIVolGrpNameResponse != null) {
325                         def groupId = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-id")
326                         def volumeName = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-name")
327                         def vnfType = utils.getNodeText(requeryAAIVolGrpNameResponse, "vnf-type")
328                         def resourceVersion = utils.getNodeText(requeryAAIVolGrpNameResponse, "resource-version")
329                         def relationshipList = ""
330                         if (utils.nodeExists(requeryAAIVolGrpNameResponse, "relationship")) {
331                                 relationshipList = rebuildRelationship(requeryAAIVolGrpNameResponse)
332                         }
333
334                         requestPayload =
335                                 """<volume-group xmlns="${namespace}">
336                                         <volume-group-id>${MsoUtils.xmlEscape(groupId)}</volume-group-id>
337                                         <volume-group-name>${MsoUtils.xmlEscape(volumeName)}</volume-group-name>
338                                         <heat-stack-id>${MsoUtils.xmlEscape(heatStackId)}</heat-stack-id>
339                                         <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
340                                         <orchestration-status>Active</orchestration-status>
341                                         <resource-version>${MsoUtils.xmlEscape(resourceVersion)}</resource-version>
342                                         <vf-module-model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</vf-module-model-customization-id>
343                                         ${relationshipList}
344                                  </volume-group>"""
345                 }
346
347                 return requestPayload
348         }
349
350
351         /**
352          * This method returns the string for Update Volume Request payload
353          * @param requeryAAIVolGrpNameResponse the response of query volume group name (in AAI)
354          * @param heatStackId the value of heat stack id
355          * @return String request payload
356          */
357         def String UpdateNetworkVolumeRequest(requeryAAIVolGrpNameResponse, heatStackId) {
358                 String requestPayload = ""
359                 if (requeryAAIVolGrpNameResponse != null) {
360                         def groupId = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-id")
361                         def volumeName = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-name")
362                         def vnfType = utils.getNodeText(requeryAAIVolGrpNameResponse, "vnf-type")
363                         def resourceVersion = utils.getNodeText(requeryAAIVolGrpNameResponse, "resource-version")
364                         def relationshipList = ""
365                         if (utils.nodeExists(requeryAAIVolGrpNameResponse, "relationship")) {
366                                 relationshipList = rebuildRelationship(requeryAAIVolGrpNameResponse)
367                         }
368
369                         requestPayload =
370                                 """<volume-group xmlns="http://org.onap.so/v6">
371                                         <volume-group-id>${MsoUtils.xmlEscape(groupId)}</volume-group-id>
372                                         <volume-group-name>${MsoUtils.xmlEscape(volumeName)}</volume-group-name>
373                                         <heat-stack-id>${MsoUtils.xmlEscape(heatStackId)}</heat-stack-id>
374                                         <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
375                                         <orchestration-status>Active</orchestration-status>
376                                         <resource-version>${MsoUtils.xmlEscape(resourceVersion)}</resource-version>
377                                         ${relationshipList}
378                                  </volume-group>"""
379                 }
380
381                 return requestPayload
382         }
383
384         /**
385          * This method returns the string for Create Contrail Network payload
386          * @param requeryIdAAIResponse the response from AAI query by id
387          * @param createNetworkResponse the response of create network
388          * @return String contrailNetworkCreatedUpdate
389          */
390         def ContrailNetworkCreatedUpdate(requeryIdAAIResponse, createNetworkResponse, schemaVersion) {
391
392                 String contrailNetworkCreatedUpdate = ""
393                 if(requeryIdAAIResponse!=null && createNetworkResponse!=null) {
394
395                         def l3Network = utils.getNodeXml(requeryIdAAIResponse, "l3-network", false).replace("tag0:","").replace(":tag0","")
396                         def createNetworkContrailResponse = ""
397                         if (utils.nodeExists(createNetworkResponse, 'createNetworkResponse')) {
398                            createNetworkContrailResponse = utils.getNodeXml(createNetworkResponse, "createNetworkResponse", false).replace("tag0:","").replace(":tag0","")
399                         } else {
400                            createNetworkContrailResponse = utils.getNodeXml(createNetworkResponse, "updateNetworkContrailResponse", false).replace("tag0:","").replace(":tag0","")
401                         }
402
403                         // rebuild network
404                         def networkList = ["network-id", "network-name", "network-type", "network-role", "network-technology", "neutron-network-id", "is-bound-to-vpn", "service-id", "network-role-instance", "resource-version", "resource-model-uuid", "orchestration-status", "heat-stack-id", "mso-catalog-key", "contrail-network-fqdn",
405                                                              "physical-network-name", "is-provider-network", "is-shared-network", "is-external-network"]
406                         String rebuildNetworkElements = buildNetworkElements(l3Network, createNetworkContrailResponse, networkList)
407
408                         // rebuild 'subnets'
409                         def rebuildSubnetList = ""
410                         if (utils.nodeExists(requeryIdAAIResponse, 'subnet')) {
411                              rebuildSubnetList = buildSubnets(requeryIdAAIResponse, createNetworkResponse)
412                         }
413
414                         // rebuild 'segmentation-assignments'
415                         def rebuildSegmentationAssignments = ""
416                         if (utils.nodeExists(requeryIdAAIResponse, 'segmentation-assignments')) {
417                                 List elementList = ["segmentation-id", "resource-version"]
418                                 if (utils.nodeExists(requeryIdAAIResponse, 'segmentation-assignment')) {  // new tag
419                                     rebuildSegmentationAssignments =  buildXMLElements(requeryIdAAIResponse, "segmentation-assignments", "segmentation-assignment", elementList)
420                                 } else {
421                                    rebuildSegmentationAssignments =  buildXMLElements(requeryIdAAIResponse, "", "segmentation-assignments", elementList)
422                                 }
423                         }
424
425                         // rebuild 'ctag-assignments' / rebuildCtagAssignments
426                         def rebuildCtagAssignmentsList = ""
427                         if (utils.nodeExists(requeryIdAAIResponse, 'ctag-assignment')) {
428                                 rebuildCtagAssignmentsList = rebuildCtagAssignments(requeryIdAAIResponse)
429                         }
430
431                         // rebuild 'relationship'
432                         def relationshipList = ""
433                         if (utils.nodeExists(requeryIdAAIResponse, 'relationship-list')) {
434                                 String rootRelationshipData = getFirstNodeXml(requeryIdAAIResponse, "relationship-list").drop(38).trim().replace("tag0:","").replace(":tag0","")
435                                 if (utils.nodeExists(rootRelationshipData, 'relationship')) {
436                                         relationshipList = rebuildRelationship(rootRelationshipData)
437                                 }
438                         }
439
440                         //Check for optional contrail network fqdn within CreateNetworkResponse
441                         String contrailNetworkFQDN
442                         if(utils.nodeExists(createNetworkResponse, "contrail-network-fqdn")){
443                                 contrailNetworkFQDN = utils.getNodeXml(createNetworkResponse, "contrail-network-fqdn")
444                                 contrailNetworkFQDN = utils.removeXmlNamespaces(contrailNetworkFQDN)
445                                 contrailNetworkFQDN = utils.removeXmlPreamble(contrailNetworkFQDN)
446                         }else{
447                                 contrailNetworkFQDN = ""
448                         }
449
450                         contrailNetworkCreatedUpdate =
451                                  """<l3-network xmlns="${schemaVersion}">
452                                                 ${rebuildNetworkElements}
453                                                 ${rebuildSubnetList}
454                                                 ${rebuildSegmentationAssignments}
455                                                 ${rebuildCtagAssignmentsList}
456                                                 ${relationshipList}
457                                                 ${contrailNetworkFQDN}
458                                       </l3-network>""".trim()
459
460                 }
461                         return contrailNetworkCreatedUpdate
462         }
463
464
465
466         /**
467          * This method returns the value for the name paramName.
468          *   Ex:   <network-params>
469          *            <param name="shared">1</param>
470          *            <param name="external">0</external>
471          *         </network-params>
472          *
473          * @param xmlInput the XML document
474          * @param paramName the param name (ex: 'shared')
475          * @return a param value for 'shared' (ex: '1')
476          */
477         def getParameterValue(xmlInput, paramName) {
478                 def rtn=""
479                 if(xmlInput!=null){
480                         def xml= new XmlSlurper().parseText(xmlInput)
481                         rtn= xml.'**'.find {param->param.'@name'.text() == paramName}
482                 }
483                 if (rtn==null) {
484                         return ""
485                 } else {
486                    return rtn
487                 }
488         }
489
490         /**
491          * This method returns the name of param if found/match with paramName.
492          *   Ex:   <network-params>
493          *            <param name="shared">1</param>
494          *            <param name="external">0</external>
495          *         </network-params>
496          *
497          * @param xmlInput the XML document
498          * @param paramName the param name (ex: 'shared', )
499          * @return a param name for 'shared' (ex: 'shared' if found)
500          */
501         def getParameterName(xmlInput, paramName) {
502                 def rtn=""
503                 if(xmlInput!=null){
504                         def xml= new XmlSlurper().parseText(xmlInput)
505                         try {
506                                 rtn= xml.'**'.find {param->param.'@name' == paramName}.'@name'
507                         } catch (Exception ex) {
508                             rtn=""
509                         }
510                 }
511                 if (rtn==null || rtn=="") {
512                         return ""
513                 } else {
514                    return rtn
515                 }
516         }
517
518         /**
519          * This method returns the networkParams xml string.
520          *   Ex: input:
521          *         <network-params>
522          *            <param name="shared">1</param>
523          *            <param name="external">0</external>
524          *         </network-params>
525          *
526          *   Sample result:
527          *         <networkParams>
528      *            <shared>1</shared>
529      *            <external>0</external>
530      *         </networkParams>
531      *
532          */
533
534         def buildParams(networkParams) {
535                 def build = ""
536                         def netParams = new XmlParser().parseText(networkParams)
537                         try {
538                                 def paramsList = netParams.'**'.findAll {param->param.'@name'}.'@name'
539                                 if (paramsList.size() > 0) {
540                                         build += "<networkParams>"
541                                         for (i in 0..paramsList.size()-1) {
542                         def name = netParams.'**'.find {param->param.'@name' == paramsList[i]}.'@name'
543                                                 def value= netParams.'**'.find {param->param.'@name' == paramsList[i]}.text()
544                                                 build += "<${name}>${MsoUtils.xmlEscape(value)}</${name}>"
545                                         }
546                                         build += "</networkParams>"
547                                 }
548
549                         } catch (Exception ex) {
550                                 println ' buildParams error - ' + ex.getMessage()
551                                 build = ""
552                         }
553                 return build
554         }
555
556         def getVlans(xmlInput) {
557                 def rtn = ""
558                 if (xmlInput!=null) {
559                         def vlansList = getListWithElements(xmlInput, 'vlans')
560                         def vlansListSize = vlansList.size()
561                         if (vlansListSize > 0) {
562                                 for (i in 0..vlansListSize-1) {
563                                    rtn += '<vlans>'+vlansList[i]+'</vlans>'
564                                 }
565                         }
566                 }
567                 return rtn
568
569
570         }
571
572         /**
573          * This method returns the uri value for the vpn bindings.
574          * Return the a list of value of vpn binding in the <related-link> string.
575          * Ex.
576          *   <relationship-list>
577          *      <relationship>
578          *          <related-to>vpn-binding</related-to>
579          *          <related-link>https://aai-app-e2e.test.openecomp.com:8443/aai/v6/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link>
580          *          <relationship-data>
581          *             <relationship-key>vpn-binding.vpn-id</relationship-key>
582          *             <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value>
583          *          </relationship-data>
584          *       </relationship>
585          *              <relationship>
586          *              <related-to>vpn-binding</related-to>
587          *                      <related-link>https://aai-ext1.test.openecomp.com:8443/aai/v6/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link>
588          *                      <relationship-data>
589          *                         <relationship-key>vpn-binding.vpn-id</relationship-key>
590          *                         <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value>
591          *                  </relationship-data>
592          *                      <related-to-property>
593          *                        <property-key>vpn-binding.vpn-name</property-key>
594          *                        <property-value>oam_protected_net_6_MTN5_msotest1</property-value>
595          *                      </related-to-property>
596          *              </relationship>
597          * @param xmlInput the XML document
598          * @return a list of vpn binding values
599          *            ex: ['aai/v6/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', 'aai/v6/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']
600          *
601          **/
602         def getVnfBindingObject(xmlInput) {
603                 //def rtn = null
604                 List rtn = []
605                 if (xmlInput!=null) {
606                         def relationshipList = getListWithElements(xmlInput, 'relationship')
607                         def relationshipListSize = relationshipList.size()
608                         if (relationshipListSize > 0) {
609                                 for (i in 0..relationshipListSize-1) {
610                                    def relationshipXml = XmlUtil.serialize(relationshipList[i])
611                                    if (utils.getNodeText(relationshipXml, 'related-to') == "vpn-binding") {
612                                           def relatedLink = utils.getNodeText(relationshipXml, 'related-link')
613                                           if (relatedLink != null || relatedLink != "") {
614                                                  rtn.add(relatedLink.substring(relatedLink.indexOf("/aai/"), relatedLink.length()))
615                                           }
616                                    }
617                                 }
618                         }
619                 }
620                 return rtn
621         }
622         /**
623          * similar to VNF bindings method
624         * @param xmlInput the XML document
625         * @return a list of network policy values
626         *            ex: ['aai/v$/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg', 'aai/v$/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg']
627         *
628         **/
629         def getNetworkPolicyObject(xmlInput) {
630                 //def rtn = null
631                 List rtn = []
632                 if (xmlInput!=null) {
633                         def relationshipList = getListWithElements(xmlInput, 'relationship')
634                         def relationshipListSize = relationshipList.size()
635                         if (relationshipListSize > 0) {
636                                 for (i in 0..relationshipListSize-1) {
637                                    def relationshipXml = XmlUtil.serialize(relationshipList[i])
638                                    if (utils.getNodeText(relationshipXml, 'related-to') == "network-policy") {
639                                           def relatedLink = utils.getNodeText(relationshipXml, 'related-link')
640                                           if (relatedLink != null || relatedLink != "") {
641                                                  rtn.add(relatedLink.substring(relatedLink.indexOf("/aai/"), relatedLink.length()))
642                                           }
643                                    }
644                                 }
645                         }
646                 }
647                 return rtn
648         }
649
650         /**
651          * similar to network policymethod
652         * @param xmlInput the XML document
653         * @return a list of network policy values
654         *            ex: ['aai/v$/network/route-table-references/route-table-reference/refFQDN1', 'aai/v$/network/route-table-references/route-table-reference/refFQDN2']
655         *
656         **/
657         def getNetworkTableRefObject(xmlInput) {
658                 //def rtn = null
659                 List rtn = []
660                 if (xmlInput!=null) {
661                         def relationshipList = getListWithElements(xmlInput, 'relationship')
662                         def relationshipListSize = relationshipList.size()
663                         if (relationshipListSize > 0) {
664                                 for (i in 0..relationshipListSize-1) {
665                                    def relationshipXml = XmlUtil.serialize(relationshipList[i])
666                                    if (utils.getNodeText(relationshipXml, 'related-to') == "route-table-reference") {
667                                           def relatedLink = utils.getNodeText(relationshipXml, 'related-link')
668                                           if (relatedLink != null || relatedLink != "") {
669                                                  rtn.add(relatedLink.substring(relatedLink.indexOf("/aai/"), relatedLink.length()))
670                                           }
671                                    }
672                                 }
673                         }
674                 }
675                 return rtn
676         }
677
678         /**
679          * similar to network policymethod
680         * @param xmlInput the XML document
681         * @return a list of IDs for related VNF instances
682         *
683         **/
684         def getRelatedVnfIdList(xmlInput) {
685                 //def rtn = null
686                 List rtn = []
687                 if (xmlInput!=null) {
688                         def relationshipList = getListWithElements(xmlInput, 'relationship')
689                         def relationshipListSize = relationshipList.size()
690                         if (relationshipListSize > 0) {
691                                 for (i in 0..relationshipListSize-1) {
692                                    def relationshipXml = XmlUtil.serialize(relationshipList[i])
693                                    if (utils.getNodeText(relationshipXml, 'related-to') == "generic-vnf") {
694                                           def relatedLink = utils.getNodeText(relationshipXml, 'related-link')
695                                           if (relatedLink != null || relatedLink != "") {
696                                                  if (relatedLink.substring(relatedLink.indexOf("/generic-vnf/")+13, relatedLink.length()).contains('/')) {
697                                                          rtn.add(relatedLink.substring(relatedLink.indexOf("/generic-vnf/")+13, relatedLink.length()-1))
698                                                  } else {
699                                                      rtn.add(relatedLink.substring(relatedLink.indexOf("/generic-vnf/")+13, relatedLink.length()))
700                                                  }
701                                           }
702                                    }
703                                 }
704                         }
705                 }
706                 return rtn
707         }
708
709         /**
710          * similar to network policymethod
711         * @param xmlInput the XML document
712         * @return a list of IDs for related Network instances
713         *
714         **/
715         def getRelatedNetworkIdList(xmlInput) {
716                 //def rtn = null
717                 List rtn = []
718                 if (xmlInput!=null) {
719                         def relationshipList = getListWithElements(xmlInput, 'relationship')
720                         def relationshipListSize = relationshipList.size()
721                         if (relationshipListSize > 0) {
722                                 for (i in 0..relationshipListSize-1) {
723                                    def relationshipXml = XmlUtil.serialize(relationshipList[i])
724                                    if (utils.getNodeText(relationshipXml, 'related-to') == "l3-network") {
725                                           def relatedLink = utils.getNodeText(relationshipXml, 'related-link')
726                                           if (relatedLink != null || relatedLink != "") {
727                                                  if (relatedLink.substring(relatedLink.indexOf("/l3-network/")+12, relatedLink.length()).contains('/')) {
728                                                          rtn.add(relatedLink.substring(relatedLink.indexOf("/l3-network/")+12, relatedLink.length()-1))
729                                                  } else {
730                                                      rtn.add(relatedLink.substring(relatedLink.indexOf("/l3-network/")+12, relatedLink.length()))
731                                                  }
732                                           }
733                                    }
734                                 }
735                         }
736                 }
737                 return rtn
738         }
739
740
741         def isInstanceValueMatch(linkResource, globalSubscriberId, serviceType) {
742                 Boolean rtn = false
743                 try {
744                         String globalSubscriberIdLink = linkResource.substring(linkResource.indexOf("/customer/")+10, linkResource.indexOf("/service-subscriptions"))
745                         String serviceTypeLink = linkResource.substring(linkResource.indexOf("/service-subscription/")+22, linkResource.indexOf("/service-instances"))
746                         if (globalSubscriberIdLink == globalSubscriberId) {
747                                         rtn = true
748                         } else {
749                                 if (serviceTypeLink == serviceType) {
750                                         rtn = true
751                                 }
752                         }
753
754                 } catch (Exception ex) {
755                     println 'Exception - ' + ex.getMessage()
756                         return false
757                 }
758         return rtn
759         }
760
761         def getListWithElements(xmlInput, groupName) {
762                 def rtn = ""
763                 if (xmlInput != null) {
764                         def relationshipData = new XmlSlurper().parseText(xmlInput)
765                         rtn = relationshipData.'**'.findAll {it.name() == groupName}
766                 }
767                 return rtn
768
769         }
770
771         // build network single elements
772         def buildNetworkElements(l3Network, createNetworkContrailResponse, networkList) {
773                 def replaceNetworkId = ""
774                 def replaceNeutronNetworkId = ""
775                 def replaceContrailNetworkFqdn = ""
776                 if (l3Network != null && createNetworkContrailResponse != null) {
777                         if (utils.nodeExists(l3Network, 'heat-stack-id')) {
778                                 replaceNetworkId = utils.getNodeText(l3Network, 'heat-stack-id')
779                         } else {
780                                 if (utils.nodeExists(createNetworkContrailResponse, 'networkStackId')) {
781                                         replaceNetworkId = utils.getNodeText(createNetworkContrailResponse, 'networkStackId')
782                                 }
783                         }
784                         if (utils.nodeExists(l3Network, 'neutron-network-id')) {
785                                 replaceNeutronNetworkId = utils.getNodeText(l3Network, 'neutron-network-id')
786                         } else {
787                                 if (utils.nodeExists(createNetworkContrailResponse, 'neutronNetworkId')) {
788                                         replaceNeutronNetworkId = utils.getNodeText(createNetworkContrailResponse, 'neutronNetworkId')
789                                 }
790                         }
791                         if (utils.nodeExists(l3Network, 'contrail-network-fqdn')) {
792                                 replaceContrailNetworkFqdn = utils.getNodeText(l3Network, 'contrail-network-fqdn')
793                         } else {
794                                 if (utils.nodeExists(createNetworkContrailResponse, 'networkFqdn')) {
795                                         replaceContrailNetworkFqdn = utils.getNodeText(createNetworkContrailResponse, 'networkFqdn')
796                                 }
797                         }
798                 }
799
800                 String var = ""
801                 def xmlNetwork = ""
802                 if (l3Network != null) {
803                         for (element in networkList) {
804                                 def xml= new XmlSlurper().parseText(l3Network)
805                                 var = xml.'**'.find {it.name() == element}
806                                 if (var == null) {
807                                         if (element=="orchestration-status") {
808                                                 if (var.toString() == 'pending-create' || var.toString() == 'PendingCreate') {
809                                                         xmlNetwork += "<"+element+">"+"Created"+"</"+element+">"
810                                             } else { //pending-update or PendingUpdate
811                                                         xmlNetwork += "<"+element+">"+"Active"+"</"+element+">"
812                                             }
813                                         }
814                                         if (element=="heat-stack-id") {
815                                                 if (replaceNetworkId != "") {
816                                                         xmlNetwork += "<"+element+">"+replaceNetworkId+"</"+element+">"
817                                                 }
818                                         }
819                                         if (element=="neutron-network-id") {
820                                                 if (replaceNeutronNetworkId != "") {
821                                                         xmlNetwork += "<"+element+">"+replaceNeutronNetworkId+"</"+element+">"
822                                                 }
823                                         }
824                                         if (element=="contrail-network-fqdn") {
825                                                 if (replaceContrailNetworkFqdn != "") {
826                                                         xmlNetwork += "<"+element+">"+replaceContrailNetworkFqdn+"</"+element+">"
827                                                 }
828                                         }
829
830                                 } else {
831                                         if (element=="orchestration-status") {
832                                            if (element=="orchestration-status") {
833                                                   if (var.toString() == 'pending-create' || var.toString() == 'PendingCreate') {
834                                                       xmlNetwork += "<"+element+">"+"Created"+"</"+element+">"
835                                                   } else { //pending-update or PendingUpdate
836                                                           xmlNetwork += "<"+element+">"+"Active"+"</"+element+">"
837                                                   }
838                                            }
839                                     } else {
840                                     xmlNetwork += "<"+element+">"+var.toString()+"</"+element+">"
841                                         }
842                                 }
843                          }
844                 }
845                 return xmlNetwork
846         }
847
848         def buildSubnets(requeryIdAAIResponse, createNetworkResponse) {
849                 def rebuildingSubnets = ""
850                 if (requeryIdAAIResponse != null && utils.nodeExists(requeryIdAAIResponse, 'subnets')) {
851                         def subnetIdMapValue = ""
852                         def subnetsGroup = utils.getNodeXml(requeryIdAAIResponse, "subnets", false)
853                         def subnetsData = new XmlSlurper().parseText(subnetsGroup)
854                         rebuildingSubnets += "<subnets>"
855                         try {
856                                 def subnets = subnetsData.'**'.findAll {it.name() == "subnet"}
857                                 def subnetsSize = subnets.size()
858                                 for (i in 0..subnetsSize-1) {
859                                    def subnet = subnets[i]
860                                    def subnetXml = XmlUtil.serialize(subnet)
861                                    def orchestrationStatus = utils.getNodeText(subnetXml, "orchestration-status")
862                                    if (orchestrationStatus == "PendingDelete" || orchestrationStatus == "pending-delete") {
863                                            // skip, do not include in processing, remove!!!
864                                    } else {
865                                       def subnetList = ["subnet-id", "neutron-subnet-id", "gateway-address", "network-start-address", "cidr-mask", "ip-version", "orchestration-status", "dhcp-enabled", "dhcp-start", "dhcp-end", "subnet-role", "resource-version", "subnet-name", "ip-assignment-direction", "host-routes"]
866                                       rebuildingSubnets += buildSubNetworkElements(subnetXml, createNetworkResponse, subnetList, "subnet")
867                                    }
868                                 }
869                                 if (utils.nodeExists(subnetsData, 'relationship')) {
870                                         rebuildingSubnets = rebuildRelationship(requeryIdAAIResponse)
871                                 }
872
873                         } catch (Exception ex) {
874                                 // error
875                         } finally {
876                                 rebuildingSubnets += "</subnets>"
877                         }
878                 }
879                 return rebuildingSubnets
880         }
881
882         def buildSubnets(L3Network network) {
883                 def rebuildingSubnets = ""
884                 Subnets subnets = network.getSubnets()
885                 try{
886                         for(Subnet s : subnets.getSubnet()){
887                                 def orchestrationStatus = s.getOrchestrationStatus()
888                                 if (orchestrationStatus == "pending-delete" || orchestrationStatus == "PendingDelete") {
889                                         // skip, do not include in processing, remove!!!
890                                 } else {
891                                         def subnetList = ["dhcp-start", "dhcp-end", "network-start-address", "cidr-mask", "dhcp-enabled", "gateway-address", "ip-version", "subnet-id", "subnet-name", "ip-assignment-direction", "host-routes"]
892                                         rebuildingSubnets += buildSubNetworkElements(s, subnetList, "subnets")
893                                         //rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "")
894                                 }
895                         }
896                 } catch (Exception ex) {
897                         //
898                 } finally {
899                         //rebuildingSubnets += "</subnets>"
900                 }
901                 return rebuildingSubnets
902         }
903
904
905         // build subnet sub-network single elements
906         def buildSubNetworkElements(subnetXml, createNetworkResponse, elementList, parentName) {
907                 String var = ""
908                 def xmlBuild = ""
909                 if (parentName != "") {
910                    xmlBuild += "<"+parentName+">"
911                 }
912                 if (subnetXml != null) {
913                         for (element in elementList) {
914                           def xml= new XmlSlurper().parseText(subnetXml)
915                           var = xml.'**'.find {it.name() == element}
916                           if (var != null) {
917                                  if (element=="orchestration-status") {
918                                         if(var.toString() == 'pending-create' || var.toString() == 'PendingCreate') {
919                                                 xmlBuild += "<"+element+">"+"Created"+"</"+element+">"
920                                         } else { // pending-update or PendingUpdate'
921                                            xmlBuild += "<"+element+">"+"Active"+"</"+element+">"
922                                         }
923                                  } else { // "subnet-id", "neutron-subnet-id"
924                                          if (element=="subnet-id") {
925                                                  if (utils.nodeExists(createNetworkResponse, "subnetMap")) {
926                                                          xmlBuild += "<"+element+">"+var.toString()+"</"+element+">"
927                                                          String neutronSubnetId = extractNeutSubId(createNetworkResponse, var.toString())
928                                                          xmlBuild += "<neutron-subnet-id>"+neutronSubnetId+"</neutron-subnet-id>"
929                                                  }
930                                          } else {
931                                              if (element=="neutron-subnet-id") {
932                                // skip
933                                                  } else {
934                                                          if (element=="host-routes") {
935                                                                  if (subnetXml.contains("host-routes")) {
936                                                                          List elementRoute = ["host-route-id", "route-prefix", "next-hop", "next-hop-type", "resource-version"]
937                                                                          xmlBuild += buildXMLElements(subnetXml, "host-routes", "host-route", elementRoute)
938                                                                  }
939                                                          } else {
940                                                                 xmlBuild += "<"+element+">"+var.toString()+"</"+element+">"
941                                                          }
942                                                  }
943                                          }
944                                  }
945                           }
946                         }
947
948                 }
949                 if (parentName != "") {
950                    xmlBuild += "</"+parentName+">"
951                 }
952                 return xmlBuild
953         }
954
955         // build subnet sub-network single elements
956         def buildSubNetworkElements(Subnet subnet, elementList, parentName) {
957
958                 def var = ""
959                 def xmlBuild = ""
960                 if (parentName != "") {
961                         xmlBuild += "<"+parentName+">"
962                  }
963                 if (subnet != null) {
964                     def networkStartAddress = ""
965                         for (element in elementList) {
966                                 if (element == "dhcp-start") {
967                                         var = subnet.getDhcpStart()
968                                         xmlBuild += "<allocationPools>"
969                                         if (var == null) {
970                                                 xmlBuild += "<start>"+""+"</start>"
971                                         } else {
972                                                 xmlBuild += "<start>"+var+"</start>"
973                                         }
974                                 }
975                                 if (element == "dhcp-end") {
976                                         var = subnet.getDhcpEnd()
977                                         if (var == null) {
978                                                 xmlBuild += "<end>"+""+"</end>"
979                                         } else {
980                                                 xmlBuild += "<end>"+var+"</end>"
981                                         }
982                                         xmlBuild += "</allocationPools>"
983                                 }
984                                 if (element == "network-start-address" || element == "cidr-mask") {
985                                         if (element == "network-start-address") {
986                                                 networkStartAddress = subnet.getNetworkStartAddress()
987                                         }
988                                         if (element == "cidr-mask") {
989                                                 xmlBuild += "<cidr>"+networkStartAddress+"/"+var+"</cidr>"
990                                         }
991                                 }
992                                 if (element == "dhcp-enabled") {
993                                         xmlBuild += "<enableDHCP>"+subnet.isDhcpEnabled()+"</enableDHCP>"
994                                 }
995                                 if (element == "gateway-address") {
996                                         xmlBuild += "<gatewayIp>"+subnet.getGatewayAddress()+"</gatewayIp>"
997                                 }
998                                 if (element == "ip-version") {
999                                         String ipVersion = getIpvVersion(subnet.getIpVersion())
1000                                         xmlBuild += "<ipVersion>"+ipVersion+"</ipVersion>"
1001                                 }
1002                                 if (element == "subnet-id") {
1003                                         xmlBuild += "<subnetId>"+subnet.getSubnetId()+"</subnetId>"
1004                                 }
1005                                 if ((element == "subnet-name") && (subnet.getSubnetName() != null)) {
1006                                         xmlBuild += "<subnetName>"+subnet.getSubnetName()+"</subnetName>"
1007                                 }
1008                                 if ((element == "ip-assignment-direction") && (subnet.getIpAssignmentDirection() != null)) {
1009                                         xmlBuild += "<addrFromStart>"+subnet.getIpAssignmentDirection()+"</addrFromStart>"
1010                                 }
1011                                 if (element == "host-routes") {
1012                                         def routes = ""
1013                                         if (subnet.getHostRoutes() != null) {
1014                                                 routes = buildHostRoutes(subnet)
1015                                         }
1016                                         xmlBuild += routes
1017                                 }
1018
1019                         }
1020                 }
1021                 if (parentName != "") {
1022                         xmlBuild += "</"+parentName+">"
1023                  }
1024                 return xmlBuild
1025         }
1026
1027         // rebuild host-routes
1028         def buildHostRoutes(subnetXml) {
1029                 List  routeElementList = ["host-route-id", "route-prefix", "next-hop", "next-hop-type", "resource-version"]
1030                 def hostRoutes = buildXMLElements(subnetXml, "host-routes", "host-route", routeElementList)
1031                 def buildHostRoutes = ""
1032                 def var = ""
1033                 if (hostRoutes!=null) {
1034                         def routesData = new XmlSlurper().parseText(hostRoutes)
1035                         def routes = routesData.'**'.findAll {it.name() == "host-route"}
1036                         def routesSize = routes.size()
1037                         for (i in 0..routesSize-1) {
1038                            buildHostRoutes += "<hostRoutes>"
1039                            def route = routes[i]
1040                            def routeXml = XmlUtil.serialize(route)
1041                            List  elementList = ["route-prefix", "next-hop"]
1042                            for (element in elementList) {
1043                                    def xml= new XmlSlurper().parseText(routeXml)
1044                                    var = xml.'**'.find {it.name() == element}
1045                                    if (element == "route-prefix") {
1046                                            buildHostRoutes += "<prefix>"+var.toString()+"</prefix>"
1047                                    }
1048                                    if (element == "next-hop") {
1049                                            buildHostRoutes += "<nextHop>"+var.toString()+"</nextHop>"
1050                                    }
1051                            }
1052                            buildHostRoutes += "</hostRoutes>"
1053                         }
1054                 }
1055                 return buildHostRoutes
1056
1057         }
1058
1059         // rebuild ctag-assignments
1060         def rebuildCtagAssignments(xmlInput) {
1061                 def rebuildingCtagAssignments = ""
1062                 if (xmlInput!=null) {
1063                         def ctagAssignmentsData = new XmlSlurper().parseText(xmlInput)
1064                         rebuildingCtagAssignments += "<ctag-assignments>"
1065                         def ctagAssignments = ctagAssignmentsData.'**'.findAll {it.name() == "ctag-assignment"}
1066                         def ctagAssignmentsSize = ctagAssignments.size()
1067                         for (i in 0..ctagAssignmentsSize-1) {
1068                                 def ctagAssignment = ctagAssignments[i]
1069                                 def ctagAssignmentXml = XmlUtil.serialize(ctagAssignment)
1070                                 rebuildingCtagAssignments += "<ctag-assignment>"
1071                                 List elementList = ["vlan-id-inner", "resource-version"]
1072                                 rebuildingCtagAssignments +=  buildXMLElements(ctagAssignmentXml, ""      , "", elementList)
1073                                 if (utils.nodeExists(ctagAssignmentXml, 'relationship')) {
1074                                         rebuildingCtagAssignments += rebuildRelationship(ctagAssignmentXml)
1075                                 }
1076                                 rebuildingCtagAssignments += "</ctag-assignment>"
1077                         }
1078                         rebuildingCtagAssignments += "</ctag-assignments>"
1079                 }
1080                 return rebuildingCtagAssignments
1081         }
1082
1083         // rebuild 'relationship-list'
1084         def rebuildRelationship(xmlInput) {
1085                 def rebuildingSubnets = ""
1086                 if (xmlInput!=null) {
1087                         def subnetsData = new XmlSlurper().parseText(xmlInput)
1088                         rebuildingSubnets += "<relationship-list>"
1089                         def relationships = subnetsData.'**'.findAll {it.name() == "relationship"}
1090                         def relationshipsSize = relationships.size()
1091                         for (i in 0..relationshipsSize-1) {
1092                                 def relationship = relationships[i]
1093                                 def relationshipXml = XmlUtil.serialize(relationship)
1094                                 rebuildingSubnets += "<relationship>"
1095                                 def relationshipList = ["related-to", "related-link"]
1096                                 rebuildingSubnets += buildSubNetworkElements(relationshipXml, "", relationshipList, "")
1097                                 if (utils.nodeExists(relationshipXml, 'relationship-data')) {
1098                                         def relationshipDataXmlData = new XmlSlurper().parseText(relationshipXml)
1099                                         def relationshipsData = relationshipDataXmlData.'**'.findAll {it.name() == "relationship-data"}
1100                                         def relationshipsDataSize = relationshipsData.size()
1101                                         for (j in 0..relationshipsDataSize-1) {
1102                                                 def relationshipData = relationshipsData[j]
1103                                                 def relationshipDataXml = XmlUtil.serialize(relationshipData)
1104                                                 def relationshipDataList =  ["relationship-key", "relationship-value"]
1105                                                 rebuildingSubnets += buildXMLElements(relationshipDataXml, "", "relationship-data", relationshipDataList)
1106                                         }
1107                                 }
1108                                 if (utils.nodeExists(relationshipXml, 'related-to-property')) {
1109                                         def relationshipDataXmlData = new XmlSlurper().parseText(relationshipXml)
1110                                         def relationshipsData = relationshipDataXmlData.'**'.findAll {it.name() == "related-to-property"}
1111                                         def relationshipsDataSize = relationshipsData.size()
1112                                         for (j in 0..relationshipsDataSize-1) {
1113                                                 def relationshipData = relationshipsData[j]
1114                                                 def relationshipDataXml = XmlUtil.serialize(relationshipData)
1115                                                 def relationshipDataList =  ["property-key", "property-value"]
1116                                                 rebuildingSubnets += buildXMLElements(relationshipDataXml, "", "related-to-property", relationshipDataList)
1117                                         }
1118                                 }
1119
1120                                 rebuildingSubnets += "</relationship>"
1121                         }
1122                         rebuildingSubnets += "</relationship-list>"
1123                 }
1124                 return rebuildingSubnets
1125         }
1126
1127         def buildVlans(queryIdResponse) {
1128                 def rebuildingSubnets = "<vlans>"
1129                 def subnetsData = new XmlSlurper().parseText(queryIdResponse)
1130
1131                 try {
1132                         def subnets = subnetsData.'**'.findAll {it.name() == "segmentation-assignments"}
1133                         def subnetsSize = subnets.size()
1134                         for (i in 0..subnetsSize-1) {
1135                            def subnet = subnets[i]
1136                            def subnetXml = XmlUtil.serialize(subnet)
1137
1138                            String vlan = utils.getNodeText(subnetXml, "segmentation-id")
1139                            if (i>0){
1140                                    rebuildingSubnets += ","
1141                            }
1142                            rebuildingSubnets += vlan
1143                         }
1144                 } catch (Exception ex) {
1145                    //
1146                 } finally {
1147                   //rebuildingSubnets += "</subnets>"
1148                 rebuildingSubnets += "</vlans>"
1149                 }
1150                 return rebuildingSubnets
1151         }
1152
1153         /* Utility code to rebuild xml/elements in a list:
1154          * rebuild xml with 1) unbounded groups of elements; or
1155          *                  2) one group of elements; or
1156          *                  3) just one or more elements (in a list as argument)
1157          * @param xmlInput the XML document
1158          * @param parentName the parent name  (ex: 'inputs')
1159          * @param childrenName the chilrendName (ex: 'entry' as unbounded/occurs>1)
1160          * @param elementList the element list of children (ex: 'key', 'value')
1161          * @return a string of rebuild xml
1162          *
1163          * Ex 1: xmlInput:
1164          *    <ws:inputs>
1165          *       <ws:entry>
1166          *          <ws:key>name</ws:key>
1167          *          <ws:value>Edward</ws:value>
1168          *       </ws:entry>
1169          *       <ws:entry>
1170          *          <ws:key>age</ws:key>
1171          *          <ws:value>30</ws:value>
1172          *       </ws:entry>
1173          *       <ws:entry>
1174          *          <ws:key>age</ws:key>
1175          *          <ws:value>30</ws:value>
1176          *       </ws:entry>
1177          *    <ws:/inputs>
1178          * Usage:
1179          * List elementList = ["key", "value"]
1180          * String rebuild =  buildXMLElements(xmlInput, "inputs", "entry", elementList)
1181          *
1182          * Ex 2: xmlInput // no parent tag
1183          *   <ws:sdnc-request-header>
1184          *    <ws:svc-request-id>fec8ec88-151a-45c9-ad60-8233e0fc8ff2</ws:svc-request-id>
1185          *    <ws:svc-notification-url>https://localhost:8443/adapters/rest/SDNCNotify</ws:svc-notification-url>
1186          *    <ws:svc-action>assign</ws:svc-action>
1187          *   </ws:sdnc-request-header>
1188          * Usage:
1189          * List elementList = ["svc-request-id", "svc-notification-url", "svc-action"]
1190          * String rebuild =  buildXMLElements(xmlInput, ""      , "sdnc-request-header", elementList)  // no parent tag
1191          *
1192          * Ex 3: xmlInput // elements one after another (with no parent & children tag)
1193          * <ws:test-id>myTestid</ws:test-id>
1194          * <ws:test-user>myUser</ws:test-user>
1195          * Usage:
1196          * List elementList = ["test-id", "test-user"]
1197          * String rebuild =  buildXMLElements(xmlInput, ""      , "", elementList)
1198          *
1199          */
1200         def buildXMLElements(xmlInput, parentName, childrenName, elementList) {
1201                 def varChildren = ""
1202                 def var = ""
1203                 def xmlBuildUnbounded = ""
1204                 if (parentName!="") {xmlBuildUnbounded += "<"+parentName+">" +'\n'}
1205                 if (xmlInput != null) {
1206                         def xml= new XmlSlurper().parseText(xmlInput)
1207                         if (childrenName!="") {
1208                                 varChildren = xml.'**'.findAll {it.name() == childrenName}
1209                                 for (i in 0..varChildren.size()-1) {
1210                                         xmlBuildUnbounded += "<"+childrenName+">" +'\n'
1211                                         for (element in elementList) {
1212                                                 var = varChildren[i].'*'.find {it.name() == element}
1213                                            if (var != null) {
1214                                                   xmlBuildUnbounded += "<"+element+">"+var.toString()+"</"+element+">" +'\n'
1215                                            }
1216                                         }
1217                                         xmlBuildUnbounded += "</"+childrenName+">" +'\n'
1218                                 }
1219                         } else {
1220                                 for (element in elementList) {
1221                                         var = xml.'*'.find {it.name() == element}
1222                                         if (var != null) {
1223                                                 xmlBuildUnbounded += "<"+element+">"+var.toString()+"</"+element+">" +'\n'
1224                                         }
1225                                 }
1226                         }
1227
1228                 }
1229                 if (parentName!="") {xmlBuildUnbounded += "</"+parentName+">" +'\n'}
1230                 return xmlBuildUnbounded
1231          }
1232
1233         def getFirstNodeXml(xmlInput, element){
1234                 def nodeAsText = ""
1235                 def nodeToSerialize =  ""
1236                 if (xmlInput != null) {
1237                         def fxml= new XmlSlurper().parseText(xmlInput)
1238                         if (utils.nodeExists(xmlInput, "payload")) {
1239                                 nodeToSerialize = fxml.'payload'.'l3-network'.'*'.find {it.name() == element}
1240                                 if (nodeToSerialize!=null) {
1241                                         nodeAsText = XmlUtil.serialize(nodeToSerialize)
1242                                 } else {
1243                                     nodeAsText = ""
1244                                 }
1245
1246                         } else {
1247                                 nodeToSerialize = fxml.'*'.find {it.name() == element}
1248                                 if (nodeToSerialize!=null) {
1249                                         nodeAsText = XmlUtil.serialize(nodeToSerialize)
1250                                 } else {
1251                                         nodeAsText = ""
1252                                 }
1253
1254                         }
1255                 }
1256                 return nodeAsText
1257
1258         }
1259
1260 //TODO: This method still needs to be tested before using.
1261         /**
1262          *
1263          * This method is similar to the gennetwork:ContrailNetworUpdateCompletedObject
1264          * BPEL method.  It extracts all of the required subnet information
1265          * for each subnet listed with an orch status equal to the one provided
1266          * and puts the corresponding infomation with the appropriate node for
1267          * updating aai. The method sets the orch status for each subnet to active
1268          *
1269          * @param subnetsXml the entire subnets xml
1270          * @param requestInput the request in the process
1271          * @param queryIdResponse the response of REST AAI query by Id
1272          * @param queryVpnBindingResponse the response of REST AAI query by vpn binding
1273          * @param routeCollection the collection of vpnBinding's 'global-route-target'
1274          * @return String request
1275          */
1276         public String networkUpdateSubnetInfo(String subnetsXml, String networkResponseXml){
1277
1278                         String subnets = ""
1279                         StringBuilder sb = new StringBuilder()
1280                         InputSource source = new InputSource(new StringReader(subnetsXml));
1281                         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
1282                         docFactory.setNamespaceAware(true)
1283                         DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
1284                         Document xml = docBuilder.parse(source)
1285                         NodeList nodeList = xml.getElementsByTagNameNS("*", "subnet")
1286                         for (int x = 0; x < nodeList.getLength(); x++) {
1287                                 Node node = nodeList.item(x)
1288                                 String subnet = ""
1289                                 if (node.getNodeType() == Node.ELEMENT_NODE) {
1290                                         Element eElement = (Element) node
1291                                         String subnetOrchStatus = eElement.getElementsByTagNameNS("*", "orchestration-status").item(0).getTextContent()
1292                                         if(subnetOrchStatus.equals("pending-create")){
1293
1294                                                 String subnetId = eElement.getElementsByTagNameNS("*", "subnet-id").item(0).getTextContent()
1295                                                 def netAddress = eElement.getElementsByTagNameNS("*", "network-start-address").item(0).getTextContent()
1296                                                 def mask = eElement.getElementsByTagNameNS("*", "cidr-mask").item(0).getTextContent()
1297                                                 def dhcpEnabledSubnet = eElement.getElementsByTagNameNS("*", "dhcp-enabled").item(0).getTextContent()
1298                                                 def gatewayAddress = eElement.getElementsByTagNameNS("*", "gateway-address").item(0).getTextContent()
1299                                                 def ipVersion = eElement.getElementsByTagNameNS("*", "ip-version").item(0).getTextContent()
1300                                                 def relationshipList =  eElement.getElementsByTagNameNS("*", "relationship-list").item(0).getTextContent() //TODO: test this
1301                                                 String neutronSubnetId = extractNeutSubId(networkResponseXml, subnetId)
1302                                                 subnet =
1303                                                 """<subnet>
1304                                         <subnetId>${MsoUtils.xmlEscape(subnetId)}</subnetId>
1305                                         <neutron-subnet-id>${MsoUtils.xmlEscape(neutronSubnetId)}</neutron-subnet-id>
1306                                         <gateway-address>${MsoUtils.xmlEscape(gatewayAddress)}</gateway-address>
1307                                         <network-start-address>${MsoUtils.xmlEscape(netAddress)}</network-start-address>
1308                                         <cidr-mask>${MsoUtils.xmlEscape(mask)}</cidr-mask>
1309                                         <ip-Version>${MsoUtils.xmlEscape(ipVersion)}</ip-Version>
1310                                         <orchestration-status>active</orchestration-status>
1311                                         <dhcp-enabled>${MsoUtils.xmlEscape(dhcpEnabledSubnet)}</dhcp-enabled>
1312                                         <relationship-list>${relationshipList}</relationship-list>
1313                                         </subnet>"""
1314
1315                                         }else if(subnetOrchStatus.equals("pending-delete")){
1316                                                 StringWriter writer = new StringWriter()
1317                                                 Transformer transformer = TransformerFactory.newInstance().newTransformer()
1318                                                 transformer.transform(new DOMSource(node), new StreamResult(writer))
1319                                                 subnet = writer.toString()
1320
1321                                         }else{
1322                                                 subnet = ""
1323                                         }
1324                                 }
1325                                 subnets = sb.append(subnet)
1326                         }
1327
1328                         subnets = utils.removeXmlPreamble(subnets)
1329
1330                         String subnetsList =
1331                         """<subnets>
1332                         ${subnets}
1333                         </subnets>"""
1334
1335                         return subnetsList
1336         }
1337
1338
1339         /**
1340          *
1341          * This method extracts the "value" node text for the the given subnet Id.
1342          *
1343          * @param String inputSource - xml that contains the subnet id key and value
1344          * @param String subnetId - for which you want the value of
1345
1346          * @return String value - node text of node named value associated with the given subnet id
1347          */
1348         public String extractNeutSubId(String inputSource, String subnetId){
1349
1350                                 String value = ""
1351                                 InputSource source = new InputSource(new StringReader(inputSource));
1352                                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
1353                                 docFactory.setNamespaceAware(true)
1354                                 DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
1355                                 Document xml = docBuilder.parse(source)
1356                                 NodeList nodeList = xml.getElementsByTagNameNS("*", "entry")
1357                                 for (int x = 0; x < nodeList.getLength(); x++) {
1358                                         Node node = nodeList.item(x)
1359                                         String subnet = ""
1360                                         if (node.getNodeType() == Node.ELEMENT_NODE) {
1361                                                 Element eElement = (Element) node
1362                                                 String key = eElement.getElementsByTagNameNS("*", "key").item(0).getTextContent()
1363                                                 if(key.equals(subnetId)){
1364                                                         value = eElement.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1365                                                 }
1366                                         }
1367                                 }
1368                                 return value
1369                         }
1370
1371         public boolean isRollbackEnabled (DelegateExecution execution, String payloadXml) {
1372
1373                 def rollbackEnabled = false
1374                 def rollbackValueSet = false
1375                 if (utils.nodeExists(payloadXml, "backout-on-failure")) {
1376                         String backoutValue = utils.getNodeText(payloadXml, "backout-on-failure")
1377                         if (backoutValue != null && !backoutValue.isEmpty()) {
1378                                 if (backoutValue.equalsIgnoreCase("false")) {
1379                                         rollbackEnabled = false
1380                                 }
1381                                 else {
1382                                         rollbackEnabled = true
1383                                 }
1384                                 rollbackValueSet = true;
1385                         }
1386                 }
1387
1388                 if (!rollbackValueSet) {
1389
1390                         if (UrnPropertiesReader.getVariable("mso.rollback", execution) != null) {
1391                             rollbackEnabled = UrnPropertiesReader.getVariable("mso.rollback", execution).toBoolean()
1392                         }
1393                 }
1394                 return rollbackEnabled
1395         }
1396
1397
1398         /**
1399          * This method extracts the version for the the given ip-version.
1400          *
1401          * @param String ipvVersion - IP protocols version (ex: ipv4 or ipv6 or 4 or 6)
1402          * @return String version - digit version (ex: 4 or 6)
1403          */
1404
1405         public String getIpvVersion (String ipvVersion) {
1406
1407                 String version = ""
1408                 try {
1409                         if (ipvVersion.isNumber()) {
1410                                 version = ipvVersion
1411                         } else {
1412                                 version = ipvVersion.substring(ipvVersion.indexOf("ipv")+3)
1413                                 if (!version.isNumber()) {
1414                                         version = ipvVersion
1415                                 }
1416                         }
1417                 } catch (Exception ex) {
1418                         version = ipvVersion
1419                 }
1420                 return version
1421         }
1422 }