2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.mso.bpmn.common.scripts
23 import groovy.xml.XmlUtil
25 import java.text.SimpleDateFormat
27 import org.apache.commons.codec.binary.Base64
28 import org.openecomp.mso.bpmn.core.BPMNLogger
29 import org.openecomp.mso.bpmn.core.xml.XmlTool
30 import org.openecomp.mso.logger.MessageEnum
31 import org.openecomp.mso.logger.MsoLogger
32 import org.openecomp.mso.utils.CryptoUtils
33 import org.w3c.dom.Element
36 def initializeEndPoints(execution){
37 // use this placeholder to initialize end points, if called independently, this need to be set
38 execution.setVariable("AAIEndPoint","http://localhost:28080/SoapUIMocks")
40 def getNodeText(xmlInput,element){
43 def xml= new XmlSlurper().parseText(xmlInput)
44 rtn= xml.'**'.find{node->node.name()==element}.text()
48 def getMultNodes(xmlInput, element){
51 def xml= new XmlSlurper().parseText(xmlInput)
52 nodes = xml.'**'.findAll{ node-> node.name() == element }*.text()
56 def getNodeText1(xmlInput,element){
59 def xml= new XmlSlurper().parseText(xmlInput)
60 rtn= xml.'**'.find{node->node.name()==element}
67 def getNodeXml(xmlInput,element){
68 return getNodeXml(xmlInput, element, true)
70 def getNodeXml(xmlInput,element,incPreamble){
71 def fxml= new XmlSlurper().parseText(xmlInput)
72 def nodeToSerialize = fxml.'**'.find {it.name() == element}
73 if(nodeToSerialize==null){
76 def nodeAsText = XmlUtil.serialize(nodeToSerialize)
78 nodeAsText = removeXmlPreamble(nodeAsText)
82 def nodeExists(xmlInput,element){
84 def fxml= new XmlSlurper().parseText(xmlInput)
85 def nodeToSerialize = fxml.'**'.find {it.name() == element}
86 return nodeToSerialize!=null
87 } catch(Exception e) {
93 /***** Utilities when using XmlParser *****/
96 * Convert a Node into a String by deserializing it and formatting it.
98 * @param node Node to be converted.
99 * @return the Node as a String.
101 def String nodeToString(Node node) {
102 def String nodeAsString = groovy.xml.XmlUtil.serialize(node)
103 nodeAsString = removeXmlPreamble(nodeAsString)
104 return formatXml(nodeAsString)
108 * Get the specified child Node of the specified parent. If there are
109 * multiple children of the same name, only the first one is returned.
110 * If there are no children with the specified name, 'null' is returned.
112 * @param parent Parent Node in which to find a child.
113 * @param childNodeName Name of the child Node to get.
114 * @return the (first) child Node with the specified name or 'null'
115 * if a child Node with the specified name does not exist.
117 def Node getChildNode(Node parent, String childNodeName) {
118 def NodeList nodeList = getIdenticalChildren(parent, childNodeName)
119 if (nodeList.size() == 0) {
122 return nodeList.get(0)
127 * Get the textual value of the specified child Node of the specified parent.
128 * If there are no children with the specified name, 'null' is returned.
130 * @param parent Parent Node in which to find a child.
131 * @param childNodeName Name of the child Node whose value to get.
132 * @return the textual value of child Node with the specified name or 'null'
133 * if a child Node with the specified name does not exist.
135 def String getChildNodeText(Node parent, String childNodeName) {
136 def Node childNode = getChildNode(parent, childNodeName)
137 if (childNode == null) {
140 return childNode.text()
145 * Get all of the child nodes from the specified parent that have the
146 * specified name. The returned NodeList could be empty.
148 * @param parent Parent Node in which to find children.
149 * @param childNodeName Name of the children to get.
150 * @return a NodeList of all the children from the parent with the specified
151 * name. The list could be empty.
153 def NodeList getIdenticalChildren(Node parent, String childNodeName) {
154 return (NodeList) parent.get(childNodeName)
157 /***** End of Utilities when using XmlParser *****/
160 /** these are covered under the common function above**/
161 def getSubscriberName(xmlInput,element){
164 def xml= new XmlSlurper().parseText(xmlInput)
165 rtn= xml.'**'.find{node->node.name()==element}.text()
169 def getTenantInformation(xmlInput,element){
170 def xml= new XmlSlurper().parseText(xmlInput)
171 def nodeToSerialize = xml.'**'.find {it.name() == 'service-information'}
172 def nodeAsText = XmlUtil.serialize(nodeToSerialize)
175 def getServiceInstanceId(xmlInput,element){
176 def xml= new XmlSlurper().parseText(xmlInput)
177 return ( xml.'**'.find{node->node.name()==element}.text() )
180 def searchResourceLink(xmlInput, resourceType){
181 def fxml= new XmlSlurper().parseText(xmlInput)
182 def element = fxml.'**'.find {it.'resource-type' == resourceType}
183 return (element == null) ? null : element.'resource-link'.text()
186 def searchMetaData(xmlInput, searchName, searchValue){
187 def fxml= new XmlSlurper().parseText(xmlInput)
188 def ret = fxml.'**'.find {it.metaname.text() == searchName && it.metaval.text() == searchValue}
190 return ret.parent().parent()
195 def searchMetaDataNode(fxml, searchName, searchValue){
196 def ret = fxml.'**'.find {it.metaname.text() == searchName && it.metaval.text() == searchValue}
198 return ret.parent().parent()
203 // for Trinity L3 add/delete bonding
204 def getPBGFList(isDebugLogEnabled, xmlInput){
205 xmlInput = xmlInput.replaceAll("&", "&")
206 xmlInput = xmlInput.replaceAll("<", "<")
207 xmlInput = xmlInput.replaceAll(">", ">")
208 log("DEBUG", "getPBGFList: xmlInput " + xmlInput,isDebugLogEnabled)
209 ArrayList myNodes = new ArrayList()
210 if(nodeExists(xmlInput,"nbnc-response-information")){
211 def respInfo=getNodeXml(xmlInput,"nbnc-response-information", false)
213 def fxml= new XmlSlurper().parseText(respInfo)
214 fxml.'virtual-datacenter-list'.each { vdc ->
215 //we only want to add two BGF per VDC, BGF1 and BGF2
216 def routerList = vdc.'router-list'.first()
217 routerList.each{ myList ->
218 def physNodes = myList.'**'.findAll {it.'border-element-tangibility'.text() =~ /PHYSICAL/}
224 def beid = nodeToAdd.'border-element-id'.text() +
225 " " + nodeToAdd.'border-element-type'.text() +
227 it.'border-element-id'.text() +
228 " " + it.'border-element-type'.text()
229 def mytag = nodeToAdd.'border-element-id'
230 mytag[0].replaceBody(beid)
233 def mytag = nodeToAdd.'vlan-id'
234 def ind = mytag.text().indexOf('.')
236 def vlan = mytag.text().substring(0,ind)
237 mytag[0].replaceBody(vlan)
239 myNodes.add(XmlUtil.serialize(nodeToAdd))
251 def getPBGFList(xmlInput){
252 getPBGFList("false", xmlInput)
255 def String decodeXML(xml) {
256 def String decodedXml = xml.replaceAll("&", "&")
257 decodedXml = decodedXml.replaceAll("<", "<")
258 decodedXml = decodedXml.replaceAll(">", ">")
261 def getMetaVal(node, name){
263 return node.'**'.find {it.metaname.text() == name}.metaval.text()
268 def getRelationshipVal(node, name){
270 return node.'**'.find {it.'relationship-key'.text() == name}.'relationship-value'.text()
277 def log(logmode,logtxt,isDebugLogEnabled="false"){
278 MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
279 if ("INFO"==logmode) {
280 msoLogger.info(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, logtxt);
281 } else if ("WARN"==logmode) {
282 msoLogger.warn (MessageEnum.BPMN_GENERAL_WARNING, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logtxt);
283 } else if ("ERROR"==logmode) {
284 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logtxt);
287 BPMNLogger.debug(isDebugLogEnabled, logtxt);
291 def logContext(requestId, serviceInstanceId){
292 MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
293 msoLogger.setLogContext(requestId, serviceInstanceId);
296 def logMetrics(elapsedTime, logtxt){
297 MsoLogger metricsLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
299 metricsLogger.recordMetricEvent (elapsedTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
300 logtxt, "BPMN", MsoLogger.getServiceName(), null);
303 def logAudit(logtxt){
304 MsoLogger auditLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
305 long startTime = System.currentTimeMillis();
307 auditLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logtxt);
310 // headers: header - name-value
311 def getHeaderNameValue(xmlInput, nameAttribute){
314 def xml= new XmlSlurper().parseText(xmlInput)
315 rtn= xml.'**'.find {header->header.'@name'.text() == nameAttribute}.'@value'
321 * Gets the children of the specified element.
323 public String getChildNodes(xmlInput, element) {
324 def xml= new XmlSlurper().parseText(xmlInput)
325 def thisElement = xml.'**'.find {it.name() == element}
326 StringBuilder out = new StringBuilder()
327 if (thisElement != null) {
328 thisElement.children().each() {
329 String nodeAsText = removeXmlPreamble(XmlUtil.serialize(it))
330 if (out.length() > 0) {
331 out.append(System.lineSeparator())
333 out.append(nodeAsText)
336 return out.toString();
340 * Encodes a value so it can be used inside an XML text element.
341 * @param s the string to encode
342 * @return the encoded string
344 public String xmlEncode(Object value) {
345 return XmlTool.encode(value)
349 * Encodes a value so it can be used inside an XML attribute.
350 * @param s the string to encode
351 * @return the encoded string
353 public String xmlEncodeAttr(Object value) {
354 return XmlTool.encodeAttr(value)
358 * Decodes XML entities in a string value
359 * @param value a value with embedded XML entities
360 * @return the decoded string
362 public String xmlDecode(Object value) {
363 return XmlTool.decode(value)
367 * Removes the preamble, if present, from an XML document.
368 * Also, for historical reasons, this also trims leading and trailing
369 * whitespace from the resulting document. TODO: remove the trimming
370 * and fix unit tests that depend on EXACT xml format.
371 * @param xml the XML document
372 * @return a possibly modified document
374 public String removeXmlPreamble(def xml) {
379 return XmlTool.removePreamble(xml).trim()
383 * Removes namespaces and namespace declarations from an XML document.
384 * @param xml the XML document
385 * @return a possibly modified document
387 public String removeXmlNamespaces(def xml) {
388 return XmlTool.removeNamespaces(xml);
392 * Use formatXml instead. Note: this method inserts an XML preamble.
395 def formatXML(xmlInput) {
398 if (xmlInput !=null) {
399 parseXml = new XmlParser().parseText(xmlInput)
400 formatXml = XmlUtil.serialize(parseXml)
405 * Reformats an XML document. The result will not contain an XML preamble
406 * or a trailing newline.
407 * @param xml the XML document
408 * @return a reformatted document
410 public String formatXml(def xml) {
411 return XmlTool.normalize(xml);
414 // build single elements
415 def buildElements(xmlInput, elementList, parentName) {
418 if (parentName != "") {
419 xmlBuild += "<tns2:"+parentName+">"
421 if (xmlInput != null) {
422 for (element in elementList) {
423 def xml= new XmlSlurper().parseText(xmlInput)
424 var = xml.'**'.find {it.name() == element}
426 xmlBuild += "<tns2:"+element+">"+var.toString()+"</tns2:"+element+">"
430 if (parentName != "") {
431 xmlBuild += "</tns2:"+parentName+">"
436 // build the Unbounded elements
437 def buildElementsUnbounded(xmlInput, elementList, parentName) {
440 def xmlBuildUnbounded = ""
441 if (xmlInput != null) {
442 def xml= new XmlSlurper().parseText(xmlInput)
443 varParents = xml.'**'.findAll {it.name() == parentName}
444 //println " Unbounded ${parentName} - varParent.Size() - " + varParents.size()
445 for (i in 0..varParents.size()-1) {
446 if (parentName != "") {
447 xmlBuildUnbounded += "<tns2:"+parentName+">"
449 for (element in elementList) {
450 var = varParents[i].'*'.find {it.name() == element}
452 xmlBuildUnbounded += "<tns2:"+element+">"+var.toString()+"</tns2:"+element+">"
453 //println " i = " + i + ", element: " + element + " = " + var.toString()
456 if (parentName != "") {
457 xmlBuildUnbounded += "</tns2:"+parentName+">"
461 return xmlBuildUnbounded
464 // Build l2-homing-information
465 def buildL2HomingInformation(xmlInput) {
466 def elementsL2HomingList = ["evc-name", "topology", "preferred-aic-clli"]
467 def rebuildL2Home = ''
468 if (xmlInput != null) {
469 rebuildL2Home = buildElements(xmlInput, elementsL2HomingList, "l2-homing-information")
474 // Build internet-evc-access-information
475 def buildInternetEvcAccessInformation(xmlInput) {
476 def elementsInternetEvcAccessInformationList = ["internet-evc-speed-value", "internet-evc-speed-units", "ip-version"]
477 def rebuildInternetEvcAccess = ''
478 if (xmlInput != null) {
479 rebuildInternetEvcAccess = buildElements(xmlInput, elementsInternetEvcAccessInformationList, "internet-evc-access-information")
481 return rebuildInternetEvcAccess
484 // Build ucpe-vms-service-information
485 def buildUcpeVmsServiceInformation(xmlInput) {
486 def rebuildUcpeVmsServiceInformation = ''
487 if (xmlInput != null) {
488 def ucpeVmsServiceInformation = getNodeXml(xmlInput, "ucpe-vms-service-information").drop(38).trim()
489 rebuildUcpeVmsServiceInformation = "<tns2:ucpe-vms-service-information>"
490 // transport-service-information
491 rebuildUcpeVmsServiceInformation += "<tns2:transport-service-information>"
492 def transportServiceInformation = getNodeXml(ucpeVmsServiceInformation, "transport-service-information").drop(38).trim()
493 def elementsTransportServiceInformationList = ["transport-service-type"]
494 rebuildUcpeVmsServiceInformation += buildElements(transportServiceInformation, elementsTransportServiceInformationList, "")
496 def accessCircuitInfoList = ["access-circuit-id", "dual-mode"]
497 rebuildUcpeVmsServiceInformation += buildElementsUnbounded(transportServiceInformation, accessCircuitInfoList, "access-circuit-info")
498 } catch (Exception e) {
499 log("ERROR", " Optional - Exception ACCESS-CIRCUIT-INFO - 'access-circuit-info' ")
501 rebuildUcpeVmsServiceInformation += "</tns2:transport-service-information>"
503 def elementsUcpeInformationList = ["ucpe-host-name", "ucpe-activation-code", "out-of-band-management-modem" ]
504 rebuildUcpeVmsServiceInformation += buildElements(ucpeVmsServiceInformation, elementsUcpeInformationList, "ucpe-information")
506 rebuildUcpeVmsServiceInformation += "<tns2:vnf-list>"
507 def vnfListList = ["vnf-instance-id", "vnf-sequence-number", "vnf-type", "vnf-vendor", "vnf-model", "vnf-id", "prov-status", "operational-state", "orchestration-status", "equipment-role" ]
508 rebuildUcpeVmsServiceInformation += buildElementsUnbounded(ucpeVmsServiceInformation, vnfListList, "vnf-information")
509 rebuildUcpeVmsServiceInformation += "</tns2:vnf-list>"
510 rebuildUcpeVmsServiceInformation += "</tns2:ucpe-vms-service-information>"
512 log("DEBUG", " rebuildUcpeVmsServiceInformation - " + rebuildUcpeVmsServiceInformation)
513 return rebuildUcpeVmsServiceInformation
516 // Build internet-service-change-details
517 def buildInternetServiceChangeDetails(xmlInput) {
518 def rebuildInternetServiceChangeDetails = ""
519 if (xmlInput != null) {
521 def internetServiceChangeDetails = getNodeXml(xmlInput, "internet-service-change-details").drop(38).trim()
522 rebuildInternetServiceChangeDetails = "<tns:internet-service-change-details>"
523 rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-value"], "")
524 rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-units"], "")
526 def tProvidedV4LanPublicPrefixesChangesList = ["request-index", "v4-next-hop-address", "v4-lan-public-prefix", "v4-lan-public-prefix-length"]
527 rebuildInternetServiceChangeDetails += buildElementsUnbounded(internetServiceChangeDetails, tProvidedV4LanPublicPrefixesChangesList, "t-provided-v4-lan-public-prefixes")
528 } catch (Exception e) {
529 log("ERROR"," Optional - Exception in INTERNET-SERVICE-CHANGE-DETAILS 't-provided-v4-lan-public-prefixes ")
532 def tProvidedV6LanPublicPrefixesChangesList = ["request-index", "v6-next-hop-address", "v6-lan-public-prefix", "v6-lan-public-prefix-length"]
533 rebuildInternetServiceChangeDetails += buildElementsUnbounded(internetServiceChangeDetails, tProvidedV6LanPublicPrefixesChangesList, "t-provided-v6-lan-public-prefixes")
534 } catch (Exception e) {
535 log("ERROR"," Optional - Exception INTERNET-SERVICE-CHANGE-DETAILS 't-provided-v6-lan-public-prefixes ")
537 rebuildInternetServiceChangeDetails += "</tns:internet-service-change-details>"
538 } catch (Exception e) {
539 log("ERROR", " Optional - Exception INTERNET-SERVICE-CHANGE-DETAILS 'internet-service-change-details' ")
542 return rebuildInternetServiceChangeDetails
546 def buildVrLan(xmlInput) {
548 def rebuildVrLan = ''
549 if (xmlInput != null) {
551 rebuildVrLan = "<tns2:vr-lan>"
552 def vrLan = getNodeXml(xmlInput, "vr-lan").drop(38).trim()
553 rebuildVrLan += buildElements(vrLan, ["routing-protocol"], "")
556 def rebuildVrLanInterface = "<tns2:vr-lan-interface>"
557 def vrLanInterface = getNodeXml(vrLan, "vr-lan-interface").drop(38).trim()
558 rebuildVrLanInterface += buildVrLanInterfacePartial(vrLanInterface)
561 def dhcp = getNodeXml(vrLan, "dhcp").drop(38).trim()
562 def rebuildDhcp = buildDhcp(dhcp)
563 rebuildVrLanInterface += rebuildDhcp
566 def pat = getNodeXml(vrLan, "pat").drop(38).trim()
567 def rebuildPat = buildPat(pat)
568 rebuildVrLanInterface += rebuildPat
573 def nat = getNodeXml(vrLan, "nat").drop(38).trim()
574 rebuildNat = buildNat(nat)
575 } catch (Exception e) {
576 log("ERROR", " Optional - Exception 'nat' ")
578 rebuildVrLanInterface += rebuildNat
581 def firewallLite = getNodeXml(vrLan, "firewall-lite").drop(38).trim()
582 def rebuildFirewallLite = buildFirewallLite(firewallLite)
583 rebuildVrLanInterface += rebuildFirewallLite
586 def rebuildStaticRoutes = ""
588 def staticRoutes = getNodeXml(vrLan, "static-routes").drop(38).trim()
589 rebuildStaticRoutes = buildStaticRoutes(staticRoutes)
590 } catch (Exception e) {
591 log("ERROR", " Optional - Exception 'static-routes' ")
593 rebuildVrLanInterface += rebuildStaticRoutes
595 rebuildVrLan += rebuildVrLanInterface
596 rebuildVrLan += "</tns2:vr-lan-interface>"
597 rebuildVrLan += "</tns2:vr-lan>"
600 log("DEBUG", " rebuildVrLan - " + rebuildVrLan)
604 // Build vr-lan-interface
605 def buildVrLanInterfacePartial(xmlInput) {
606 def rebuildingVrLanInterface = ''
607 if (xmlInput != null) {
608 def vrLanInterfaceList = ["vr-designation", "v4-vr-lan-prefix", "v4-vr-lan-address", "v4-vr-lan-prefix-length", "v6-vr-lan-prefix", "v6-vr-lan-address", "v6-vr-lan-prefix-length", "v4-vce-loopback-address", "v6-vce-wan-address"]
609 rebuildingVrLanInterface += buildElements(xmlInput, vrLanInterfaceList, "")
610 rebuildingVrLanInterface += "<tns2:v4-public-lan-prefixes>"
612 def tProvidedV4LanPublicPrefixes = getNodeXml(xmlInput, "v4-public-lan-prefixes").drop(38).trim()
613 def tProvidedV4LanPublicPrefixesList = ["request-index", "v4-next-hop-address", "v4-lan-public-prefix", "v4-lan-public-prefix-length" ]
614 rebuildingVrLanInterface += buildElementsUnbounded(xmlInput, tProvidedV4LanPublicPrefixesList, "t-provided-v4-lan-public-prefixes")
615 } catch (Exception ex) {
616 log("ERROR", " Optional - Exception VR-LAN INTERFACE 'v4-public-lan-prefixes' ")
618 rebuildingVrLanInterface += "</tns2:v4-public-lan-prefixes>"
619 rebuildingVrLanInterface += "<tns2:v6-public-lan-prefixes>"
621 def tProvidedV6LanPublicPrefixes = getNodeXml(xmlInput, "v6-public-lan-prefixes").drop(38).trim()
622 def tProvidedV6LanPublicPrefixesList = ["request-index", "v6-next-hop-address", "v6-lan-public-prefix", "v6-lan-public-prefix-length" ]
623 rebuildingVrLanInterface += buildElementsUnbounded(xmlInput, tProvidedV6LanPublicPrefixesList, "t-provided-v6-lan-public-prefixes")
624 } catch (Exception e) {
625 log("ERROR", " Optional - Exception VR-LAN INTERFACE 'v6-public-lan-prefixes' ")
627 rebuildingVrLanInterface += "</tns2:v6-public-lan-prefixes>"
629 log("DEBUG", " rebuildingVrLanInterface - " + rebuildingVrLanInterface)
630 return rebuildingVrLanInterface
634 def buildDhcp(xmlInput) {
635 def rebuildingDhcp = ''
636 if (xmlInput != null) {
637 def dhcpData = new XmlSlurper().parseText(xmlInput)
638 rebuildingDhcp = "<tns2:dhcp>"
639 def dhcpList1 = ["v4-dhcp-server-enabled", "v6-dhcp-server-enabled", "use-v4-default-pool", "v4-dhcp-default-pool-prefix", "v4-dhcp-default-pool-prefix-length"]
640 rebuildingDhcp += buildElements(xmlInput, dhcpList1, "")
642 def excludedV4DhcpAddressesFromDefaultPoolList = ["excluded-v4-address"]
643 rebuildingDhcp += buildElementsUnbounded(xmlInput, excludedV4DhcpAddressesFromDefaultPoolList, "excluded-v4-dhcp-addresses-from-default-pool")
644 } catch (Exception e) {
645 log("ERROR", " Optional - Exception DHCP 'excluded-v4-dhcp-addresses-from-default-pool' ")
648 def v4DhcpPools = dhcpData.'**'.findAll {it.name() == "v4-dhcp-pools"}
649 def v4DhcpPoolsSize = v4DhcpPools.size()
650 // println " v4DhcpPoolsSize = " + v4DhcpPools.size()
651 for (i in 0..v4DhcpPoolsSize-1) {
652 def v4DhcpPool = v4DhcpPools[i]
653 def v4DhcpPoolXml = XmlUtil.serialize(v4DhcpPool)
654 rebuildingDhcp += "<tns2:v4-dhcp-pools>"
655 def v4DhcpPoolsList1 = ["v4-dhcp-pool-prefix", "v4-dhcp-pool-prefix-length" ]
656 rebuildingDhcp += buildElements(v4DhcpPoolXml, v4DhcpPoolsList1, "")
658 def excludedV4AddressesList = ["excluded-v4-address"]
659 rebuildingDhcp += buildElementsUnbounded(v4DhcpPoolXml, excludedV4AddressesList, "excluded-v4-addresses")
660 } catch (Exception e) {
661 log("ERROR", " Optional - Exception DHCP 'excluded-v4-addresses' ")
663 def v4DhcpPoolsList2 = ["v4-dhcp-relay-gateway-address", "v4-dhcp-relay-next-hop-address"]
664 rebuildingDhcp += buildElements(v4DhcpPoolXml, v4DhcpPoolsList2, "")
665 rebuildingDhcp += "</tns2:v4-dhcp-pools>"
667 } catch (Exception e) {
668 log("ERROR"," Optional - Exception DHCP 'v4-dhcp-pools' ")
670 def dhcpList2 = ["use-v6-default-pool", "v6-dhcp-default-pool-prefix", "v6-dhcp-default-pool-prefix-length"]
671 rebuildingDhcp += buildElements(xmlInput, dhcpList2, "")
673 def excludedV6DhcpAddressesFromDdefaultPoolList = ["excluded-v6-address"]
674 rebuildingDhcp += buildElementsUnbounded(xmlInput, excludedV6DhcpAddressesFromDdefaultPoolList, "excluded-v6-dhcp-addresses-from-default-pool")
675 } catch (Exception e) {
676 log("ERROR", " Optional - Exception DHCP 'excluded-v6-dhcp-addresses-from-default-pool' ")
679 def v6DhcpPools = dhcpData.'**'.findAll {it.name() == "v6-dhcp-pools"}
680 def v6DhcpPoolsSize = v6DhcpPools.size()
681 //println " v6DhcpPoolsSize = " + v6DhcpPools.size()
682 for (i in 0..v6DhcpPoolsSize-1) {
683 def v6DhcpPool = v6DhcpPools[i]
684 def v6DhcpPoolXml = XmlUtil.serialize(v6DhcpPool)
685 rebuildingDhcp += "<tns2:v6-dhcp-pools>"
686 def v6DhcpPoolsList1 = ["v6-dhcp-pool-prefix", "v6-dhcp-pool-prefix-length"]
687 rebuildingDhcp += buildElements(v6DhcpPoolXml, v6DhcpPoolsList1, "")
689 def excludedV6AddressesList = ["excluded-v6-address"]
690 rebuildingDhcp += buildElementsUnbounded(v6DhcpPoolXml, excludedV6AddressesList, "excluded-v6-addresses")
691 } catch (Exception e) {
692 log("ERROR", " Optional - Exception DHCP 'excluded-v6-addresses' ")
694 def v6DhcpPoolsList2 = ["v6-dhcp-relay-gateway-address", "v6-dhcp-relay-next-hop-address"]
695 rebuildingDhcp += buildElements(v6DhcpPoolXml, v6DhcpPoolsList2, "")
696 rebuildingDhcp += "</tns2:v6-dhcp-pools>"
698 } catch (Exception e) {
699 log("ERROR", " Optional - Exception DHCP 'v6-dhcp-pools' ")
701 rebuildingDhcp += "</tns2:dhcp>"
703 log("DEBUG", " rebuildingDhcp - " + rebuildingDhcp)
704 return rebuildingDhcp
708 def buildPat(xmlInput) {
709 def rebuildingPat = ''
710 if (xmlInput != null) {
711 rebuildingPat = "<tns2:pat>"
712 def patList = ["v4-pat-enabled", "use-v4-default-pool", "v4-pat-default-pool-prefix", "v4-pat-default-pool-prefix-length"]
713 rebuildingPat += buildElements(xmlInput, patList, "")
715 def v4PatPools = getNodeXml(xmlInput, "v4-pat-pools").drop(38).trim()
716 def v4PatPoolsList = ["v4-pat-pool-prefix", "v4-pat-pool-prefix-length", "v4-pat-pool-next-hop-address"]
717 rebuildingPat += buildElementsUnbounded(xmlInput, v4PatPoolsList, "v4-pat-pools")
718 } catch (Exception e) {
719 log("ERROR", " Optional - Exception 'v4-pat-pool-next-hop-address' ")
721 rebuildingPat += "</tns2:pat>"
723 log("DEBUG", " rebuildingPat - " + rebuildingPat)
728 def buildNat(xmlInput) {
729 def rebuildingNat = ''
730 if (xmlInput != null) {
731 rebuildingNat = "<tns2:nat>"
732 rebuildingNat += buildElements(xmlInput, ["v4-nat-enabled"], "")
734 def v4NatMappingEntries = getNodeXml(xmlInput, "v4-nat-mapping-entries").drop(38).trim()
735 def v4NatMappingEntriesList = ["v4-nat-internal", "v4-nat-next-hop-address", "v4-nat-external"]
736 rebuildingNat += buildElementsUnbounded(xmlInput, v4NatMappingEntriesList, "v4-nat-mapping-entries")
737 } catch (Exception e) {
738 log("ERROR", " Optional - Exception 'v4-nat-external' ")
740 rebuildingNat += "</tns2:nat>"
742 log("DEBUG", " rebuildingNat - " + rebuildingNat)
746 // Build firewall-lite
747 def buildFirewallLite(xmlInput) {
748 def rebuildingFirewallLite = ''
750 if (xmlInput != null) {
752 def firewallLiteData = new XmlSlurper().parseText(xmlInput)
753 rebuildingFirewallLite = "<tns2:firewall-lite>"
754 def firewallLiteList = ["stateful-firewall-lite-v4-enabled", "stateful-firewall-lite-v6-enabled"]
755 rebuildingFirewallLite += buildElements(xmlInput, firewallLiteList, "")
758 def v4FirewallPacketFilters = firewallLiteData.'**'.findAll {it.name() == "v4-firewall-packet-filters"}
759 def v4FirewallPacketFiltersSize = v4FirewallPacketFilters.size()
760 //println " v4FirewallPacketFiltersSize = " + v4FirewallPacketFilters.size()
761 for (i in 0..v4FirewallPacketFiltersSize-1) {
762 def v4FirewallPacketFilter = v4FirewallPacketFilters[i]
763 def v4FirewallPacketFilterXml = XmlUtil.serialize(v4FirewallPacketFilter)
764 rebuildingFirewallLite += "<tns2:v4-firewall-packet-filters>"
765 def v4FirewallPacketFiltersList = ["v4-firewall-prefix", "v4-firewall-prefix-length", "allow-icmp-ping"]
766 rebuildingFirewallLite += buildElements(v4FirewallPacketFilterXml, v4FirewallPacketFiltersList, "")
768 def udpPortsList = ["port-number"]
769 rebuildingFirewallLite += buildElementsUnbounded(v4FirewallPacketFilterXml, udpPortsList, "udp-ports")
770 } catch (Exception e) {
771 log("ERROR", " Optional - Exception FIREWALL-LITE v4 'udp-ports' ")
774 def tcpPortsList = ["port-number"]
775 rebuildingFirewallLite += buildElementsUnbounded(v4FirewallPacketFilterXml, tcpPortsList, "tcp-ports")
776 } catch (Exception e) {
777 log("ERROR", " Optional - Exception FIREWALL-LITE v4 'tcp-ports' ")
779 rebuildingFirewallLite += "</tns2:v4-firewall-packet-filters>"
781 } catch (Exception e) {
782 log("ERROR", " Optional - Exception FIREWALL-LITE 'v4-firewall-packet-filters' ")
786 def v6FirewallPacketFilters = firewallLiteData.'**'.findAll {it.name() == "v6-firewall-packet-filters"}
787 def v6FirewallPacketFiltersSize = v6FirewallPacketFilters.size()
788 //println " v6FirewallPacketFiltersSize = " + v6FirewallPacketFilters.size()
789 for (i in 0..v6FirewallPacketFiltersSize-1) {
790 def v6FirewallPacketFilter = v6FirewallPacketFilters[i]
791 def v6FirewallPacketFilterXml = XmlUtil.serialize(v6FirewallPacketFilter)
792 rebuildingFirewallLite += "<tns2:v6-firewall-packet-filters>"
793 def v6FirewallPacketFiltersList = ["v6-firewall-prefix", "v6-firewall-prefix-length", "allow-icmp-ping"]
794 rebuildingFirewallLite += buildElements(v6FirewallPacketFilterXml, v6FirewallPacketFiltersList, "")
796 def udpPortsList = ["port-number"]
797 rebuildingFirewallLite += buildElementsUnbounded(v6FirewallPacketFilterXml, udpPortsList, "udp-ports")
798 } catch (Exception e) {
799 log("ERROR", " Optional - Exception FIREWALL-LITE v6 'udp-ports' ")
802 def tcpPortsList = ["port-number"]
803 rebuildingFirewallLite += buildElementsUnbounded(v6FirewallPacketFilterXml, tcpPortsList, "tcp-ports")
804 } catch (Exception e) {
805 log("ERROR", " Optional - Exception FIREWALL-LITE v6 'tcp-ports' ")
807 rebuildingFirewallLite += "</tns2:v6-firewall-packet-filters>"
809 } catch (Exception e) {
810 log("ERROR", " Optional - Exception FIREWALL-LITE 'v6-firewall-packet-filters' ")
812 rebuildingFirewallLite+= "</tns2:firewall-lite>"
814 log("DEBUG", " rebuildingFirewallLite - " + rebuildingFirewallLite)
815 return rebuildingFirewallLite
818 def buildStaticRoutes(xmlInput) {
819 def rebuildingStaticRoutes = ''
820 if (xmlInput != null) {
821 rebuildingStaticRoutes = "<tns2:static-routes>"
822 def v4StaticRouteslist = ["v4-static-route-prefix","v4-static-route-prefix-length", "v4-next-hop-address"]
823 rebuildingStaticRoutes += buildElementsUnbounded(xmlInput, v4StaticRouteslist, "v4-static-routes")
824 def v6StaticRouteslist = ["v6-static-route-prefix","v6-static-route-prefix-length", "v6-next-hop-address"]
825 rebuildingStaticRoutes += buildElementsUnbounded(xmlInput, v6StaticRouteslist, "v6-static-routes")
826 rebuildingStaticRoutes += "</tns2:static-routes>"
828 log("DEBUG", " rebuildingStaticRoutes - " + rebuildingStaticRoutes)
829 return rebuildingStaticRoutes
832 public String generateCurrentTimeInUtc(){
833 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
834 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
835 final String utcTime = sdf.format(new Date());
839 public String generateCurrentTimeInGMT(){
840 final SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy h:m:s z");
841 sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
842 final String utcTime = sdf.format(new Date());
848 * @param encryptedAuth: encrypted credentials from urn properties
849 * @param msoKey: key to use to decrypt from urn properties
850 * @return base 64 encoded basic auth credentials
852 def getBasicAuth(encryptedAuth, msoKey){
854 def auth = decrypt(encryptedAuth, msoKey)
855 byte[] encoded = Base64.encodeBase64(auth.getBytes())
856 String encodedString = new String(encoded)
857 encodedString = "Basic " + encodedString
859 } catch (Exception ex) {
860 log("ERROR", "Unable to encode basic auth")
865 def encrypt(toEncrypt, msokey){
867 String result = CryptoUtils.encrypt(toEncrypt, msokey);
870 catch (Exception e) {
871 log("ERROR", "Failed to encrypt credentials")
875 def decrypt(toDecrypt, msokey){
877 String result = CryptoUtils.decrypt(toDecrypt, msokey);
880 catch (Exception e) {
881 log("ERROR", "Failed to decrypt credentials")
887 * Return URL with qualified host name (if any) or urn mapping
888 * @param String url from urn mapping
889 * @return String url with qualified host name
891 public String getQualifiedHostNameForCallback(String urnCallbackUrl) {
892 def callbackUrlToUse = urnCallbackUrl
894 //swap host name with qualified host name from the jboss properties
895 def qualifiedHostName = System.getProperty("jboss.qualified.host.name")
896 if(qualifiedHostName!=null){
897 log("DEBUG", "qualifiedHostName:\n" + qualifiedHostName)
898 callbackUrlToUse = callbackUrlToUse.replaceAll("(http://)(.*)(:28080*)", {orig, first, torepl, last -> "${first}${qualifiedHostName}${last}"})
901 log("DEBUG", "unable to grab qualified host name, using what's in urn properties for callbackurl. Exception was: " + e.printStackTrace())
903 return callbackUrlToUse
908 * Retrieves text context of the element if the element exists, returns empty string otherwise
909 * @param com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl element to parse
910 * param String tagName tagName
911 * @return String text content of the element
913 public String getElementText(Element element, String tagName) {
915 org.w3c.dom.NodeList nodeList = element.getElementsByTagNameNS("*", tagName)
916 if (nodeList != null && nodeList.length > 0) {
917 text = nodeList.item(0).getTextContent()
924 * Find the lowest unused module-index value in a given xml
926 public String getLowestUnusedIndex(String xml) {
927 if (xml == null || xml.isEmpty()) {
930 def moduleIndexList = getMultNodes(xml, "module-index")
931 if (moduleIndexList == null || moduleIndexList.size() == 0) {
934 def sortedModuleIndexList = moduleIndexList.sort { a, b -> a.compareTo b }
936 for (i in 0..sortedModuleIndexList.size()-1) {
937 if (Integer.parseInt(sortedModuleIndexList[i]) != i) {
941 return sortedModuleIndexList.size().toString()