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