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