various fixes - passes tests in sfav1 mode
[sfa.git] / sfa / util / xml.py
1 #!/usr/bin/python 
2 from types import StringTypes
3 from lxml import etree
4 from StringIO import StringIO
5 from sfa.util.faults import InvalidXML
6
7 class XpathFilter:
8     @staticmethod
9
10     def filter_value(key, value):
11         xpath = ""    
12         if isinstance(value, str):
13             if '*' in value:
14                 value = value.replace('*', '')
15                 xpath = 'contains(%s, "%s")' % (key, value)
16             else:
17                 xpath = '%s="%s"' % (key, value)                
18         return xpath
19
20     @staticmethod
21     def xpath(filter={}):
22         xpath = ""
23         if filter:
24             filter_list = []
25             for (key, value) in filter.items():
26                 if key == 'text':
27                     key = 'text()'
28                 else:
29                     key = '@'+key
30                 if isinstance(value, str):
31                     filter_list.append(XpathFilter.filter_value(key, value))
32                 elif isinstance(value, list):
33                     stmt = ' or '.join([XpathFilter.filter_value(key, str(val)) for val in value])
34                     filter_list.append(stmt)   
35             if filter_list:
36                 xpath = ' and '.join(filter_list)
37                 xpath = '[' + xpath + ']'
38         return xpath
39
40 class XmlNode:
41     def __init__(self, node, namespaces):
42         self.node = node
43         self.text = node.text
44         self.namespaces = namespaces
45         self.attrib = node.attrib
46         
47
48     def xpath(self, xpath, namespaces=None):
49         if not namespaces:
50             namespaces = self.namespaces 
51         elems = self.node.xpath(xpath, namespaces=namespaces)
52         return [XmlNode(elem, namespaces) for elem in elems]
53     
54     def add_element(self, tagname, **kwds):
55         element = etree.SubElement(self.node, tagname, **kwds)
56         return XmlNode(element, self.namespaces)
57
58     def append(self, elem):
59         if isinstance(elem, XmlNode):
60             self.node.append(elem.node)
61         else:
62             self.node.append(elem)
63
64     def remove_elements(name):
65         """
66         Removes all occurences of an element from the tree. Start at
67         specified root_node if specified, otherwise start at tree's root.
68         """
69         
70         if not element_name.startswith('//'):
71             element_name = '//' + element_name
72         elements = self.node.xpath('%s ' % name, namespaces=self.namespaces) 
73         for element in elements:
74             parent = element.getparent()
75             parent.remove(element)
76
77     def remove(element):
78         self.node.remove(element)
79
80     def get(self, key, *args):
81         return self.node.get(key, *args)
82
83     def items(self): return self.node.items()
84
85     def set(self, key, value):
86         self.node.set(key, value)
87     
88     def set_text(self, text):
89         self.node.text = text
90     
91     def unset(self, key):
92         del self.node.attrib[key]
93   
94     def iterchildren(self):
95         return self.node.iterchildren()
96      
97     def toxml(self):
98         return etree.tostring(self.node, encoding='UTF-8', pretty_print=True)                    
99
100     def __str__(self):
101         return self.toxml()
102
103 class XML:
104  
105     def __init__(self, xml=None, namespaces=None):
106         self.root = None
107         self.namespaces = namespaces
108         self.default_namespace = None
109         self.schema = None
110         if isinstance(xml, basestring):
111             self.parse_xml(xml)
112         if isinstance(xml, XmlNode):
113             self.root = xml
114             self.namespaces = xml.namespaces
115         elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
116             self.parse_xml(etree.tostring(xml))
117
118     def parse_xml(self, xml):
119         """
120         parse rspec into etree
121         """
122         parser = etree.XMLParser(remove_blank_text=True)
123         try:
124             tree = etree.parse(xml, parser)
125         except IOError:
126             # 'rspec' file doesnt exist. 'rspec' is proably an xml string
127             try:
128                 tree = etree.parse(StringIO(xml), parser)
129             except Exception, e:
130                 raise InvalidXML(str(e))
131         root = tree.getroot()
132         self.namespaces = dict(root.nsmap)
133         # set namespaces map
134         if 'default' not in self.namespaces and None in self.namespaces: 
135             # If the 'None' exist, then it's pointing to the default namespace. This makes 
136             # it hard for us to write xpath queries for the default naemspace because lxml 
137             # wont understand a None prefix. We will just associate the default namespeace 
138             # with a key named 'default'.     
139             self.namespaces['default'] = self.namespaces.pop(None)
140             
141         else:
142             self.namespaces['default'] = 'default' 
143
144         self.root = XmlNode(root, self.namespaces)
145         # set schema 
146         for key in self.root.attrib.keys():
147             if key.endswith('schemaLocation'):
148                 # schema location should be at the end of the list
149                 schema_parts  = self.root.attrib[key].split(' ')
150                 self.schema = schema_parts[1]    
151                 namespace, schema  = schema_parts[0], schema_parts[1]
152                 break
153
154     def parse_dict(self, d, root_tag_name='xml', element = None):
155         if element is None: 
156             if self.root is None:
157                 self.parse_xml('<%s/>' % root_tag_name)
158             element = self.root
159
160         if 'text' in d:
161             text = d.pop('text')
162             element.text = text
163
164         # handle repeating fields
165         for (key, value) in d.items():
166             if isinstance(value, list):
167                 value = d.pop(key)
168                 for val in value:
169                     if isinstance(val, dict):
170                         child_element = etree.SubElement(element, key)
171                         self.parse_dict(val, key, child_element)
172                     elif isinstance(val, basestring):
173                         child_element = etree.SubElement(element, key).text = val
174                         
175             elif isinstance(value, int):
176                 d[key] = unicode(d[key])  
177             elif value is None:
178                 d.pop(key)
179
180         # element.attrib.update will explode if DateTimes are in the
181         # dcitionary.
182         d=d.copy()
183         # looks like iteritems won't stand side-effects
184         for k in d.keys():
185             if not isinstance(d[k],StringTypes):
186                 del d[k]
187
188         element.attrib.update(d)
189
190     def validate(self, schema):
191         """
192         Validate against rng schema
193         """
194         relaxng_doc = etree.parse(schema)
195         relaxng = etree.RelaxNG(relaxng_doc)
196         if not relaxng(self.root):
197             error = relaxng.error_log.last_error
198             message = "%s (line %s)" % (error.message, error.line)
199             raise InvalidXML(message)
200         return True
201
202     def xpath(self, xpath, namespaces=None):
203         if not namespaces:
204             namespaces = self.namespaces
205         return self.root.xpath(xpath, namespaces=namespaces)
206
207     def set(self, key, value, node=None):
208         if not node:
209             node = self.root 
210         return node.set(key, value)
211
212     def remove_attribute(self, name, node=None):
213         if not node:
214             node = self.root
215         node.remove_attribute(name) 
216         
217
218     def add_element(self, name, **kwds):
219         """
220         Wrapper around etree.SubElement(). Adds an element to 
221         specified parent node. Adds element to root node is parent is 
222         not specified. 
223         """
224         parent = self.root
225         xmlnode = parent.add_element(name, *kwds)
226         return xmlnode
227
228     def remove_elements(self, name, node = None):
229         """
230         Removes all occurences of an element from the tree. Start at 
231         specified root_node if specified, otherwise start at tree's root.   
232         """
233         if not node:
234             node = self.root
235
236         node.remove_elements(name)
237
238     def attributes_list(self, elem):
239         # convert a list of attribute tags into list of tuples
240         # (tagnme, text_value)
241         opts = []
242         if elem is not None:
243             for e in elem:
244                 opts.append((e.tag, str(e.text).strip()))
245         return opts
246
247     def get_element_attributes(self, elem=None, depth=0):
248         if elem == None:
249             elem = self.root_node
250         if not hasattr(elem, 'attrib'):
251             # this is probably not an element node with attribute. could be just and an
252             # attribute, return it
253             return elem
254         attrs = dict(elem.attrib)
255         attrs['text'] = str(elem.text).strip()
256         attrs['parent'] = elem.getparent()
257         if isinstance(depth, int) and depth > 0:
258             for child_elem in list(elem):
259                 key = str(child_elem.tag)
260                 if key not in attrs:
261                     attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
262                 else:
263                     attrs[key].append(self.get_element_attributes(child_elem, depth-1))
264         else:
265             attrs['child_nodes'] = list(elem)
266         return attrs
267
268     def merge(self, in_xml):
269         pass
270
271     def __str__(self):
272         return self.toxml()
273
274     def toxml(self):
275         return etree.tostring(self.root.node, encoding='UTF-8', pretty_print=True)  
276     
277     # XXX smbaker, for record.load_from_string
278     def todict(self, elem=None):
279         if elem is None:
280             elem = self.root
281         d = {}
282         d.update(elem.attrib)
283         d['text'] = elem.text
284         for child in elem.iterchildren():
285             if child.tag not in d:
286                 d[child.tag] = []
287             d[child.tag].append(self.todict(child))
288
289         if len(d)==1 and ("text" in d):
290             d = d["text"]
291
292         return d
293         
294     def save(self, filename):
295         f = open(filename, 'w')
296         f.write(self.toxml())
297         f.close()
298
299 # no RSpec in scope 
300 #if __name__ == '__main__':
301 #    rspec = RSpec('/tmp/resources.rspec')
302 #    print rspec
303