replaced Element.get_elements() with XmlNode.get_instance(). replaced Element.add_ele...
[sfa.git] / sfa / util / xml.py
index e79fd47..d6fd196 100755 (executable)
@@ -1,13 +1,24 @@
 #!/usr/bin/python 
+from types import StringTypes
 from lxml import etree
 from StringIO import StringIO
-from datetime import datetime, timedelta
-from sfa.util.xrn import *
-from sfa.util.plxrn import hostname_to_urn
-from sfa.util.faults import SfaNotImplemented, InvalidXML
+from sfa.util.faults import InvalidXML
+from sfa.rspecs.elements.element import Element
 
 class XpathFilter:
     @staticmethod
+
+    def filter_value(key, value):
+        xpath = ""    
+        if isinstance(value, str):
+            if '*' in value:
+                value = value.replace('*', '')
+                xpath = 'contains(%s, "%s")' % (key, value)
+            else:
+                xpath = '%s="%s"' % (key, value)                
+        return xpath
+
+    @staticmethod
     def xpath(filter={}):
         xpath = ""
         if filter:
@@ -18,27 +29,130 @@ class XpathFilter:
                 else:
                     key = '@'+key
                 if isinstance(value, str):
-                    filter_list.append('%s="%s"' % (key, value))
+                    filter_list.append(XpathFilter.filter_value(key, value))
                 elif isinstance(value, list):
-                    filter_list.append('contains("%s", %s)' % (' '.join(map(str, value)), key))
+                    stmt = ' or '.join([XpathFilter.filter_value(key, str(val)) for val in value])
+                    filter_list.append(stmt)   
             if filter_list:
                 xpath = ' and '.join(filter_list)
                 xpath = '[' + xpath + ']'
         return xpath
 
+class XmlElement:
+    def __init__(self, element, namespaces):
+        self.element = element
+        self.text = element.text
+        self.namespaces = namespaces
+        self.attrib = element.attrib
+        
+
+    def xpath(self, xpath, namespaces=None):
+        if not namespaces:
+            namespaces = self.namespaces 
+        elems = self.element.xpath(xpath, namespaces=namespaces)
+        return [XmlElement(elem, namespaces) for elem in elems]
+    
+    def add_element(self, tagname, **kwds):
+        element = etree.SubElement(self.element, tagname, **kwds)
+        return XmlElement(element, self.namespaces)
+
+    def append(self, elem):
+        if isinstance(elem, XmlElement):
+            self.element.append(elem.element)
+        else:
+            self.element.append(elem)
+
+    def getparent(self):
+        return XmlElement(self.element.getparent(), self.namespaces)
+
+    def get_instance(self, instance_class=None, fields=[]):
+        """
+        Returns an instance (dict) of this xml element. The instance
+        holds a reference this xml element.   
+        """
+        if not instance_class:
+            instance_class = Element
+        if not fields and hasattr(instance_class, 'fields'):
+            fields = instance_class.fields
+
+        if not fields:
+            instance = instance_class(self.attrib, self)
+        else:
+            instance = instance_class({}, self)
+            for field in fields:
+                if field in self.attrib:
+                   instance[field] = self.attrib[field]  
+        return instance             
+
+    def add_instance(self, name, instance, fields=[]):
+        """
+        Adds the specifed instance(s) as a child element of this xml 
+        element. 
+        """
+        if not fields and hasattr(instance, 'keys'):
+            fields = instance.keys()
+        elem = self.add_element(name)
+        for field in fields:
+            if field in instance and instance[field]:
+                elem.set(field, unicode(instance[field]))
+        return elem                  
+
+    def remove_elements(self, name):
+        """
+        Removes all occurences of an element from the tree. Start at
+        specified root_node if specified, otherwise start at tree's root.
+        """
+        
+        if not element_name.startswith('//'):
+            element_name = '//' + element_name
+        elements = self.element.xpath('%s ' % name, namespaces=self.namespaces) 
+        for element in elements:
+            parent = element.getparent()
+            parent.remove(element)
+
+    def remove(self, element):
+        if isinstance(element, XmlElement):
+            self.element.remove(element.element)
+        else:
+            self.element.remove(element)
+
+    def get(self, key, *args):
+        return self.element.get(key, *args)
+
+    def items(self): return self.element.items()
+
+    def set(self, key, value):
+        self.element.set(key, value)
+    
+    def set_text(self, text):
+        self.element.text = text
+    
+    def unset(self, key):
+        del self.element.attrib[key]
+  
+    def iterchildren(self):
+        return self.element.iterchildren()
+     
+    def toxml(self):
+        return etree.tostring(self.element, encoding='UTF-8', pretty_print=True)                    
+
+    def __str__(self):
+        return self.toxml()
+
 class XML:
  
-    def __init__(self, xml=None):
+    def __init__(self, xml=None, namespaces=None):
         self.root = None
-        self.namespaces = None
+        self.namespaces = namespaces
         self.default_namespace = None
         self.schema = None
         if isinstance(xml, basestring):
             self.parse_xml(xml)
-        elif isinstance(xml, etree._ElementTree):
-            self.root = xml.getroot()
-        elif isinstance(xml, etree._Element):
-            self.root = xml 
+        if isinstance(xml, XmlElement):
+            self.root = xml
+            self.namespaces = xml.namespaces
+        elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
+            self.parse_xml(etree.tostring(xml))
 
     def parse_xml(self, xml):
         """
@@ -53,19 +167,20 @@ class XML:
                 tree = etree.parse(StringIO(xml), parser)
             except Exception, e:
                 raise InvalidXML(str(e))
-        self.root = tree.getroot()
+        root = tree.getroot()
+        self.namespaces = dict(root.nsmap)
         # set namespaces map
-        self.namespaces = dict(self.root.nsmap)
         if 'default' not in self.namespaces and None in self.namespaces: 
-            self.namespaces['default'] = self.namespaces[None]
-        # If the 'None' exist, then it's pointing to the default namespace. This makes 
-        # it hard for us to write xpath queries for the default naemspace because lxml 
-        # wont understand a None prefix. We will just associate the default namespeace 
-        # with a key named 'default'.     
-        if None in self.namespaces:
-            default_namespace = self.namespaces.pop(None)
-            self.namespaces['default'] = default_namespace
+            # If the 'None' exist, then it's pointing to the default namespace. This makes 
+            # it hard for us to write xpath queries for the default naemspace because lxml 
+            # wont understand a None prefix. We will just associate the default namespeace 
+            # with a key named 'default'.     
+            self.namespaces['default'] = self.namespaces.pop(None)
+            
+        else:
+            self.namespaces['default'] = 'default' 
 
+        self.root = XmlElement(root, self.namespaces)
         # set schema 
         for key in self.root.attrib.keys():
             if key.endswith('schemaLocation'):
@@ -77,7 +192,8 @@ class XML:
 
     def parse_dict(self, d, root_tag_name='xml', element = None):
         if element is None: 
-            self.parse_xml('<%s/>' % root_tag_name)
+            if self.root is None:
+                self.parse_xml('<%s/>' % root_tag_name)
             element = self.root
 
         if 'text' in d:
@@ -91,8 +207,23 @@ class XML:
                 for val in value:
                     if isinstance(val, dict):
                         child_element = etree.SubElement(element, key)
-                        self.parse_dict(val, key, child_element) 
-        
+                        self.parse_dict(val, key, child_element)
+                    elif isinstance(val, basestring):
+                        child_element = etree.SubElement(element, key).text = val
+                        
+            elif isinstance(value, int):
+                d[key] = unicode(d[key])  
+            elif value is None:
+                d.pop(key)
+
+        # element.attrib.update will explode if DateTimes are in the
+        # dcitionary.
+        d=d.copy()
+        # looks like iteritems won't stand side-effects
+        for k in d.keys():
+            if not isinstance(d[k],StringTypes):
+                del d[k]
+
         element.attrib.update(d)
 
     def validate(self, schema):
@@ -112,71 +243,43 @@ class XML:
             namespaces = self.namespaces
         return self.root.xpath(xpath, namespaces=namespaces)
 
-    def set(self, key, value):
-        return self.root.set(key, value)
-
-    def add_attribute(self, elem, name, value):
-        """
-        Add attribute to specified etree element    
-        """
-        opt = etree.SubElement(elem, name)
-        opt.text = value
+    def set(self, key, value, element=None):
+        if not element:
+            element = self.root 
+        return element.set(key, value)
 
-    def add_element(self, name, attrs={}, parent=None, text=""):
+    def remove_attribute(self, name, element=None):
+        if not element:
+            element = self.root
+        element.remove_attribute(name) 
+        
+    def add_element(self, *args, **kwds):
         """
-        Generic wrapper around etree.SubElement(). Adds an element to 
+        Wrapper around etree.SubElement(). Adds an element to 
         specified parent node. Adds element to root node is parent is 
         not specified. 
         """
-        if parent == None:
-            parent = self.root
-        element = etree.SubElement(parent, name)
-        if text:
-            element.text = text
-        if isinstance(attrs, dict):
-            for attr in attrs:
-                element.set(attr, attrs[attr])  
-        return element
+        return self.root.add_element(*args, **kwds)
 
-    def remove_attribute(self, elem, name, value):
-        """
-        Removes an attribute from an element
-        """
-        if elem is not None:
-            opts = elem.iterfind(name)
-            if opts is not None:
-                for opt in opts:
-                    if opt.text == value:
-                        elem.remove(opt)
-
-    def remove_element(self, element_name, root_node = None):
+    def remove_elements(self, name, element = None):
         """
         Removes all occurences of an element from the tree. Start at 
         specified root_node if specified, otherwise start at tree's root.   
         """
-        if not root_node:
-            root_node = self.root
+        if not element:
+            element = self.root
 
-        if not element_name.startswith('//'):
-            element_name = '//' + element_name
+        element.remove_elements(name)
 
-        elements = root_node.xpath('%s ' % element_name, namespaces=self.namespaces)
-        for element in elements:
-            parent = element.getparent()
-            parent.remove(element)
+    def add_instance(self, *args, **kwds):
+        return self.root.add_instance(*args, **kwds)
 
-    def attributes_list(self, elem):
-        # convert a list of attribute tags into list of tuples
-        # (tagnme, text_value)
-        opts = []
-        if elem is not None:
-            for e in elem:
-                opts.append((e.tag, str(e.text).strip()))
-        return opts
+    def get_instance(self, *args, **kwds):
+        return self.root.get_instnace(*args, **kwds)
 
     def get_element_attributes(self, elem=None, depth=0):
         if elem == None:
-            elem = self.root_node
+            elem = self.root
         if not hasattr(elem, 'attrib'):
             # this is probably not an element node with attribute. could be just and an
             # attribute, return it
@@ -195,6 +298,12 @@ class XML:
             attrs['child_nodes'] = list(elem)
         return attrs
 
+    def append(self, elem):
+        return self.root.append(elem)
+
+    def iterchildren(self):
+        return self.root.iterchildren()    
+
     def merge(self, in_xml):
         pass
 
@@ -202,8 +311,9 @@ class XML:
         return self.toxml()
 
     def toxml(self):
-        return etree.tostring(self.root, encoding='UTF-8', pretty_print=True)  
+        return etree.tostring(self.root.element, encoding='UTF-8', pretty_print=True)  
     
+    # XXX smbaker, for record.load_from_string
     def todict(self, elem=None):
         if elem is None:
             elem = self.root
@@ -214,14 +324,19 @@ class XML:
             if child.tag not in d:
                 d[child.tag] = []
             d[child.tag].append(self.todict(child))
-        return d            
+
+        if len(d)==1 and ("text" in d):
+            d = d["text"]
+
+        return d
         
     def save(self, filename):
         f = open(filename, 'w')
         f.write(self.toxml())
         f.close()
-if __name__ == '__main__':
-    rspec = RSpec('/tmp/resources.rspec')
-    print rspec
+
+# no RSpec in scope 
+#if __name__ == '__main__':
+#    rspec = RSpec('/tmp/resources.rspec')
+#    print rspec