python3 - 2to3 + miscell obvious tweaks
[sfa.git] / sfa / util / xml.py
1 #!/usr/bin/env python3
2 from lxml import etree
3 from sfa.util.faults import InvalidXML
4 from sfa.rspecs.elements.element import Element
5
6 from sfa.util.py23 import StringType
7 from sfa.util.py23 import StringIO
8
9 # helper functions to help build xpaths
10
11
12 class XpathFilter:
13
14     @staticmethod
15     def filter_value(key, value):
16         xpath = ""
17         if isinstance(value, str):
18             if '*' in value:
19                 value = value.replace('*', '')
20                 xpath = 'contains(%s, "%s")' % (key, value)
21             else:
22                 xpath = '%s="%s"' % (key, value)
23         return xpath
24
25     @staticmethod
26     def xpath(filter=None):
27         if filter is None:
28             filter = {}
29         xpath = ""
30         if filter:
31             filter_list = []
32             for (key, value) in list(filter.items()):
33                 if key == 'text':
34                     key = 'text()'
35                 else:
36                     key = '@' + key
37                 if isinstance(value, str):
38                     filter_list.append(XpathFilter.filter_value(key, value))
39                 elif isinstance(value, list):
40                     stmt = ' or '.join(
41                         [XpathFilter.filter_value(key, str(val)) for val in value])
42                     filter_list.append(stmt)
43             if filter_list:
44                 xpath = ' and '.join(filter_list)
45                 xpath = '[' + xpath + ']'
46         return xpath
47
48 # a wrapper class around lxml.etree._Element
49 # the reason why we need this one is because of the limitations
50 # we've found in xpath to address documents with multiple namespaces defined
51 # in a nutshell, we deal with xml documents that have
52 # a default namespace defined (xmlns="http://default.com/") and specific prefixes defined
53 # (xmlns:foo="http://foo.com")
54 # according to the documentation instead of writing
55 # element.xpath ( "//node/foo:subnode" )
56 # we'd then need to write xpaths like
57 # element.xpath ( "//{http://default.com/}node/{http://foo.com}subnode" )
58 # which is a real pain..
59 # So just so we can keep some reasonable programming style we need to manage the
60 # namespace map that goes with the _Element (its internal .nsmap being
61 # unmutable)
62
63
64 class XmlElement:
65
66     def __init__(self, element, namespaces):
67         self.element = element
68         self.namespaces = namespaces
69
70     # redefine as few methods as possible
71     def xpath(self, xpath, namespaces=None):
72         if not namespaces:
73             namespaces = self.namespaces
74         elems = self.element.xpath(xpath, namespaces=namespaces)
75         return [XmlElement(elem, namespaces) for elem in elems]
76
77     def add_element(self, tagname, **kwds):
78         element = etree.SubElement(self.element, tagname, **kwds)
79         return XmlElement(element, self.namespaces)
80
81     def append(self, elem):
82         if isinstance(elem, XmlElement):
83             self.element.append(elem.element)
84         else:
85             self.element.append(elem)
86
87     def getparent(self):
88         return XmlElement(self.element.getparent(), self.namespaces)
89
90     def get_instance(self, instance_class=None, fields=None):
91         """
92         Returns an instance (dict) of this xml element. The instance
93         holds a reference to this xml element.   
94         """
95         if fields is None:
96             fields = []
97         if not instance_class:
98             instance_class = Element
99         if not fields and hasattr(instance_class, 'fields'):
100             fields = instance_class.fields
101
102         if not fields:
103             instance = instance_class(self.attrib, self)
104         else:
105             instance = instance_class({}, self)
106             for field in fields:
107                 if field in self.attrib:
108                     instance[field] = self.attrib[field]
109         return instance
110
111     def add_instance(self, name, instance, fields=None):
112         """
113         Adds the specifed instance(s) as a child element of this xml 
114         element. 
115         """
116         if fields is None:
117             fields = []
118         if not fields and hasattr(instance, 'keys'):
119             fields = list(instance.keys())
120         elem = self.add_element(name)
121         for field in fields:
122             if field in instance and instance[field]:
123                 elem.set(field, str(instance[field]))
124         return elem
125
126     def remove_elements(self, name):
127         """
128         Removes all occurences of an element from the tree. Start at
129         specified root_node if specified, otherwise start at tree's root.
130         """
131
132         if not element_name.startswith('//'):
133             element_name = '//' + element_name
134         elements = self.element.xpath('%s ' % name, namespaces=self.namespaces)
135         for element in elements:
136             parent = element.getparent()
137             parent.remove(element)
138
139     def delete(self):
140         parent = self.getparent()
141         parent.remove(self)
142
143     def remove(self, element):
144         if isinstance(element, XmlElement):
145             self.element.remove(element.element)
146         else:
147             self.element.remove(element)
148
149     def set_text(self, text):
150         self.element.text = text
151
152     # Element does not have unset ?!?
153     def unset(self, key):
154         del self.element.attrib[key]
155
156     def toxml(self):
157         return etree.tostring(self.element, encoding='UTF-8', pretty_print=True)
158
159     def __str__(self):
160         return self.toxml()
161
162     # other method calls or attribute access like .text or .tag or .get
163     # are redirected on self.element
164     def __getattr__(self, name):
165         if not hasattr(self.element, name):
166             raise AttributeError(name)
167         return getattr(self.element, name)
168
169
170 class XML:
171
172     def __init__(self, xml=None, namespaces=None):
173         self.root = None
174         self.namespaces = namespaces
175         self.default_namespace = None
176         self.schema = None
177         if isinstance(xml, StringType):
178             self.parse_xml(xml)
179         if isinstance(xml, XmlElement):
180             self.root = xml
181             self.namespaces = xml.namespaces
182         elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
183             self.parse_xml(etree.tostring(xml))
184
185     def parse_xml(self, xml):
186         """
187         parse rspec into etree
188         """
189         parser = etree.XMLParser(remove_blank_text=True)
190         try:
191             tree = etree.parse(xml, parser)
192         except IOError:
193             # 'rspec' file doesnt exist. 'rspec' is proably an xml string
194             try:
195                 tree = etree.parse(StringIO(xml), parser)
196             except Exception as e:
197                 raise InvalidXML(str(e))
198         root = tree.getroot()
199         self.namespaces = dict(root.nsmap)
200         # set namespaces map
201         if 'default' not in self.namespaces and None in self.namespaces:
202             # If the 'None' exist, then it's pointing to the default namespace. This makes
203             # it hard for us to write xpath queries for the default naemspace because lxml
204             # wont understand a None prefix. We will just associate the default namespeace
205             # with a key named 'default'.
206             self.namespaces['default'] = self.namespaces.pop(None)
207
208         else:
209             self.namespaces['default'] = 'default'
210
211         self.root = XmlElement(root, self.namespaces)
212         # set schema
213         for key in list(self.root.attrib.keys()):
214             if key.endswith('schemaLocation'):
215                 # schemaLocation should be at the end of the list.
216                 # Use list comprehension to filter out empty strings
217                 schema_parts = [
218                     x for x in self.root.attrib[key].split(' ') if x]
219                 self.schema = schema_parts[1]
220                 namespace, schema = schema_parts[0], schema_parts[1]
221                 break
222
223     def parse_dict(self, d, root_tag_name='xml', element=None):
224         if element is None:
225             if self.root is None:
226                 self.parse_xml('<%s/>' % root_tag_name)
227             element = self.root.element
228
229         if 'text' in d:
230             text = d.pop('text')
231             element.text = text
232
233         # handle repeating fields
234         for (key, value) in list(d.items()):
235             if isinstance(value, list):
236                 value = d.pop(key)
237                 for val in value:
238                     if isinstance(val, dict):
239                         child_element = etree.SubElement(element, key)
240                         self.parse_dict(val, key, child_element)
241                     elif isinstance(val, StringType):
242                         child_element = etree.SubElement(
243                             element, key).text = val
244
245             elif isinstance(value, int):
246                 d[key] = str(d[key])
247             elif value is None:
248                 d.pop(key)
249
250         # element.attrib.update will explode if DateTimes are in the
251         # dcitionary.
252         d = d.copy()
253         # looks like iteritems won't stand side-effects
254         for k in list(d.keys()):
255             if not isinstance(d[k], StringType):
256                 del d[k]
257
258         element.attrib.update(d)
259
260     def validate(self, schema):
261         """
262         Validate against rng schema
263         """
264         relaxng_doc = etree.parse(schema)
265         relaxng = etree.RelaxNG(relaxng_doc)
266         if not relaxng(self.root):
267             error = relaxng.error_log.last_error
268             message = "%s (line %s)" % (error.message, error.line)
269             raise InvalidXML(message)
270         return True
271
272     def xpath(self, xpath, namespaces=None):
273         if not namespaces:
274             namespaces = self.namespaces
275         return self.root.xpath(xpath, namespaces=namespaces)
276
277     def set(self, key, value):
278         return self.root.set(key, value)
279
280     def remove_attribute(self, name, element=None):
281         if not element:
282             element = self.root
283         element.remove_attribute(name)
284
285     def add_element(self, *args, **kwds):
286         """
287         Wrapper around etree.SubElement(). Adds an element to 
288         specified parent node. Adds element to root node is parent is 
289         not specified. 
290         """
291         return self.root.add_element(*args, **kwds)
292
293     def remove_elements(self, name, element=None):
294         """
295         Removes all occurences of an element from the tree. Start at 
296         specified root_node if specified, otherwise start at tree's root.   
297         """
298         if not element:
299             element = self.root
300
301         element.remove_elements(name)
302
303     def add_instance(self, *args, **kwds):
304         return self.root.add_instance(*args, **kwds)
305
306     def get_instance(self, *args, **kwds):
307         return self.root.get_instnace(*args, **kwds)
308
309     def get_element_attributes(self, elem=None, depth=0):
310         if elem == None:
311             elem = self.root
312         if not hasattr(elem, 'attrib'):
313             # this is probably not an element node with attribute. could be just and an
314             # attribute, return it
315             return elem
316         attrs = dict(elem.attrib)
317         attrs['text'] = str(elem.text).strip()
318         attrs['parent'] = elem.getparent()
319         if isinstance(depth, int) and depth > 0:
320             for child_elem in list(elem):
321                 key = str(child_elem.tag)
322                 if key not in attrs:
323                     attrs[key] = [self.get_element_attributes(
324                         child_elem, depth - 1)]
325                 else:
326                     attrs[key].append(
327                         self.get_element_attributes(child_elem, depth - 1))
328         else:
329             attrs['child_nodes'] = list(elem)
330         return attrs
331
332     def append(self, elem):
333         return self.root.append(elem)
334
335     def iterchildren(self):
336         return self.root.iterchildren()
337
338     def merge(self, in_xml):
339         pass
340
341     def __str__(self):
342         return self.toxml()
343
344     def toxml(self):
345         return etree.tostring(self.root.element, encoding='UTF-8', pretty_print=True)
346
347     # XXX smbaker, for record.load_from_string
348     def todict(self, elem=None):
349         if elem is None:
350             elem = self.root
351         d = {}
352         d.update(elem.attrib)
353         d['text'] = elem.text
354         for child in elem.iterchildren():
355             if child.tag not in d:
356                 d[child.tag] = []
357             d[child.tag].append(self.todict(child))
358
359         if len(d) == 1 and ("text" in d):
360             d = d["text"]
361
362         return d
363
364     def save(self, filename):
365         f = open(filename, 'w')
366         f.write(self.toxml())
367         f.close()
368
369 # no RSpec in scope
370 # if __name__ == '__main__':
371 #    rspec = RSpec('/tmp/resources.rspec')
372 #    print rspec