c1199aefd73d620a609acf476380cf5769fa8ea5
[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.HostRoute
26 import org.onap.aai.domain.yang.L3Network
27 import org.onap.aai.domain.yang.SegmentationAssignment
28 import org.onap.aai.domain.yang.Subnet
29 import org.onap.aai.domain.yang.Subnets
30 import org.onap.so.bpmn.core.UrnPropertiesReader
31 import org.w3c.dom.Document
32 import org.w3c.dom.Element
33 import org.w3c.dom.Node
34 import org.w3c.dom.NodeList
35 import org.xml.sax.InputSource
36
37 import javax.xml.parsers.DocumentBuilder
38 import javax.xml.parsers.DocumentBuilderFactory
39 import javax.xml.transform.Transformer
40 import javax.xml.transform.TransformerFactory
41 import javax.xml.transform.dom.DOMSource
42 import javax.xml.transform.stream.StreamResult
43
44 /**
45  * This groovy class supports the any Network processes that need the methods defined here.
46  */
47 class NetworkUtils {
48
49         public MsoUtils utils = new MsoUtils()
50         private AbstractServiceTaskProcessor taskProcessor
51
52         public NetworkUtils(AbstractServiceTaskProcessor taskProcessor) {
53                 this.taskProcessor = taskProcessor
54         }
55
56         /**
57          * This method returns the string for Network request
58          * V2 for Contrail 3.x will populate cloud-region data in same cloudSiteId filed
59          * Network adapter will handle it properly
60          * @param requestId either 'request-id' or 'mso-request-id'
61          * @param requestInput the request in the process
62          * @param queryIdResponse the response of REST AAI query by Id
63          * @param routeCollection the collection
64          * @param policyFqdns the policy
65          * @param tableCollection the collection
66          * @param cloudRegionId the cloud-region-region
67          * @return String request
68          */
69         def CreateNetworkRequestV2(execution, requestId, messageId, requestInput,L3Network queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) {
70                 String createNetworkRequest = null
71                 if(requestInput!=null && queryIdResponse!=null) {
72                                 String serviceInstanceId = ""
73                                 String sharedValue = ""
74                                 String externalValue = ""
75
76                                 if (source == "VID") {
77                                         sharedValue = queryIdResponse.isIsSharedNetwork() != null ? queryIdResponse.isIsSharedNetwork() : "false"
78                                         externalValue = queryIdResponse.isIsExternalNetwork() != null ? queryIdResponse.isIsExternalNetwork() : "false"
79                                         serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id")
80
81                                 } else { // source = 'PORTAL'
82                                         sharedValue = getParameterValue(requestInput, "shared")
83                                         externalValue = getParameterValue(requestInput, "external")
84                                         serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") != null ? utils.getNodeText(requestInput, "service-instance-id") : ""
85                                 }
86
87                                 String networkParams = ""
88                                 if (utils.nodeExists(requestInput, "network-params")) {
89                                         String netParams = utils.getNodeXml(requestInput, "network-params", false).replace("tag0:","").replace(":tag0","")
90                                         networkParams = buildParams(netParams)
91                                 }
92
93                                 String failIfExists = "false"
94                                 // requestInput
95                                 String cloudRegion = cloudRegionId
96                                 String tenantId = utils.getNodeText(requestInput, "tenant-id")
97
98                                 String networkType = ""
99                                 String modelCustomizationUuid = ""
100                                 if (utils.nodeExists(requestInput, "networkModelInfo")) {
101                                         String networkModelInfo = utils.getNodeXml(requestInput, "networkModelInfo", false).replace("tag0:","").replace(":tag0","")
102                                         networkType = utils.getNodeText(networkModelInfo, "modelName")
103                                         modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid")
104                                 } else {
105                                         networkType = queryIdResponse.getNetworkType()
106                                         modelCustomizationUuid = utils.getNodeText(requestInput, "modelCustomizationId")
107                                 }
108
109                                 // queryIdResponse
110                                 String networkName = queryIdResponse.getNetworkName()
111                                 String networkId = queryIdResponse.getNetworkId()
112                                 String networkTechnology = queryIdResponse.getNetworkTechnology()
113
114                                 // contrailNetwork - networkTechnology = 'Contrail' vs. 'AIC_SR_IOV')
115                                 String contrailNetwork = ""
116                                 if (networkTechnology.contains('Contrail') || networkTechnology.contains('contrail') || networkTechnology.contains('CONTRAIL')) {
117                                         contrailNetwork = """<contrailNetwork>
118                                                                <shared>${MsoUtils.xmlEscape(sharedValue)}</shared>
119                                                                <external>${MsoUtils.xmlEscape(externalValue)}</external>
120                                                                ${routeCollection}
121                                                                ${policyFqdns}
122                                                                ${tableCollection}
123                                                          </contrailNetwork>"""
124                                         networkTechnology = "CONTRAIL"    // replace
125                             }
126
127                                 // rebuild subnets
128                                 String subnets = ""
129                                 if (queryIdResponse.getSubnets() != null) {
130                                         subnets = buildSubnets(queryIdResponse)
131                                 }
132
133                                 String physicalNetworkName = ""
134                                 physicalNetworkName = queryIdResponse.getPhysicalNetworkName()
135
136                                 String vlansCollection = buildVlans(queryIdResponse)
137
138                                 String notificationUrl = ""                                   //TODO - is this coming from URN? What variable/value to use?
139                                 //String notificationUrl = execution.getVariable("URN_?????") //TODO - is this coming from URN? What variable/value to use?
140
141                                 createNetworkRequest = """
142                                                                 <createNetworkRequest>
143                                                                         <cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId>
144                                                                         <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
145                                                                         <networkId>${MsoUtils.xmlEscape(networkId)}</networkId>
146                                                                         <networkName>${MsoUtils.xmlEscape(networkName)}</networkName>
147                                                                         <networkType>${MsoUtils.xmlEscape(networkType)}</networkType>
148                                                                         <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid>
149                                                                         <networkTechnology>${MsoUtils.xmlEscape(networkTechnology)}</networkTechnology>
150                                                                         <providerVlanNetwork>
151                                                                                 <physicalNetworkName>${MsoUtils.xmlEscape(physicalNetworkName)}</physicalNetworkName >
152                                                                                 ${vlansCollection}
153                                                                         </providerVlanNetwork>
154                                     ${contrailNetwork}
155                                                                         ${subnets}
156                                                                         <skipAAI>true</skipAAI>
157                                                                         <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout>
158                                                                         <failIfExists>${MsoUtils.xmlEscape(failIfExists)}</failIfExists>
159                                                                         ${networkParams}
160                                                                         <msoRequest>
161                                                                                 <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
162                                                                                 <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
163                                                                 </msoRequest>
164                                                                         <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
165                                                                         <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
166                                                                 </createNetworkRequest>
167                                                                 """.trim()
168                 }
169                 return createNetworkRequest
170
171         }
172
173         /**
174          * This method returns the string for Network request
175          * V2 for Contrail 3.x will populate cloud-region data in same cloudSiteId filed
176          * Network adapter will handle it properly
177          * @param requestId either 'request-id' or 'mso-request-id'
178          * @param requestInput the request in the process
179          * @param queryIdResponse the response of REST AAI query by Id
180          * @param routeCollection the collection
181          * @param policyFqdns the policy
182          * @param cloudRegionId the cloud-region-region
183          * @return String request
184          */
185         def UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, L3Network queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) {
186                 String updateNetworkRequest = null
187                 if(requestInput!=null && queryIdResponse!=null) {
188                                 String serviceInstanceId = ""
189                                 String sharedValue = ""
190                                 String externalValue = ""
191
192                                 if (source == "VID") {
193                                         sharedValue = queryIdResponse.isIsSharedNetwork() != null ? queryIdResponse.isIsSharedNetwork() : "false"
194                                         externalValue = queryIdResponse.isIsExternalNetwork() != null ? queryIdResponse.isIsExternalNetwork() : "false"
195                                         serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id")
196
197                                 } else { // source = 'PORTAL'
198                                         sharedValue = getParameterValue(requestInput, "shared")
199                                         externalValue = getParameterValue(requestInput, "external")
200                                         serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") != null ? utils.getNodeText(requestInput, "service-instance-id") : ""
201                                 }
202
203                                 String failIfExists = "false"
204                                 // requestInput
205                                 String cloudRegion = cloudRegionId
206                                 String tenantId = utils.getNodeText(requestInput, "tenant-id")
207
208                                 // queryIdResponse
209                                 String networkName = queryIdResponse.getNetworkName()
210                                 String networkId = queryIdResponse.getNetworkId()
211
212                                 String networkType = ""
213                                 String modelCustomizationUuid = ""
214                                 if (utils.nodeExists(requestInput, "networkModelInfo")) {
215                                         String networkModelInfo = utils.getNodeXml(requestInput, "networkModelInfo", false).replace("tag0:","").replace(":tag0","")
216                                         networkType = utils.getNodeText(networkModelInfo, "modelName")
217                                         modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid")
218                                 } else {
219                                         networkType = queryIdResponse.getNetworkType()
220                                         modelCustomizationUuid = utils.getNodeText(requestInput, "modelCustomizationId")
221                                 }
222
223                                 // rebuild subnets
224                                 String subnets = ""
225                                 if (queryIdResponse.getSubnets() != null) {
226                                         subnets = buildSubnets(queryIdResponse)
227                                 }
228
229                                 String networkParams = ""
230                                 if (utils.nodeExists(requestInput, "network-params")) {
231                                         String netParams = utils.getNodeXml(requestInput, "network-params", false).replace("tag0:","").replace(":tag0","")
232                                         networkParams = buildParams(netParams)
233                                 }
234
235                                 String networkStackId = queryIdResponse.getHeatStackId()
236                                 if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) {
237                                         networkStackId = "force_update"
238                                 }
239
240                                 String physicalNetworkName = queryIdResponse.getPhysicalNetworkName()
241                                 String vlansCollection = buildVlans(queryIdResponse)
242
243                                 updateNetworkRequest =
244                          """<updateNetworkRequest>
245                                                                 <cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId>
246                                                                 <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
247                                                                 <networkId>${MsoUtils.xmlEscape(networkId)}</networkId>
248                                                         <networkStackId>${MsoUtils.xmlEscape(networkStackId)}</networkStackId>
249                                                                 <networkName>${MsoUtils.xmlEscape(networkName)}</networkName>
250                                                                 <networkType>${MsoUtils.xmlEscape(networkType)}</networkType>
251                                                                 <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid>
252                                                                 <networkTypeVersion/>
253                                                                 <networkTechnology>CONTRAIL</networkTechnology>
254                                                                 <providerVlanNetwork>
255                                                                         <physicalNetworkName>${MsoUtils.xmlEscape(physicalNetworkName)}</physicalNetworkName>
256                                                                         ${vlansCollection}
257                                                                 </providerVlanNetwork>
258                                                                 <contrailNetwork>
259                                                                         <shared>${MsoUtils.xmlEscape(sharedValue)}</shared>
260                                                                         <external>${MsoUtils.xmlEscape(externalValue)}</external>
261                                                                         ${routeCollection}
262                                                                         ${policyFqdns}
263                                                                         ${tableCollection}
264                                                                 </contrailNetwork>
265                                                                 ${subnets}
266                                                                 <skipAAI>true</skipAAI>
267                                                                 <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout>
268                                                                 <failIfExists>${MsoUtils.xmlEscape(failIfExists)}</failIfExists>
269                                                                         ${networkParams}
270
271                                                                 <msoRequest>
272                                                                   <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
273                                                                   <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
274                                                                 </msoRequest>
275                                                                 <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
276                                                                 <notificationUrl></notificationUrl>
277                                                         </updateNetworkRequest>""".trim()
278
279                 }
280                 return updateNetworkRequest
281
282         }
283
284         /**
285          * This method returns the value for the name paramName.
286          *   Ex:   <network-params>
287          *            <param name="shared">1</param>
288          *            <param name="external">0</external>
289          *         </network-params>
290          *
291          * @param xmlInput the XML document
292          * @param paramName the param name (ex: 'shared')
293          * @return a param value for 'shared' (ex: '1')
294          */
295         def getParameterValue(xmlInput, paramName) {
296                 def rtn=""
297                 if(xmlInput!=null){
298                         def xml= new XmlSlurper().parseText(xmlInput)
299                         rtn= xml.'**'.find {param->param.'@name'.text() == paramName}
300                 }
301                 if (rtn==null) {
302                         return ""
303                 } else {
304                    return rtn
305                 }
306         }
307
308         /**
309          * This method returns the networkParams xml string.
310          *   Ex: input:
311          *         <network-params>
312          *            <param name="shared">1</param>
313          *            <param name="external">0</external>
314          *         </network-params>
315          *
316          *   Sample result:
317          *         <networkParams>
318      *            <shared>1</shared>
319      *            <external>0</external>
320      *         </networkParams>
321      *
322          */
323
324         def buildParams(networkParams) {
325                 def build = ""
326                         def netParams = new XmlParser().parseText(networkParams)
327                         try {
328                                 def paramsList = netParams.'**'.findAll {param->param.'@name'}.'@name'
329                                 if (paramsList.size() > 0) {
330                                         build += "<networkParams>"
331                                         for (i in 0..paramsList.size()-1) {
332                         def name = netParams.'**'.find {param->param.'@name' == paramsList[i]}.'@name'
333                                                 def value= netParams.'**'.find {param->param.'@name' == paramsList[i]}.text()
334                                                 build += "<${name}>${MsoUtils.xmlEscape(value)}</${name}>"
335                                         }
336                                         build += "</networkParams>"
337                                 }
338
339                         } catch (Exception ex) {
340                                 println ' buildParams error - ' + ex.getMessage()
341                                 build = ""
342                         }
343                 return build
344         }
345
346         // build network single elements
347         @Deprecated //TODO remove if not used anywhere
348         def buildNetworkElements(l3Network, createNetworkContrailResponse, networkList) {
349                 def replaceNetworkId = ""
350                 def replaceNeutronNetworkId = ""
351                 def replaceContrailNetworkFqdn = ""
352                 if (l3Network != null && createNetworkContrailResponse != null) {
353                         if (utils.nodeExists(l3Network, 'heat-stack-id')) {
354                                 replaceNetworkId = utils.getNodeText(l3Network, 'heat-stack-id')
355                         } else {
356                                 if (utils.nodeExists(createNetworkContrailResponse, 'networkStackId')) {
357                                         replaceNetworkId = utils.getNodeText(createNetworkContrailResponse, 'networkStackId')
358                                 }
359                         }
360                         if (utils.nodeExists(l3Network, 'neutron-network-id')) {
361                                 replaceNeutronNetworkId = utils.getNodeText(l3Network, 'neutron-network-id')
362                         } else {
363                                 if (utils.nodeExists(createNetworkContrailResponse, 'neutronNetworkId')) {
364                                         replaceNeutronNetworkId = utils.getNodeText(createNetworkContrailResponse, 'neutronNetworkId')
365                                 }
366                         }
367                         if (utils.nodeExists(l3Network, 'contrail-network-fqdn')) {
368                                 replaceContrailNetworkFqdn = utils.getNodeText(l3Network, 'contrail-network-fqdn')
369                         } else {
370                                 if (utils.nodeExists(createNetworkContrailResponse, 'networkFqdn')) {
371                                         replaceContrailNetworkFqdn = utils.getNodeText(createNetworkContrailResponse, 'networkFqdn')
372                                 }
373                         }
374                 }
375
376                 String var = ""
377                 def xmlNetwork = ""
378                 if (l3Network != null) {
379                         for (element in networkList) {
380                                 def xml= new XmlSlurper().parseText(l3Network)
381                                 var = xml.'**'.find {it.name() == element}
382                                 if (var == null) {
383                                         if (element=="orchestration-status") {
384                                                 if (var.toString() == 'pending-create' || var.toString() == 'PendingCreate') {
385                                                         xmlNetwork += "<"+element+">"+"Created"+"</"+element+">"
386                                             } else { //pending-update or PendingUpdate
387                                                         xmlNetwork += "<"+element+">"+"Active"+"</"+element+">"
388                                             }
389                                         }
390                                         if (element=="heat-stack-id") {
391                                                 if (replaceNetworkId != "") {
392                                                         xmlNetwork += "<"+element+">"+replaceNetworkId+"</"+element+">"
393                                                 }
394                                         }
395                                         if (element=="neutron-network-id") {
396                                                 if (replaceNeutronNetworkId != "") {
397                                                         xmlNetwork += "<"+element+">"+replaceNeutronNetworkId+"</"+element+">"
398                                                 }
399                                         }
400                                         if (element=="contrail-network-fqdn") {
401                                                 if (replaceContrailNetworkFqdn != "") {
402                                                         xmlNetwork += "<"+element+">"+replaceContrailNetworkFqdn+"</"+element+">"
403                                                 }
404                                         }
405
406                                 } else {
407                                         if (element=="orchestration-status") {
408                                            if (element=="orchestration-status") {
409                                                   if (var.toString() == 'pending-create' || var.toString() == 'PendingCreate') {
410                                                       xmlNetwork += "<"+element+">"+"Created"+"</"+element+">"
411                                                   } else { //pending-update or PendingUpdate
412                                                           xmlNetwork += "<"+element+">"+"Active"+"</"+element+">"
413                                                   }
414                                            }
415                                     } else {
416                                     xmlNetwork += "<"+element+">"+var.toString()+"</"+element+">"
417                                         }
418                                 }
419                          }
420                 }
421                 return xmlNetwork
422         }
423
424         def buildSubnets(L3Network network) {
425                 def rebuildingSubnets = ""
426                 Subnets subnets = network.getSubnets()
427                 try{
428                         for(Subnet s : subnets.getSubnet()){
429                                 def orchestrationStatus = s.getOrchestrationStatus()
430                                 if (orchestrationStatus == "pending-delete" || orchestrationStatus == "PendingDelete") {
431                                         // skip, do not include in processing, remove!!!
432                                 } else {
433                                         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"]
434                                         rebuildingSubnets += buildSubNetworkElements(s, subnetList, "subnets")
435                                         //rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "")
436                                 }
437                         }
438                 } catch (Exception ex) {
439                         //
440                 } finally {
441                         //rebuildingSubnets += "</subnets>"
442                 }
443                 return rebuildingSubnets
444         }
445
446         // build subnet sub-network single elements
447         def buildSubNetworkElements(Subnet subnet, elementList, parentName) {
448
449                 def var = ""
450                 def xmlBuild = ""
451                 if (parentName != "") {
452                         xmlBuild += "<"+parentName+">"
453                  }
454                 if (subnet != null) {
455                     def networkStartAddress = ""
456                         for (element in elementList) {
457                                 if (element == "dhcp-start") {
458                                         var = subnet.getDhcpStart()
459                                         xmlBuild += "<allocationPools>"
460                                         if (var == null) {
461                                                 xmlBuild += "<start>"+""+"</start>"
462                                         } else {
463                                                 xmlBuild += "<start>"+var+"</start>"
464                                         }
465                                 }
466                                 if (element == "dhcp-end") {
467                                         var = subnet.getDhcpEnd()
468                                         if (var == null) {
469                                                 xmlBuild += "<end>"+""+"</end>"
470                                         } else {
471                                                 xmlBuild += "<end>"+var+"</end>"
472                                         }
473                                         xmlBuild += "</allocationPools>"
474                                 }
475                                 if (element == "network-start-address" || element == "cidr-mask") {
476                                         if (element == "network-start-address") {
477                                                 networkStartAddress = subnet.getNetworkStartAddress()
478                                         }
479                                         if (element == "cidr-mask") {
480                                                 xmlBuild += "<cidr>"+networkStartAddress+"/"+var+"</cidr>"
481                                         }
482                                 }
483                                 if (element == "dhcp-enabled") {
484                                         xmlBuild += "<enableDHCP>"+subnet.isDhcpEnabled()+"</enableDHCP>"
485                                 }
486                                 if (element == "gateway-address") {
487                                         xmlBuild += "<gatewayIp>"+subnet.getGatewayAddress()+"</gatewayIp>"
488                                 }
489                                 if (element == "ip-version") {
490                                         String ipVersion = getIpvVersion(subnet.getIpVersion())
491                                         xmlBuild += "<ipVersion>"+ipVersion+"</ipVersion>"
492                                 }
493                                 if (element == "subnet-id") {
494                                         xmlBuild += "<subnetId>"+subnet.getSubnetId()+"</subnetId>"
495                                 }
496                                 if ((element == "subnet-name") && (subnet.getSubnetName() != null)) {
497                                         xmlBuild += "<subnetName>"+subnet.getSubnetName()+"</subnetName>"
498                                 }
499                                 if ((element == "ip-assignment-direction") && (subnet.getIpAssignmentDirection() != null)) {
500                                         xmlBuild += "<addrFromStart>"+subnet.getIpAssignmentDirection()+"</addrFromStart>"
501                                 }
502                                 if (element == "host-routes") {
503                                         def routes = ""
504                                         if (subnet.getHostRoutes() != null) {
505                                                 routes = buildHostRoutes(subnet)
506                                         }
507                                         xmlBuild += routes
508                                 }
509
510                         }
511                 }
512                 if (parentName != "") {
513                         xmlBuild += "</"+parentName+">"
514                  }
515                 return xmlBuild
516         }
517
518         // rebuild host-routes
519         def buildHostRoutes(Subnet subnet) {
520                 def buildHostRoutes = ""
521                 List<HostRoute> routes = subnet.getHostRoutes().getHostRoute()
522                 if(!routes.isEmpty()){
523                         for(HostRoute route:routes){
524                                 buildHostRoutes += "<hostRoutes>"
525                                 buildHostRoutes += "<prefix>" + route.getRoutePrefix() + "</prefix>"
526                                 buildHostRoutes += "<nextHop>" + route.getNextHop() + "</nextHop>"
527                                 buildHostRoutes += "</hostRoutes>"
528                         }
529                 }
530
531                 return buildHostRoutes
532         }
533
534         private String buildVlans(L3Network queryIdResponse) { // get seg ids in put in vlan tags
535                 String vlans = "<vlans>"
536                 if(queryIdResponse.getSegmentationAssignments() != null){
537                         List<SegmentationAssignment> segmentations = queryIdResponse.getSegmentationAssignments().getSegmentationAssignment()
538                         if(!segmentations.isEmpty()){
539                                 for(SegmentationAssignment seg:segmentations){
540                                         String vlan = seg.getSegmentationId() + ","
541                                         vlans += vlan
542                                 }
543                         }
544                 }
545
546                 if(vlans.endsWith(",")){
547                         vlans = vlans.substring(0, vlans.length() - 1)
548                 }
549
550                 vlans += "</vlans>"
551
552                 return vlans
553         }
554
555 //TODO: This method still needs to be tested before using.
556         /**
557          *
558          * This method is similar to the gennetwork:ContrailNetworUpdateCompletedObject
559          * BPEL method.  It extracts all of the required subnet information
560          * for each subnet listed with an orch status equal to the one provided
561          * and puts the corresponding infomation with the appropriate node for
562          * updating aai. The method sets the orch status for each subnet to active
563          *
564          * @param subnetsXml the entire subnets xml
565          * @param requestInput the request in the process
566          * @param queryIdResponse the response of REST AAI query by Id
567          * @param queryVpnBindingResponse the response of REST AAI query by vpn binding
568          * @param routeCollection the collection of vpnBinding's 'global-route-target'
569          * @return String request
570          */
571         public String networkUpdateSubnetInfo(String subnetsXml, String networkResponseXml){
572
573                         String subnets = ""
574                         StringBuilder sb = new StringBuilder()
575                         InputSource source = new InputSource(new StringReader(subnetsXml));
576                         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
577                         docFactory.setNamespaceAware(true)
578                         DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
579                         Document xml = docBuilder.parse(source)
580                         NodeList nodeList = xml.getElementsByTagNameNS("*", "subnet")
581                         for (int x = 0; x < nodeList.getLength(); x++) {
582                                 Node node = nodeList.item(x)
583                                 String subnet = ""
584                                 if (node.getNodeType() == Node.ELEMENT_NODE) {
585                                         Element eElement = (Element) node
586                                         String subnetOrchStatus = eElement.getElementsByTagNameNS("*", "orchestration-status").item(0).getTextContent()
587                                         if(subnetOrchStatus.equals("pending-create")){
588
589                                                 String subnetId = eElement.getElementsByTagNameNS("*", "subnet-id").item(0).getTextContent()
590                                                 def netAddress = eElement.getElementsByTagNameNS("*", "network-start-address").item(0).getTextContent()
591                                                 def mask = eElement.getElementsByTagNameNS("*", "cidr-mask").item(0).getTextContent()
592                                                 def dhcpEnabledSubnet = eElement.getElementsByTagNameNS("*", "dhcp-enabled").item(0).getTextContent()
593                                                 def gatewayAddress = eElement.getElementsByTagNameNS("*", "gateway-address").item(0).getTextContent()
594                                                 def ipVersion = eElement.getElementsByTagNameNS("*", "ip-version").item(0).getTextContent()
595                                                 def relationshipList =  eElement.getElementsByTagNameNS("*", "relationship-list").item(0).getTextContent() //TODO: test this
596                                                 String neutronSubnetId = extractNeutSubId(networkResponseXml, subnetId)
597                                                 subnet =
598                                                 """<subnet>
599                                         <subnetId>${MsoUtils.xmlEscape(subnetId)}</subnetId>
600                                         <neutron-subnet-id>${MsoUtils.xmlEscape(neutronSubnetId)}</neutron-subnet-id>
601                                         <gateway-address>${MsoUtils.xmlEscape(gatewayAddress)}</gateway-address>
602                                         <network-start-address>${MsoUtils.xmlEscape(netAddress)}</network-start-address>
603                                         <cidr-mask>${MsoUtils.xmlEscape(mask)}</cidr-mask>
604                                         <ip-Version>${MsoUtils.xmlEscape(ipVersion)}</ip-Version>
605                                         <orchestration-status>active</orchestration-status>
606                                         <dhcp-enabled>${MsoUtils.xmlEscape(dhcpEnabledSubnet)}</dhcp-enabled>
607                                         <relationship-list>${relationshipList}</relationship-list>
608                                         </subnet>"""
609
610                                         }else if(subnetOrchStatus.equals("pending-delete")){
611                                                 StringWriter writer = new StringWriter()
612                                                 Transformer transformer = TransformerFactory.newInstance().newTransformer()
613                                                 transformer.transform(new DOMSource(node), new StreamResult(writer))
614                                                 subnet = writer.toString()
615
616                                         }else{
617                                                 subnet = ""
618                                         }
619                                 }
620                                 subnets = sb.append(subnet)
621                         }
622
623                         subnets = utils.removeXmlPreamble(subnets)
624
625                         String subnetsList =
626                         """<subnets>
627                         ${subnets}
628                         </subnets>"""
629
630                         return subnetsList
631         }
632
633
634         /**
635          *
636          * This method extracts the "value" node text for the the given subnet Id.
637          *
638          * @param String inputSource - xml that contains the subnet id key and value
639          * @param String subnetId - for which you want the value of
640
641          * @return String value - node text of node named value associated with the given subnet id
642          */
643         public String extractNeutSubId(String inputSource, String subnetId){
644
645                                 String value = ""
646                                 InputSource source = new InputSource(new StringReader(inputSource));
647                                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
648                                 docFactory.setNamespaceAware(true)
649                                 DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
650                                 Document xml = docBuilder.parse(source)
651                                 NodeList nodeList = xml.getElementsByTagNameNS("*", "entry")
652                                 for (int x = 0; x < nodeList.getLength(); x++) {
653                                         Node node = nodeList.item(x)
654                                         String subnet = ""
655                                         if (node.getNodeType() == Node.ELEMENT_NODE) {
656                                                 Element eElement = (Element) node
657                                                 String key = eElement.getElementsByTagNameNS("*", "key").item(0).getTextContent()
658                                                 if(key.equals(subnetId)){
659                                                         value = eElement.getElementsByTagNameNS("*", "value").item(0).getTextContent()
660                                                 }
661                                         }
662                                 }
663                                 return value
664                         }
665
666         public boolean isRollbackEnabled (DelegateExecution execution, String payloadXml) {
667
668                 def rollbackEnabled = false
669                 def rollbackValueSet = false
670                 if (utils.nodeExists(payloadXml, "backout-on-failure")) {
671                         String backoutValue = utils.getNodeText(payloadXml, "backout-on-failure")
672                         if (backoutValue != null && !backoutValue.isEmpty()) {
673                                 if (backoutValue.equalsIgnoreCase("false")) {
674                                         rollbackEnabled = false
675                                 }
676                                 else {
677                                         rollbackEnabled = true
678                                 }
679                                 rollbackValueSet = true;
680                         }
681                 }
682
683                 if (!rollbackValueSet) {
684
685                         if (UrnPropertiesReader.getVariable("mso.rollback", execution) != null) {
686                             rollbackEnabled = UrnPropertiesReader.getVariable("mso.rollback", execution).toBoolean()
687                         }
688                 }
689                 return rollbackEnabled
690         }
691
692
693         /**
694          * This method extracts the version for the the given ip-version.
695          *
696          * @param String ipvVersion - IP protocols version (ex: ipv4 or ipv6 or 4 or 6)
697          * @return String version - digit version (ex: 4 or 6)
698          */
699
700         public String getIpvVersion (String ipvVersion) {
701
702                 String version = ""
703                 try {
704                         if (ipvVersion.isNumber()) {
705                                 version = ipvVersion
706                         } else {
707                                 version = ipvVersion.substring(ipvVersion.indexOf("ipv")+3)
708                                 if (!version.isNumber()) {
709                                         version = ipvVersion
710                                 }
711                         }
712                 } catch (Exception ex) {
713                         version = ipvVersion
714                 }
715                 return version
716         }
717 }