Remove unnecessary use of Calendar.getInstance()
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / openecomp / mso / bpmn / common / scripts / MsoUtils.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 groovy.xml.XmlUtil
24
25 import java.text.SimpleDateFormat
26
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
34
35 class MsoUtils {
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")                       
39         }
40         def getNodeText(xmlInput,element){
41                 def rtn=null
42                 if(xmlInput!=null){
43                         def xml= new XmlSlurper().parseText(xmlInput)
44                         rtn= xml.'**'.find{node->node.name()==element}.text()
45                 }
46                 return rtn
47         }
48         def getMultNodes(xmlInput, element){
49                 def nodes=null
50                 if(xmlInput!=null){
51                         def xml= new XmlSlurper().parseText(xmlInput)
52                         nodes = xml.'**'.findAll{ node-> node.name() == element }*.text()
53                 }
54                 return nodes
55         }
56         def getNodeText1(xmlInput,element){
57                 def rtn=null
58                 if(xmlInput!=null){
59                         def xml= new XmlSlurper().parseText(xmlInput)
60                         rtn= xml.'**'.find{node->node.name()==element}
61                         if (rtn != null){
62                                 rtn=rtn.text()
63                         }
64                 }
65                 return rtn
66         }       
67         def getNodeXml(xmlInput,element){
68                 return getNodeXml(xmlInput, element, true)
69         }
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){
74                         return ""
75                 }
76                 def nodeAsText = XmlUtil.serialize(nodeToSerialize)
77                 if (!incPreamble) {
78                         nodeAsText = removeXmlPreamble(nodeAsText)
79                 }
80                 return nodeAsText               
81         }
82         def nodeExists(xmlInput,element){
83                 try {
84                         def fxml= new XmlSlurper().parseText(xmlInput)
85                         def nodeToSerialize = fxml.'**'.find {it.name() == element}
86                         return nodeToSerialize!=null
87                 } catch(Exception e) {
88                         return false
89                 }
90         }
91
92         
93         /***** Utilities when using XmlParser *****/
94         
95         /**
96          * Convert a Node into a String by deserializing it and formatting it.
97          *
98          * @param node Node to be converted.
99          * @return the Node as a String.
100          */
101         def String nodeToString(Node node) {
102                 def String nodeAsString = groovy.xml.XmlUtil.serialize(node)
103                 nodeAsString = removeXmlPreamble(nodeAsString)
104                 return formatXml(nodeAsString)
105         }
106         
107         /**
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.
111          * 
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.
116          */
117         def Node getChildNode(Node parent, String childNodeName) {
118                 def NodeList nodeList = getIdenticalChildren(parent, childNodeName)
119                 if (nodeList.size() == 0) {
120                         return null
121                 } else {
122                         return nodeList.get(0)
123                 }
124         }
125         
126         /**
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.
129          * 
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.
134          */
135         def String getChildNodeText(Node parent, String childNodeName) {
136                 def Node childNode = getChildNode(parent, childNodeName)
137                 if (childNode == null) {
138                         return null
139                 } else {
140                         return childNode.text()
141                 }
142         }
143         
144         /**
145          * Get all of the child nodes from the specified parent that have the
146          * specified name.  The returned NodeList could be empty.
147          * 
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.
152          */
153         def NodeList getIdenticalChildren(Node parent, String childNodeName) {
154                 return (NodeList) parent.get(childNodeName)
155         }
156
157         /***** End of Utilities when using XmlParser *****/
158
159         
160         /** these are covered under the common function above**/
161         def getSubscriberName(xmlInput,element){
162                 def rtn=null
163                 if(xmlInput!=null){
164                         def xml= new XmlSlurper().parseText(xmlInput)
165                         rtn= xml.'**'.find{node->node.name()==element}.text()
166                 } 
167                 return rtn
168         }
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)
173                 return nodeAsText
174         }
175         def getServiceInstanceId(xmlInput,element){
176                 def xml= new XmlSlurper().parseText(xmlInput)
177                 return ( xml.'**'.find{node->node.name()==element}.text() )
178         }
179         //for aai tenant url
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()
184         }
185
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}
189                 if(ret != null){
190                         return ret.parent().parent()
191                 }
192                 return ret
193         }
194         
195         def searchMetaDataNode(fxml, searchName, searchValue){
196                 def ret = fxml.'**'.find {it.metaname.text() == searchName && it.metaval.text() == searchValue}
197                 if(ret != null){
198                         return ret.parent().parent()
199                 }
200                 return ret
201         }
202         
203         // for Trinity L3 add/delete bonding
204         def getPBGFList(isDebugLogEnabled, xmlInput){
205                 xmlInput = xmlInput.replaceAll("&", "&")
206                 xmlInput = xmlInput.replaceAll("&lt;", "<")
207                 xmlInput = xmlInput.replaceAll("&gt;", ">")
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)
212                 if(respInfo!=null){
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/}
219                                                 def nodeToAdd
220                                                 physNodes.each{
221                                                         if(nodeToAdd==null){
222                                                                 nodeToAdd = it
223                                                         }else{
224                                                                 def beid = nodeToAdd.'border-element-id'.text() +
225                                                                          " " + nodeToAdd.'border-element-type'.text() +
226                                                                          " and " +
227                                                                          it.'border-element-id'.text() +
228                                                                          " " + it.'border-element-type'.text()
229                                                                 def mytag = nodeToAdd.'border-element-id'
230                                                                 mytag[0].replaceBody(beid)
231                                                         }
232                                                 }
233                                                 def mytag = nodeToAdd.'vlan-id'
234                                                 def ind = mytag.text().indexOf('.')
235                                                 if(ind >= 0){
236                                                         def vlan = mytag.text().substring(0,ind)
237                                                         mytag[0].replaceBody(vlan)
238                                                 }
239                                                 myNodes.add(XmlUtil.serialize(nodeToAdd))
240                                         }
241                                         
242                         }
243                 }
244                                 
245                         return myNodes
246                 }else{
247                         return null
248                 }
249         }
250         
251         def getPBGFList(xmlInput){
252                 getPBGFList("false", xmlInput)
253         }
254         
255         def String decodeXML(xml) {
256                 def String decodedXml = xml.replaceAll("&amp;", "&")
257                 decodedXml = decodedXml.replaceAll("&lt;", "<")
258                 decodedXml = decodedXml.replaceAll("&gt;", ">")
259         }
260         
261         def getMetaVal(node, name){
262                 try{
263                         return node.'**'.find {it.metaname.text() == name}.metaval.text()
264                 }catch(Exception e){
265                         return null
266                 }
267         }
268         def getRelationshipVal(node, name){
269                 try{
270                         return node.'**'.find {it.'relationship-key'.text() == name}.'relationship-value'.text()
271                 }catch(Exception e){
272                         return null
273                 }
274         }
275
276         
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);
285                         
286                 } else {
287                         BPMNLogger.debug(isDebugLogEnabled, logtxt);
288                 }
289         }
290         
291         def logContext(requestId, serviceInstanceId){
292             MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
293                 msoLogger.setLogContext(requestId, serviceInstanceId);
294         }
295         
296         def logMetrics(elapsedTime, logtxt){
297                 MsoLogger metricsLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
298                 
299                 metricsLogger.recordMetricEvent (elapsedTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
300                         logtxt, "BPMN", MsoLogger.getServiceName(), null);
301         }
302         
303         def logAudit(logtxt){
304                 MsoLogger auditLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
305                 long startTime = System.currentTimeMillis();
306                 
307                 auditLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logtxt);
308         }
309         
310         // headers: header - name-value
311         def getHeaderNameValue(xmlInput, nameAttribute){
312                 def rtn=null
313                 if(xmlInput!=null){
314                         def xml= new XmlSlurper().parseText(xmlInput)
315                         rtn= xml.'**'.find {header->header.'@name'.text() == nameAttribute}.'@value'
316                 }
317                 return rtn
318         }
319         
320         /**
321          * Gets the children of the specified element.
322          */
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())
332                                 }
333                                 out.append(nodeAsText)
334                         }
335                 }
336                 return out.toString();
337         }
338         
339         /**
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
343          */
344         public String xmlEncode(Object value) {
345                 return XmlTool.encode(value)
346         }
347         
348         /**
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
352          */
353         public String xmlEncodeAttr(Object value) {
354                 return XmlTool.encodeAttr(value)
355         }
356         
357         /**
358          * Decodes XML entities in a string value
359          * @param value a value with embedded XML entities
360          * @return the decoded string
361          */
362         public String xmlDecode(Object value) {
363                 return XmlTool.decode(value)
364         }
365         
366         /**
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
373          */
374         public String removeXmlPreamble(def xml) {
375                 if (xml == null) {
376                         return null
377                 }
378
379                 return XmlTool.removePreamble(xml).trim()
380         }
381
382         /**
383          * Removes namespaces and namespace declarations from an XML document.
384          * @param xml the XML document
385          * @return a possibly modified document
386          */
387         public String removeXmlNamespaces(def xml) {
388                 return XmlTool.removeNamespaces(xml);
389         }
390
391         /**
392          * Use formatXml instead.  Note: this method inserts an XML preamble.
393          */
394         @Deprecated
395         def formatXML(xmlInput) {
396                 def parseXml = null
397                 def formatXml = null
398                 if (xmlInput !=null) {
399                         parseXml = new XmlParser().parseText(xmlInput)
400                         formatXml = XmlUtil.serialize(parseXml)
401                 }
402         }
403
404         /**
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
409          */
410         public String formatXml(def xml) {
411                 return XmlTool.normalize(xml);
412         }
413         
414         // build single elements
415         def buildElements(xmlInput, elementList, parentName) {
416                 String var = ""
417                 def xmlBuild = ""
418                 if (parentName != "") {
419                    xmlBuild += "<tns2:"+parentName+">"
420                 }   
421                 if (xmlInput != null) {
422                            for (element in elementList) {
423                               def xml= new XmlSlurper().parseText(xmlInput)
424                               var = xml.'**'.find {it.name() == element}
425                                   if (var != null) {
426                                  xmlBuild += "<tns2:"+element+">"+var.toString()+"</tns2:"+element+">"
427                                   } 
428                            }
429                 }
430                 if (parentName != "") {
431                    xmlBuild += "</tns2:"+parentName+">"
432                 }   
433                 return xmlBuild
434         }
435         
436         // build the Unbounded elements
437         def buildElementsUnbounded(xmlInput, elementList, parentName) {
438                 def varParents = ""
439                 def var = ""
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+">"
448                                  }
449                                 for (element in elementList) {
450                                         var = varParents[i].'*'.find {it.name() == element}
451                                    if (var != null) {
452                                           xmlBuildUnbounded += "<tns2:"+element+">"+var.toString()+"</tns2:"+element+">"
453                                           //println " i = " + i + ", element: " + element + " = " + var.toString()
454                                    }
455                                 }
456                                 if (parentName != "") {
457                                         xmlBuildUnbounded += "</tns2:"+parentName+">"
458                                  }
459                         }
460                 }
461                 return xmlBuildUnbounded
462          }
463         
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")
470                 }
471                 return rebuildL2Home
472         }
473         
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")
480                 }
481                 return rebuildInternetEvcAccess
482         }
483         
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, "")
495                         try { // optional
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' ")
500                         }
501                         rebuildUcpeVmsServiceInformation += "</tns2:transport-service-information>"
502                         // ucpe-information
503                         def elementsUcpeInformationList = ["ucpe-host-name", "ucpe-activation-code", "out-of-band-management-modem" ]
504                         rebuildUcpeVmsServiceInformation += buildElements(ucpeVmsServiceInformation, elementsUcpeInformationList, "ucpe-information")
505                         // vnf-list
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>"
511                 }
512                 log("DEBUG", " rebuildUcpeVmsServiceInformation - " + rebuildUcpeVmsServiceInformation)
513                 return rebuildUcpeVmsServiceInformation
514         }
515         
516     // Build internet-service-change-details
517         def buildInternetServiceChangeDetails(xmlInput) {
518                 def rebuildInternetServiceChangeDetails = ""
519                 if (xmlInput != null) {
520                     try { // optional
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"], "")
525                                 try { // optional
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 ")
530                             }
531                                 try { // optional
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 ")
536                                 }
537                                 rebuildInternetServiceChangeDetails += "</tns:internet-service-change-details>"
538                         } catch (Exception e) {
539                                 log("ERROR", " Optional - Exception INTERNET-SERVICE-CHANGE-DETAILS 'internet-service-change-details' ")
540                         }
541                 }
542             return rebuildInternetServiceChangeDetails
543         }               
544         
545         // Build vr-lan 
546         def buildVrLan(xmlInput) {
547                 
548                 def rebuildVrLan = ''
549                 if (xmlInput != null) {
550                         
551                         rebuildVrLan = "<tns2:vr-lan>"
552                         def vrLan = getNodeXml(xmlInput, "vr-lan").drop(38).trim()
553                         rebuildVrLan += buildElements(vrLan, ["routing-protocol"], "")
554                         
555                         // vr-lan-interface
556                         def rebuildVrLanInterface = "<tns2:vr-lan-interface>"
557                         def vrLanInterface = getNodeXml(vrLan, "vr-lan-interface").drop(38).trim()
558                         rebuildVrLanInterface += buildVrLanInterfacePartial(vrLanInterface)
559                         
560                          // dhcp
561                          def dhcp = getNodeXml(vrLan, "dhcp").drop(38).trim()
562                          def rebuildDhcp = buildDhcp(dhcp)
563                          rebuildVrLanInterface += rebuildDhcp
564                          
565                          // pat
566                          def pat = getNodeXml(vrLan, "pat").drop(38).trim()
567                          def rebuildPat = buildPat(pat)
568                          rebuildVrLanInterface += rebuildPat
569                          
570                          // nat
571                          def rebuildNat = ""
572                          try { // optional
573                                 def nat = getNodeXml(vrLan, "nat").drop(38).trim()
574                                 rebuildNat = buildNat(nat)
575                          } catch (Exception e) {
576                                  log("ERROR", " Optional - Exception 'nat' ")
577                          }
578                          rebuildVrLanInterface += rebuildNat
579                                                                                 
580                          // firewall-lite
581                          def firewallLite = getNodeXml(vrLan, "firewall-lite").drop(38).trim()
582                          def rebuildFirewallLite = buildFirewallLite(firewallLite)
583                          rebuildVrLanInterface += rebuildFirewallLite
584                          
585                          // static-routes
586                          def rebuildStaticRoutes = ""
587                          try { // optional 
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' ")
592                         }
593                         rebuildVrLanInterface += rebuildStaticRoutes
594                          
595                    rebuildVrLan += rebuildVrLanInterface
596                    rebuildVrLan += "</tns2:vr-lan-interface>"
597                    rebuildVrLan += "</tns2:vr-lan>"
598                         
599                 }
600                 log("DEBUG", " rebuildVrLan - " + rebuildVrLan)
601                 return rebuildVrLan             
602         }
603         
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>"
611                         try { // optional
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' ")
617                         }
618                         rebuildingVrLanInterface += "</tns2:v4-public-lan-prefixes>"
619                         rebuildingVrLanInterface += "<tns2:v6-public-lan-prefixes>"
620                         try { // optional
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' ")
626                         }
627                         rebuildingVrLanInterface += "</tns2:v6-public-lan-prefixes>"
628                 }
629                 log("DEBUG", " rebuildingVrLanInterface - " + rebuildingVrLanInterface)
630                 return rebuildingVrLanInterface
631         }
632         
633         // Build dhcp
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, "")
641                         try { // optional
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' ")
646                         }
647                         try { // optional
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, "")
657                                         try { // optional
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' ")
662                                         }
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>"
666                                  }
667                          } catch (Exception e) {
668                                   log("ERROR"," Optional - Exception DHCP 'v4-dhcp-pools' ")
669                          }
670                          def dhcpList2 = ["use-v6-default-pool", "v6-dhcp-default-pool-prefix", "v6-dhcp-default-pool-prefix-length"]
671                          rebuildingDhcp += buildElements(xmlInput, dhcpList2, "")
672                          try { // optional
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' ")
677                          }
678                          try { // optional
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, "")
688                                         try { // optional
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' ")
693                                         }
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>"
697                                  }
698                          } catch (Exception e) {
699                                  log("ERROR", " Optional - Exception DHCP 'v6-dhcp-pools' ")
700                          }
701                          rebuildingDhcp += "</tns2:dhcp>"
702                 }        
703                 log("DEBUG", " rebuildingDhcp - " + rebuildingDhcp)
704                 return rebuildingDhcp
705         }       
706
707         // Build pat
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, "")
714                          try { // optional
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' ")
720                          }
721                          rebuildingPat += "</tns2:pat>"
722                  }
723                  log("DEBUG", " rebuildingPat - " + rebuildingPat)
724              return rebuildingPat
725     }
726         
727         // Build nat
728         def buildNat(xmlInput) {
729                 def rebuildingNat = ''
730                 if (xmlInput != null) {
731                         rebuildingNat = "<tns2:nat>"
732                         rebuildingNat += buildElements(xmlInput, ["v4-nat-enabled"], "")
733                         try { // optional
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' ")
739                         }
740                         rebuildingNat += "</tns2:nat>"
741                 }
742                 log("DEBUG", " rebuildingNat - " + rebuildingNat)
743             return rebuildingNat
744         }                               
745         
746         // Build firewall-lite
747         def buildFirewallLite(xmlInput) {
748                 def rebuildingFirewallLite = ''
749                 
750                 if (xmlInput != null) {
751                         
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, "")
756                         
757                          try { // optional
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, "")
767                                    try {  // optional
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' ")
772                                    }
773                                    try {  // optional
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' ")
778                                    }
779                                    rebuildingFirewallLite += "</tns2:v4-firewall-packet-filters>"
780                                  }
781                          } catch (Exception e) {
782                                  log("ERROR", " Optional - Exception FIREWALL-LITE 'v4-firewall-packet-filters' ")
783                          }
784                          
785                          try { // optional
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, "")
795                                         try { // optional
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' ")
800                                         }
801                                         try { // optional
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' ")
806                                         }
807                                rebuildingFirewallLite += "</tns2:v6-firewall-packet-filters>"
808                                  }
809                          } catch (Exception e) {
810                                  log("ERROR", " Optional - Exception FIREWALL-LITE 'v6-firewall-packet-filters' ")
811                          }
812                          rebuildingFirewallLite+= "</tns2:firewall-lite>"
813                 }
814                 log("DEBUG", " rebuildingFirewallLite - " + rebuildingFirewallLite)
815                 return rebuildingFirewallLite
816      }
817         
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>"
827                 }
828                 log("DEBUG", " rebuildingStaticRoutes - " + rebuildingStaticRoutes)
829                 return rebuildingStaticRoutes
830         }
831         
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());
836                 return utcTime;
837         }
838         
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());
843                 return utcTime;
844         }
845         
846
847         /**
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
851          */
852         def getBasicAuth(encryptedAuth, msoKey){
853                 try {
854                         def auth = decrypt(encryptedAuth, msoKey)
855                         byte[] encoded = Base64.encodeBase64(auth.getBytes())
856                         String encodedString = new String(encoded)
857                         encodedString = "Basic " + encodedString
858                         return encodedString
859                 } catch (Exception ex) {
860                         log("ERROR", "Unable to encode basic auth")
861                         throw ex
862                 }
863         }
864         
865         def encrypt(toEncrypt, msokey){
866                 try {
867                         String result = CryptoUtils.encrypt(toEncrypt, msokey);
868                         return result
869                 }
870                 catch (Exception e) {
871                         log("ERROR", "Failed to encrypt credentials")
872                 }
873         }
874         
875         def decrypt(toDecrypt, msokey){
876                 try {
877                         String result = CryptoUtils.decrypt(toDecrypt, msokey);
878                         return result
879                 }
880                 catch (Exception e) {
881                         log("ERROR", "Failed to decrypt credentials")
882                         throw e
883                 }
884         }
885         
886         /**
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
890          */
891         public String getQualifiedHostNameForCallback(String urnCallbackUrl) {
892                 def callbackUrlToUse = urnCallbackUrl
893                 try{
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}"})
899                         }
900                 }catch(Exception e){
901                                 log("DEBUG", "unable to grab qualified host name, using what's in urn properties for callbackurl. Exception was: " + e.printStackTrace())
902                 }
903                 return callbackUrlToUse
904                 
905         }
906         
907         /**
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
912          */
913          public String getElementText(Element element, String tagName) {
914                 String text = ""
915                 org.w3c.dom.NodeList nodeList = element.getElementsByTagNameNS("*", tagName)
916                 if (nodeList != null && nodeList.length > 0) {
917                         text = nodeList.item(0).getTextContent()
918                 }
919                 return text
920          }
921          
922          /**
923           *
924           * Find the lowest unused module-index value in a given xml
925           */
926          public String getLowestUnusedIndex(String xml) {
927                  if (xml == null || xml.isEmpty()) {
928                          return "0"
929                  }               
930                  def moduleIndexList = getMultNodes(xml, "module-index") 
931                  if (moduleIndexList == null || moduleIndexList.size() == 0) {                  
932                          return "0"
933                  }
934                  def sortedModuleIndexList = moduleIndexList.sort { a, b -> a.compareTo b }
935                 
936                  for (i in 0..sortedModuleIndexList.size()-1) {
937                          if (Integer.parseInt(sortedModuleIndexList[i]) != i) {
938                                  return i.toString()
939                          }
940                  }
941                  return sortedModuleIndexList.size().toString()
942          }
943
944 }