Initial OpenECOMP MSO commit
[so.git] / bpmn / MSOGammaBPMN / src / main / groovy / com / att / bpm / 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 com.att.bpm.scripts
22
23 import groovy.util.Node;
24 import groovy.xml.XmlUtil
25
26 import java.text.SimpleDateFormat
27
28 import org.apache.commons.codec.binary.Base64
29
30
31
32 import org.apache.commons.codec.binary.Base64
33 import org.camunda.bpm.engine.runtime.Execution;
34 import org.slf4j.MDC;
35 import org.w3c.dom.Element
36 //import org.w3c.dom.NodeList
37
38 import org.openecomp.mso.bpmn.core.BPMNLogger
39 import org.openecomp.mso.logger.MessageEnum
40 import org.openecomp.mso.logger.MsoLogger
41 import org.openecomp.mso.utils.CryptoUtils
42 import org.openecomp.mso.bpmn.core.xml.XmlTool
43
44 class MsoUtils {
45         def initializeEndPoints(execution){
46                 // use this placeholder to initialize end points, if called independently, this need to be set
47                 execution.setVariable("AAIEndPoint","http://localhost:8080/SoapUIMocks")                        
48         }
49         def getNodeText(xmlInput,element){
50                 def rtn=null
51                 if(xmlInput!=null){
52                         def xml= new XmlSlurper().parseText(xmlInput)
53                         rtn= xml.'**'.find{node->node.name()==element}.text()
54                 }
55                 return rtn
56         }
57         def getMultNodes(xmlInput, element){
58                 def nodes=null
59                 if(xmlInput!=null){
60                         def xml= new XmlSlurper().parseText(xmlInput)
61                         nodes = xml.'**'.findAll{ node-> node.name() == element }*.text()
62                 }
63                 return nodes
64         }
65         def getNodeText1(xmlInput,element){
66                 def rtn=null
67                 if(xmlInput!=null){
68                         def xml= new XmlSlurper().parseText(xmlInput)
69                         rtn= xml.'**'.find{node->node.name()==element}
70                         if (rtn != null){
71                                 rtn=rtn.text()
72                         }
73                 }
74                 return rtn
75         }       
76         def getNodeXml(xmlInput,element){
77                 return getNodeXml(xmlInput, element, true)
78         }
79         def getNodeXml(xmlInput,element,incPreamble){
80                 def fxml= new XmlSlurper().parseText(xmlInput)
81                 def nodeToSerialize = fxml.'**'.find {it.name() == element}
82                 if(nodeToSerialize==null){
83                         return ""
84                 }
85                 def nodeAsText = XmlUtil.serialize(nodeToSerialize)
86                 if (!incPreamble) {
87                         nodeAsText = removeXmlPreamble(nodeAsText)
88                 }
89                 return nodeAsText               
90         }
91         def nodeExists(xmlInput,element){
92                 try {
93                         def fxml= new XmlSlurper().parseText(xmlInput)
94                         def nodeToSerialize = fxml.'**'.find {it.name() == element}
95                         return nodeToSerialize!=null
96                 } catch(Exception e) {
97                         return false
98                 }
99         }
100
101         
102         /***** Utilities when using XmlParser *****/
103         
104         /**
105          * Convert a Node into a String by deserializing it and formatting it.
106          *
107          * @param node Node to be converted.
108          * @return the Node as a String.
109          */
110         def String nodeToString(Node node) {
111                 def String nodeAsString = groovy.xml.XmlUtil.serialize(node)
112                 nodeAsString = removeXmlPreamble(nodeAsString)
113                 return formatXml(nodeAsString)
114         }
115         
116         /**
117          * Get the specified child Node of the specified parent. If there are
118          * multiple children of the same name, only the first one is returned.
119          * If there are no children with the specified name, 'null' is returned.
120          * 
121          * @param parent Parent Node in which to find a child.
122          * @param childNodeName Name of the child Node to get.
123          * @return the (first) child Node with the specified name or 'null'
124          * if a child Node with the specified name does not exist.
125          */
126         def Node getChildNode(Node parent, String childNodeName) {
127                 def NodeList nodeList = getIdenticalChildren(parent, childNodeName)
128                 if (nodeList.size() == 0) {
129                         return null
130                 } else {
131                         return nodeList.get(0)
132                 }
133         }
134         
135         /**
136          * Get the textual value of the specified child Node of the specified parent.
137          * If there are no children with the specified name, 'null' is returned.
138          * 
139          * @param parent Parent Node in which to find a child.
140          * @param childNodeName Name of the child Node whose value to get.
141          * @return the textual value of child Node with the specified name or 'null'
142          * if a child Node with the specified name does not exist.
143          */
144         def String getChildNodeText(Node parent, String childNodeName) {
145                 def Node childNode = getChildNode(parent, childNodeName)
146                 if (childNode == null) {
147                         return null
148                 } else {
149                         return childNode.text()
150                 }
151         }
152         
153         /**
154          * Get all of the child nodes from the specified parent that have the
155          * specified name.  The returned NodeList could be empty.
156          * 
157          * @param parent Parent Node in which to find children.
158          * @param childNodeName Name of the children to get.
159          * @return a NodeList of all the children from the parent with the specified
160          * name. The list could be empty.
161          */
162         def NodeList getIdenticalChildren(Node parent, String childNodeName) {
163                 return (NodeList) parent.get(childNodeName)
164         }
165
166         /***** End of Utilities when using XmlParser *****/
167
168         
169         /** these are covered under the common function above**/
170         def getSubscriberName(xmlInput,element){
171                 def rtn=null
172                 if(xmlInput!=null){
173                         def xml= new XmlSlurper().parseText(xmlInput)
174                         rtn= xml.'**'.find{node->node.name()==element}.text()
175                 } 
176                 return rtn
177         }
178         def getTenantInformation(xmlInput,element){
179                 def xml= new XmlSlurper().parseText(xmlInput)
180                 def nodeToSerialize = xml.'**'.find {it.name() == 'service-information'}
181                 def nodeAsText = XmlUtil.serialize(nodeToSerialize)
182                 return nodeAsText
183         }
184         def getServiceInstanceId(xmlInput,element){
185                 def xml= new XmlSlurper().parseText(xmlInput)
186                 return ( xml.'**'.find{node->node.name()==element}.text() )
187         }
188         //for aai tenant url
189         def searchResourceLink(xmlInput, resourceType){
190                 def fxml= new XmlSlurper().parseText(xmlInput)
191                 def element = fxml.'**'.find {it.'resource-type' == resourceType}
192                 return (element == null) ? null : element.'resource-link'.text()
193         }
194
195         def searchMetaData(xmlInput, searchName, searchValue){
196                 def fxml= new XmlSlurper().parseText(xmlInput)
197                 def ret = fxml.'**'.find {it.metaname.text() == searchName && it.metaval.text() == searchValue}
198                 if(ret != null){
199                         return ret.parent().parent()
200                 }
201                 return ret
202         }
203         
204         def searchMetaDataNode(fxml, searchName, searchValue){
205                 def ret = fxml.'**'.find {it.metaname.text() == searchName && it.metaval.text() == searchValue}
206                 if(ret != null){
207                         return ret.parent().parent()
208                 }
209                 return ret
210         }
211         
212         // for Trinity L3 delete bonding
213         def getPBGFList(isDebugLogEnabled, xmlInput){
214                 xmlInput = xmlInput.replaceAll("&", "&")
215                 xmlInput = xmlInput.replaceAll("&lt;", "<")
216                 xmlInput = xmlInput.replaceAll("&gt;", ">")
217                 log("DEBUG", "getPBGFList: xmlInput " + xmlInput,isDebugLogEnabled)
218                 ArrayList myNodes = new ArrayList()
219                 if(nodeExists(xmlInput,"nbnc-response-information")){
220                 def respInfo=getNodeXml(xmlInput,"nbnc-response-information", false)
221                 if(respInfo!=null){
222                         def fxml= new XmlSlurper().parseText(respInfo)
223                         def myNode
224                         fxml.'virtual-datacenter-list'.each { vdc ->
225                                 //we only want to add one BFG per VDC
226                                 log("DEBUG", "vdc " + vdc.text(),isDebugLogEnabled)
227                                 myNode = vdc.'**'.find {it.'border-element-tangibility'.text() =~ /PHYSICAL/}
228                                 log("DEBUG", "myNode " + myNode.text(),isDebugLogEnabled)
229                                 myNodes.add(XmlUtil.serialize(myNode))
230                         }
231                 }
232                                 
233                         return myNodes
234                 }else{
235                         return null
236                 }
237         }
238         
239         def getPBGFList(xmlInput){
240                 getPBGFList("false", xmlInput)
241         }
242         
243         def String decodeXML(xml) {
244                 def String decodedXml = xml.replaceAll("&amp;", "&")
245                 decodedXml = decodedXml.replaceAll("&lt;", "<")
246                 decodedXml = decodedXml.replaceAll("&gt;", ">")
247         }
248         
249         def getMetaVal(node, name){
250                 try{
251                         return node.'**'.find {it.metaname.text() == name}.metaval.text()
252                 }catch(Exception e){
253                         return null
254                 }
255         }
256         def getRelationshipVal(node, name){
257                 try{
258                         return node.'**'.find {it.'relationship-key'.text() == name}.'relationship-value'.text()
259                 }catch(Exception e){
260                         return null
261                 }
262         }
263
264         
265         def log(logmode,logtxt,isDebugLogEnabled="false"){
266                 MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
267                 if ("INFO"==logmode) {
268                         msoLogger.info(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, logtxt);
269                 } else if ("WARN"==logmode) {
270                         msoLogger.warn (MessageEnum.BPMN_GENERAL_WARNING, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logtxt);
271                 } else if ("ERROR"==logmode) {
272                     msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logtxt);
273                         
274                 } else {
275                         BPMNLogger.debug(isDebugLogEnabled, logtxt);
276                 }
277         }
278         
279         def logContext(requestId, serviceInstanceId){
280             MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
281                 msoLogger.setLogContext(requestId, serviceInstanceId);
282         }
283         
284         def logMetrics(elapsedTime, logtxt){
285                 MsoLogger metricsLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
286                 
287                 metricsLogger.recordMetricEvent (elapsedTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
288                         logtxt, "BPMN", MsoLogger.getServiceName(), null);
289         }
290         
291         def logAudit(logtxt){
292                 MsoLogger auditLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
293                 long startTime = System.currentTimeMillis();
294                 
295                 auditLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logtxt);
296         }
297         
298         // headers: header - name-value
299         def getHeaderNameValue(xmlInput, nameAttribute){
300                 def rtn=null
301                 if(xmlInput!=null){
302                         def xml= new XmlSlurper().parseText(xmlInput)
303                         rtn= xml.'**'.find {header->header.'@name'.text() == nameAttribute}.'@value'
304                 }
305                 return rtn
306         }
307         
308         /**
309          * Gets the children of the specified element.
310          */
311         public String getChildNodes(xmlInput, element) {
312                 def xml= new XmlSlurper().parseText(xmlInput)
313                 def thisElement = xml.'**'.find {it.name() == element}
314                 StringBuilder out = new StringBuilder()
315                 if (thisElement != null) {
316                         thisElement.children().each() {
317                                 String nodeAsText = removeXmlPreamble(XmlUtil.serialize(it))
318                                 if (out.length() > 0) {
319                                         out.append(System.lineSeparator())
320                                 }
321                                 out.append(nodeAsText)
322                         }
323                 }
324                 return out.toString();
325         }
326         
327         /**
328          * Encodes a value so it can be used inside an XML text element.
329          * @param s the string to encode
330          * @return the encoded string
331          */
332         public String xmlEncode(Object value) {
333                 return XmlTool.encode(value)
334         }
335         
336         /**
337          * Encodes a value so it can be used inside an XML attribute.
338          * @param s the string to encode
339          * @return the encoded string
340          */
341         public String xmlEncodeAttr(Object value) {
342                 return XmlTool.encodeAttr(value)
343         }
344         
345         /**
346          * Decodes XML entities in a string value
347          * @param value a value with embedded XML entities
348          * @return the decoded string
349          */
350         public String xmlDecode(Object value) {
351                 return XmlTool.decode(value)
352         }
353         
354         /**
355          * Removes the preamble, if present, from an XML document.
356          * Also, for historical reasons, this also trims leading and trailing
357          * whitespace from the resulting document.  TODO: remove the trimming
358          * and fix unit tests that depend on EXACT xml format.
359          * @param xml the XML document
360          * @return a possibly modified document
361          */
362         public String removeXmlPreamble(def xml) {
363                 if (xml == null) {
364                         return null
365                 }
366
367                 return XmlTool.removePreamble(xml).trim()
368         }
369
370         /**
371          * Removes namespaces and namespace declarations from an XML document.
372          * @param xml the XML document
373          * @return a possibly modified document
374          */
375         public String removeXmlNamespaces(def xml) {
376                 return XmlTool.removeNamespaces(xml);
377         }
378
379         /**
380          * Use formatXml instead.  Note: this method inserts an XML preamble.
381          */
382         @Deprecated
383         def formatXML(xmlInput) {
384                 def parseXml = null
385                 def formatXml = null
386                 if (xmlInput !=null) {
387                         parseXml = new XmlParser().parseText(xmlInput)
388                         formatXml = XmlUtil.serialize(parseXml)
389                 }
390         }
391
392         /**
393          * Reformats an XML document. The result will not contain an XML preamble
394          * or a trailing newline.
395          * @param xml the XML document
396          * @return a reformatted document
397          */
398         public String formatXml(def xml) {
399                 return XmlTool.normalize(xml);
400         }
401         
402         // build single elements
403         def buildElements(xmlInput, elementList, parentName) {
404                 String var = ""
405                 def xmlBuild = ""
406                 if (parentName != "") {
407                    xmlBuild += "<tns2:"+parentName+">"
408                 }   
409                 if (xmlInput != null) {
410                            for (element in elementList) {
411                               def xml= new XmlSlurper().parseText(xmlInput)
412                               var = xml.'**'.find {it.name() == element}
413                                   if (var != null) {
414                                  xmlBuild += "<tns2:"+element+">"+var.toString()+"</tns2:"+element+">"
415                                   } 
416                            }
417                 }
418                 if (parentName != "") {
419                    xmlBuild += "</tns2:"+parentName+">"
420                 }   
421                 return xmlBuild
422         }
423         
424         // build the Unbounded elements
425         def buildElementsUnbounded(xmlInput, elementList, parentName) {
426                 def varParents = ""
427                 def var = ""
428                 def xmlBuildUnbounded = ""
429                 if (xmlInput != null) {
430                         def xml= new XmlSlurper().parseText(xmlInput)
431                         varParents = xml.'**'.findAll {it.name() == parentName}
432                         //println " Unbounded ${parentName} - varParent.Size() - " + varParents.size()
433                         for (i in 0..varParents.size()-1) {
434                                 if (parentName != "") {
435                                         xmlBuildUnbounded += "<tns2:"+parentName+">"
436                                  }
437                                 for (element in elementList) {
438                                         var = varParents[i].'*'.find {it.name() == element}
439                                    if (var != null) {
440                                           xmlBuildUnbounded += "<tns2:"+element+">"+var.toString()+"</tns2:"+element+">"
441                                           //println " i = " + i + ", element: " + element + " = " + var.toString()
442                                    }
443                                 }
444                                 if (parentName != "") {
445                                         xmlBuildUnbounded += "</tns2:"+parentName+">"
446                                  }
447                         }
448                 }
449                 return xmlBuildUnbounded
450          }
451         
452         // Build internet-evc-access-information
453         def buildInternetEvcAccessInformation(xmlInput) {
454                 def elementsInternetEvcAccessInformationList = ["internet-evc-speed-value", "internet-evc-speed-units", "ip-version"]
455                 def rebuildInternetEvcAccess = ''
456                 if (xmlInput != null) {
457                         rebuildInternetEvcAccess = buildElements(xmlInput, elementsInternetEvcAccessInformationList, "internet-evc-access-information")
458                 }
459                 return rebuildInternetEvcAccess
460         }
461         
462     // Build internet-service-change-details
463         def buildInternetServiceChangeDetails(xmlInput) {
464                 def rebuildInternetServiceChangeDetails = ""
465                 if (xmlInput != null) {
466                     try { // optional
467                                 def internetServiceChangeDetails = getNodeXml(xmlInput, "internet-service-change-details").drop(38).trim()
468                                 rebuildInternetServiceChangeDetails = "<tns:internet-service-change-details>"
469                                 rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-value"], "")
470                                 rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-units"], "")
471                                 def tProvidedV4LanPublicPrefixesChangesList = ["request-index", "v4-next-hop-address", "v4-lan-public-prefix", "v4-lan-public-prefix-length"]
472                                 rebuildInternetServiceChangeDetails += buildElementsUnbounded(internetServiceChangeDetails, tProvidedV4LanPublicPrefixesChangesList, "t-provided-v4-lan-public-prefixes")
473                                 try { // optional
474                                   def tProvidedV6LanPublicPrefixesChangesList = ["request-index", "v6-next-hop-address", "v6-lan-public-prefix", "v6-lan-public-prefix-length"]
475                                   rebuildInternetServiceChangeDetails += buildElementsUnbounded(internetServiceChangeDetails, tProvidedV6LanPublicPrefixesChangesList, "t-provided-v6-lan-public-prefixes")
476                                 } catch (Exception e) {
477                                         log("ERROR"," Optional - Exception INTERNET-SERVICE-CHANGE-DETAILS 't-provided-v6-lan-public-prefixes ")
478                                 }
479                                 rebuildInternetServiceChangeDetails += "</tns:internet-service-change-details>"
480                         } catch (Exception e) {
481                                 log("ERROR", " Optional - Exception INTERNET-SERVICE-CHANGE-DETAILS 'internet-service-change-details' ")
482                         }
483                 }
484             return rebuildInternetServiceChangeDetails
485         }               
486         
487         // Build vr-lan 
488         def buildVrLan(xmlInput) {
489                 
490                 def rebuildVrLan = ''
491                 if (xmlInput != null) {
492                         
493                         rebuildVrLan = "<tns2:vr-lan>"
494                         def vrLan = getNodeXml(xmlInput, "vr-lan").drop(38).trim()
495                         rebuildVrLan += buildElements(vrLan, ["routing-protocol"], "")
496                         
497                         // vr-lan-interface
498                         def rebuildVrLanInterface = "<tns2:vr-lan-interface>"
499                         def vrLanInterface = getNodeXml(vrLan, "vr-lan-interface").drop(38).trim()
500                         rebuildVrLanInterface += buildVrLanInterfacePartial(vrLanInterface)
501                         
502                          // dhcp
503                          def dhcp = getNodeXml(vrLan, "dhcp").drop(38).trim()
504                          def rebuildDhcp = buildDhcp(dhcp)
505                          rebuildVrLanInterface += rebuildDhcp
506                          
507                          // pat
508                          def pat = getNodeXml(vrLan, "pat").drop(38).trim()
509                          def rebuildPat = buildPat(pat)
510                          rebuildVrLanInterface += rebuildPat
511                          
512                          // nat
513                          def rebuildNat = ""
514                          try { // optional
515                                 def nat = getNodeXml(vrLan, "nat").drop(38).trim()
516                                 rebuildNat = buildNat(nat)
517                          } catch (Exception e) {
518                                  log("ERROR", " Optional - Exception 'nat' ")
519                          }
520                          rebuildVrLanInterface += rebuildNat
521                                                                                 
522                          // firewall-lite
523                          def firewallLite = getNodeXml(vrLan, "firewall-lite").drop(38).trim()
524                          def rebuildFirewallLite = buildFirewallLite(firewallLite)
525                          rebuildVrLanInterface += rebuildFirewallLite
526                          
527                          // static-routes
528                          def rebuildStaticRoutes = ""
529                          try { // optional 
530                                  def staticRoutes = getNodeXml(vrLan, "static-routes").drop(38).trim()
531                                  rebuildStaticRoutes = buildStaticRoutes(staticRoutes)
532                         } catch (Exception e) {
533                                  log("ERROR", " Optional - Exception 'static-routes' ")
534                         }
535                         rebuildVrLanInterface += rebuildStaticRoutes
536                          
537                    rebuildVrLan += rebuildVrLanInterface
538                    rebuildVrLan += "</tns2:vr-lan-interface>"
539                    rebuildVrLan += "</tns2:vr-lan>"
540                         
541                 }
542                 log("DEBUG", " rebuildVrLan - " + rebuildVrLan)
543                 return rebuildVrLan             
544         }
545         
546         // Build vr-lan-interface
547         def buildVrLanInterfacePartial(xmlInput) {
548                 def rebuildingVrLanInterface = ''
549                 if (xmlInput != null) {
550                         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"]
551                         rebuildingVrLanInterface += buildElements(xmlInput, vrLanInterfaceList, "")
552                         rebuildingVrLanInterface += "<tns2:v4-public-lan-prefixes>"
553                         try { // optional
554                                 def tProvidedV4LanPublicPrefixes = getNodeXml(xmlInput, "v4-public-lan-prefixes").drop(38).trim()
555                                 def tProvidedV4LanPublicPrefixesList = ["request-index", "v4-next-hop-address", "v4-lan-public-prefix", "v4-lan-public-prefix-length" ]
556                                 rebuildingVrLanInterface += buildElementsUnbounded(xmlInput, tProvidedV4LanPublicPrefixesList, "t-provided-v4-lan-public-prefixes")
557                         } catch (Exception ex) {
558                                 log("ERROR", " Optional - Exception VR-LAN INTERFACE 'v4-public-lan-prefixes' ")
559                         }
560                         rebuildingVrLanInterface += "</tns2:v4-public-lan-prefixes>"
561                         rebuildingVrLanInterface += "<tns2:v6-public-lan-prefixes>"
562                         try { // optional
563                                 def tProvidedV6LanPublicPrefixes = getNodeXml(xmlInput, "v6-public-lan-prefixes").drop(38).trim()
564                                 def tProvidedV6LanPublicPrefixesList = ["request-index", "v6-next-hop-address", "v6-lan-public-prefix", "v6-lan-public-prefix-length" ]
565                                 rebuildingVrLanInterface += buildElementsUnbounded(xmlInput, tProvidedV6LanPublicPrefixesList, "t-provided-v6-lan-public-prefixes")
566                         } catch (Exception e) {
567                                 log("ERROR", " Optional - Exception VR-LAN INTERFACE 'v6-public-lan-prefixes' ")
568                         }
569                         rebuildingVrLanInterface += "</tns2:v6-public-lan-prefixes>"
570                 }
571                 log("DEBUG", " rebuildingVrLanInterface - " + rebuildingVrLanInterface)
572                 return rebuildingVrLanInterface
573         }
574         
575         // Build dhcp
576         def buildDhcp(xmlInput) {
577                 def rebuildingDhcp = ''
578                 if (xmlInput != null) {
579                         def dhcpData = new XmlSlurper().parseText(xmlInput)
580                         rebuildingDhcp = "<tns2:dhcp>"
581                         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"]
582                         rebuildingDhcp += buildElements(xmlInput, dhcpList1, "")
583                         try { // optional
584                                 def excludedV4DhcpAddressesFromDefaultPoolList = ["excluded-v4-address"]
585                                 rebuildingDhcp += buildElementsUnbounded(xmlInput, excludedV4DhcpAddressesFromDefaultPoolList, "excluded-v4-dhcp-addresses-from-default-pool")
586                         } catch (Exception e) {
587                                 log("ERROR", " Optional - Exception DHCP 'excluded-v4-dhcp-addresses-from-default-pool' ")
588                         }
589                         try { // optional
590                                 def v4DhcpPools = dhcpData.'**'.findAll {it.name() == "v4-dhcp-pools"}
591                                 def v4DhcpPoolsSize = v4DhcpPools.size()
592                                 // println " v4DhcpPoolsSize = " + v4DhcpPools.size()
593                                 for (i in 0..v4DhcpPoolsSize-1) {
594                                         def v4DhcpPool = v4DhcpPools[i]
595                                         def v4DhcpPoolXml = XmlUtil.serialize(v4DhcpPool)
596                                         rebuildingDhcp += "<tns2:v4-dhcp-pools>"
597                                         def v4DhcpPoolsList1 = ["v4-dhcp-pool-prefix", "v4-dhcp-pool-prefix-length" ]
598                                         rebuildingDhcp += buildElements(v4DhcpPoolXml, v4DhcpPoolsList1, "")
599                                         try { // optional
600                                            def excludedV4AddressesList = ["excluded-v4-address"]
601                                            rebuildingDhcp += buildElementsUnbounded(v4DhcpPoolXml, excludedV4AddressesList, "excluded-v4-addresses")
602                                         } catch (Exception e) {
603                                            log("ERROR", " Optional - Exception DHCP 'excluded-v4-addresses' ")
604                                         }
605                                         def v4DhcpPoolsList2 = ["v4-dhcp-relay-gateway-address", "v4-dhcp-relay-next-hop-address"]
606                                         rebuildingDhcp += buildElements(v4DhcpPoolXml, v4DhcpPoolsList2, "")
607                                         rebuildingDhcp += "</tns2:v4-dhcp-pools>"
608                                  }
609                          } catch (Exception e) {
610                                   log("ERROR"," Optional - Exception DHCP 'v4-dhcp-pools' ")
611                          }
612                          def dhcpList2 = ["use-v6-default-pool", "v6-dhcp-default-pool-prefix", "v6-dhcp-default-pool-prefix-length"]
613                          rebuildingDhcp += buildElements(xmlInput, dhcpList2, "")
614                          try { // optional
615                                  def excludedV6DhcpAddressesFromDdefaultPoolList = ["excluded-v6-address"]
616                                  rebuildingDhcp += buildElementsUnbounded(xmlInput, excludedV6DhcpAddressesFromDdefaultPoolList, "excluded-v6-dhcp-addresses-from-default-pool")
617                          } catch (Exception e) {
618                            log("ERROR", " Optional - Exception DHCP 'excluded-v6-dhcp-addresses-from-default-pool' ")
619                          }
620                          try { // optional
621                                  def v6DhcpPools = dhcpData.'**'.findAll {it.name() == "v6-dhcp-pools"}
622                                  def v6DhcpPoolsSize = v6DhcpPools.size()
623                                  //println " v6DhcpPoolsSize = " + v6DhcpPools.size()
624                                  for (i in 0..v6DhcpPoolsSize-1) {
625                                         def v6DhcpPool = v6DhcpPools[i]
626                                         def v6DhcpPoolXml = XmlUtil.serialize(v6DhcpPool)
627                                         rebuildingDhcp += "<tns2:v6-dhcp-pools>"
628                                         def v6DhcpPoolsList1 = ["v6-dhcp-pool-prefix", "v6-dhcp-pool-prefix-length"]
629                                         rebuildingDhcp += buildElements(v6DhcpPoolXml, v6DhcpPoolsList1, "")
630                                         try { // optional
631                                                 def excludedV6AddressesList = ["excluded-v6-address"]
632                                                 rebuildingDhcp += buildElementsUnbounded(v6DhcpPoolXml, excludedV6AddressesList, "excluded-v6-addresses")
633                                         } catch (Exception e) {
634                                                          log("ERROR", " Optional - Exception DHCP 'excluded-v6-addresses' ")
635                                         }
636                                         def v6DhcpPoolsList2 = ["v6-dhcp-relay-gateway-address", "v6-dhcp-relay-next-hop-address"]
637                                         rebuildingDhcp += buildElements(v6DhcpPoolXml, v6DhcpPoolsList2, "")
638                                         rebuildingDhcp += "</tns2:v6-dhcp-pools>"
639                                  }
640                          } catch (Exception e) {
641                                  log("ERROR", " Optional - Exception DHCP 'v6-dhcp-pools' ")
642                          }
643                          rebuildingDhcp += "</tns2:dhcp>"
644                 }        
645                 log("DEBUG", " rebuildingDhcp - " + rebuildingDhcp)
646                 return rebuildingDhcp
647         }       
648
649         // Build pat
650         def buildPat(xmlInput) {
651                  def rebuildingPat = ''
652                  if (xmlInput != null) {
653                          rebuildingPat = "<tns2:pat>"
654                          def patList = ["v4-pat-enabled", "use-v4-default-pool", "v4-pat-default-pool-prefix", "v4-pat-default-pool-prefix-length"]
655                          rebuildingPat += buildElements(xmlInput, patList, "")
656                          try { // optional
657                                  def v4PatPools = getNodeXml(xmlInput, "v4-pat-pools").drop(38).trim()
658                                  def v4PatPoolsList = ["v4-pat-pool-prefix", "v4-pat-pool-prefix-length", "v4-pat-pool-next-hop-address"]
659                                  rebuildingPat += buildElementsUnbounded(xmlInput, v4PatPoolsList, "v4-pat-pools")
660                          } catch (Exception e) {
661                                 log("ERROR", " Optional - Exception 'v4-pat-pool-next-hop-address' ")
662                          }
663                          rebuildingPat += "</tns2:pat>"
664                  }
665                  log("DEBUG", " rebuildingPat - " + rebuildingPat)
666              return rebuildingPat
667     }
668         
669         // Build nat
670         def buildNat(xmlInput) {
671                 def rebuildingNat = ''
672                 if (xmlInput != null) {
673                         rebuildingNat = "<tns2:nat>"
674                         rebuildingNat += buildElements(xmlInput, ["v4-nat-enabled"], "")
675                         try { // optional
676                          def v4NatMappingEntries = getNodeXml(xmlInput, "v4-nat-mapping-entries").drop(38).trim()
677                          def v4NatMappingEntriesList = ["v4-nat-internal", "v4-nat-next-hop-address", "v4-nat-external"]
678                          rebuildingNat += buildElementsUnbounded(xmlInput, v4NatMappingEntriesList, "v4-nat-mapping-entries")
679                         } catch (Exception e) {
680                            log("ERROR", " Optional - Exception 'v4-nat-external' ")
681                         }
682                         rebuildingNat += "</tns2:nat>"
683                 }
684                 log("DEBUG", " rebuildingNat - " + rebuildingNat)
685             return rebuildingNat
686         }                               
687         
688         // Build firewall-lite
689         def buildFirewallLite(xmlInput) {
690                 def rebuildingFirewallLite = ''
691                 
692                 if (xmlInput != null) {
693                         
694                         def firewallLiteData = new XmlSlurper().parseText(xmlInput)
695                         rebuildingFirewallLite = "<tns2:firewall-lite>"
696                         def firewallLiteList = ["stateful-firewall-lite-v4-enabled", "stateful-firewall-lite-v6-enabled"]
697                         rebuildingFirewallLite += buildElements(xmlInput, firewallLiteList, "")
698                         
699                          try { // optional
700                                  def v4FirewallPacketFilters = firewallLiteData.'**'.findAll {it.name() == "v4-firewall-packet-filters"}
701                                  def v4FirewallPacketFiltersSize = v4FirewallPacketFilters.size()
702                                  //println " v4FirewallPacketFiltersSize = " + v4FirewallPacketFilters.size()
703                                  for (i in 0..v4FirewallPacketFiltersSize-1) {
704                                def v4FirewallPacketFilter = v4FirewallPacketFilters[i]
705                                def v4FirewallPacketFilterXml = XmlUtil.serialize(v4FirewallPacketFilter)
706                                    rebuildingFirewallLite += "<tns2:v4-firewall-packet-filters>"
707                                    def v4FirewallPacketFiltersList = ["v4-firewall-prefix", "v4-firewall-prefix-length", "allow-icmp-ping"]
708                                    rebuildingFirewallLite += buildElements(v4FirewallPacketFilterXml, v4FirewallPacketFiltersList, "")
709                                    try {  // optional
710                                   def udpPortsList = ["port-number"]
711                                           rebuildingFirewallLite += buildElementsUnbounded(v4FirewallPacketFilterXml, udpPortsList, "udp-ports")
712                                    } catch (Exception e) {
713                                           log("ERROR", " Optional - Exception FIREWALL-LITE v4 'udp-ports' ")
714                                    }
715                                    try {  // optional
716                                           def tcpPortsList =  ["port-number"]
717                                           rebuildingFirewallLite += buildElementsUnbounded(v4FirewallPacketFilterXml, tcpPortsList, "tcp-ports")
718                                    } catch (Exception e) {
719                                       log("ERROR", " Optional - Exception FIREWALL-LITE v4 'tcp-ports' ")
720                                    }
721                                    rebuildingFirewallLite += "</tns2:v4-firewall-packet-filters>"
722                                  }
723                          } catch (Exception e) {
724                                  log("ERROR", " Optional - Exception FIREWALL-LITE 'v4-firewall-packet-filters' ")
725                          }
726                          
727                          try { // optional
728                                  def v6FirewallPacketFilters = firewallLiteData.'**'.findAll {it.name() == "v6-firewall-packet-filters"}
729                                  def v6FirewallPacketFiltersSize = v6FirewallPacketFilters.size()
730                                  //println " v6FirewallPacketFiltersSize = " + v6FirewallPacketFilters.size()
731                                  for (i in 0..v6FirewallPacketFiltersSize-1) {
732                                         def v6FirewallPacketFilter = v6FirewallPacketFilters[i]
733                                         def v6FirewallPacketFilterXml = XmlUtil.serialize(v6FirewallPacketFilter)
734                                         rebuildingFirewallLite += "<tns2:v6-firewall-packet-filters>"
735                                         def v6FirewallPacketFiltersList = ["v6-firewall-prefix", "v6-firewall-prefix-length", "allow-icmp-ping"]
736                                         rebuildingFirewallLite += buildElements(v6FirewallPacketFilterXml, v6FirewallPacketFiltersList, "")
737                                         try { // optional
738                                                 def udpPortsList = ["port-number"]
739                                                 rebuildingFirewallLite += buildElementsUnbounded(v6FirewallPacketFilterXml, udpPortsList, "udp-ports")
740                                         } catch (Exception e) {
741                                       log("ERROR", " Optional - Exception FIREWALL-LITE v6 'udp-ports' ")
742                                         }
743                                         try { // optional
744                                                 def tcpPortsList =  ["port-number"]
745                                                 rebuildingFirewallLite += buildElementsUnbounded(v6FirewallPacketFilterXml, tcpPortsList, "tcp-ports")
746                                         } catch (Exception e) {
747                                         log("ERROR", " Optional - Exception FIREWALL-LITE v6 'tcp-ports' ")
748                                         }
749                                rebuildingFirewallLite += "</tns2:v6-firewall-packet-filters>"
750                                  }
751                          } catch (Exception e) {
752                                  log("ERROR", " Optional - Exception FIREWALL-LITE 'v6-firewall-packet-filters' ")
753                          }
754                          rebuildingFirewallLite+= "</tns2:firewall-lite>"
755                 }
756                 log("DEBUG", " rebuildingFirewallLite - " + rebuildingFirewallLite)
757                 return rebuildingFirewallLite
758      }
759         
760         def buildStaticRoutes(xmlInput) {
761                 def rebuildingStaticRoutes = ''
762                 if (xmlInput != null) {
763                         rebuildingStaticRoutes = "<tns2:static-routes>"
764                         def v4StaticRouteslist = ["v4-static-route-prefix","v4-static-route-prefix-length", "v4-next-hop-address"]
765                         rebuildingStaticRoutes += buildElementsUnbounded(xmlInput, v4StaticRouteslist, "v4-static-routes")
766                         def v6StaticRouteslist = ["v6-static-route-prefix","v6-static-route-prefix-length", "v6-next-hop-address"]
767                         rebuildingStaticRoutes += buildElementsUnbounded(xmlInput, v6StaticRouteslist, "v6-static-routes")
768                         rebuildingStaticRoutes += "</tns2:static-routes>"
769                 }
770                 log("DEBUG", " rebuildingStaticRoutes - " + rebuildingStaticRoutes)
771                 return rebuildingStaticRoutes
772         }
773         
774         public String generateCurrentTimeInUtc(){
775                 final  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
776                 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
777                 final String utcTime = sdf.format(new Date());
778                 return utcTime;
779         }
780         
781         public String generateCurrentTimeInGMT(){
782                 final  SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy h:m:s z");
783                 sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
784                 final String utcTime = sdf.format(new Date());
785                 return utcTime;
786         }
787         
788
789         /**
790          * @param encryptedAuth: encrypted credentials from urn properties
791          * @param msoKey: key to use to decrypt from urn properties
792          * @return base 64 encoded basic auth credentials
793          */
794         def getBasicAuth(encryptedAuth, msoKey){
795                 try {
796                         def auth = decrypt(encryptedAuth, msoKey)
797                         byte[] encoded = Base64.encodeBase64(auth.getBytes())
798                         String encodedString = new String(encoded)
799                         encodedString = "Basic " + encodedString
800                         return encodedString
801                 } catch (Exception ex) {
802                         log("ERROR", "Unable to encode basic auth")
803                         throw ex
804                 }
805         }
806         
807         def encrypt(toEncrypt, msokey){
808                 try {
809                         String result = CryptoUtils.encrypt(toEncrypt, msokey);
810                         return result
811                 }
812                 catch (Exception e) {
813                         log("ERROR", "Failed to encrypt credentials")
814                 }
815         }
816         
817         def decrypt(toDecrypt, msokey){
818                 try {
819                         String result = CryptoUtils.decrypt(toDecrypt, msokey);
820                         return result
821                 }
822                 catch (Exception e) {
823                         log("ERROR", "Failed to decrypt credentials")
824                         throw e
825                 }
826         }
827         
828         /**
829          * Return URL with qualified host name (if any) or urn mapping
830          * @param  String url from urn mapping
831          * @return String url with qualified host name
832          */
833         public String getQualifiedHostNameForCallback(String urnCallbackUrl) {
834                 def callbackUrlToUse = urnCallbackUrl
835                 try{
836                         //swap host name with qualified host name from the jboss properties
837                         def qualifiedHostName = System.getProperty("jboss.qualified.host.name")
838                         if(qualifiedHostName!=null){
839                                 log("DEBUG", "qualifiedHostName:\n" + qualifiedHostName)
840                                 callbackUrlToUse = callbackUrlToUse.replaceAll("(http://)(.*)(:8080*)", {orig, first, torepl, last -> "${first}${qualifiedHostName}${last}"})
841                         }
842                 }catch(Exception e){
843                                 log("DEBUG", "unable to grab qualified host name, using what's in urn properties for callbackurl. Exception was: " + e.printStackTrace())
844                 }
845                 return callbackUrlToUse
846                 
847         }
848         
849         /**
850          * Retrieves text context of the element if the element exists, returns empty string otherwise
851          * @param com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl element to parse
852          * param String tagName tagName
853          * @return String text content of the element
854          */
855          public String getElementText(Element element, String tagName) {
856                 String text = ""
857                 org.w3c.dom.NodeList nodeList = element.getElementsByTagNameNS("*", tagName)
858                 if (nodeList != null && nodeList.length > 0) {
859                         text = nodeList.item(0).getTextContent()
860                 }
861                 return text
862          }
863
864 }