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