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                 # schemaLocation should be at the end of the list.
202                 # Use list comprehension to filter out empty strings 
203                 schema_parts  = [x for x in self.root.attrib[key].split(' ') if x]
204                 self.schema = schema_parts[1]    
205                 namespace, schema  = schema_parts[0], schema_parts[1]
206                 break
207
208     def parse_dict(self, d, root_tag_name='xml', element = None):
209         if element is None: 
210             if self.root is None:
211                 self.parse_xml('<%s/>' % root_tag_name)
212             element = self.root.element
213
214         if 'text' in d:
215             text = d.pop('text')
216             element.text = text
217
218         # handle repeating fields
219         for (key, value) in d.items():
220             if isinstance(value, list):
221                 value = d.pop(key)
222                 for val in value:
223                     if isinstance(val, dict):
224                         child_element = etree.SubElement(element, key)
225                         self.parse_dict(val, key, child_element)
226                     elif isinstance(val, basestring):
227                         child_element = etree.SubElement(element, key).text = val
228
229             elif isinstance(value, int):
230                 d[key] = unicode(d[key])
231             elif value is None:
232                 d.pop(key)
233
234         # element.attrib.update will explode if DateTimes are in the
235         # dcitionary.
236         d=d.copy()
237         # looks like iteritems won't stand side-effects
238         for k in d.keys():
239             if not isinstance(d[k],StringTypes):
240                 del d[k]
241
242         element.attrib.update(d)
243
244     def validate(self, schema):
245         """
246         Validate against rng schema
247         """
248         relaxng_doc = etree.parse(schema)
249         relaxng = etree.RelaxNG(relaxng_doc)
250         if not relaxng(self.root):
251             error = relaxng.error_log.last_error
252             message = "%s (line %s)" % (error.message, error.line)
253             raise InvalidXML(message)
254         return True
255
256     def xpath(self, xpath, namespaces=None):
257         if not namespaces:
258             namespaces = self.namespaces
259         return self.root.xpath(xpath, namespaces=namespaces)
260
261     def set(self, key, value):
262         return self.root.set(key, value)
263
264     def remove_attribute(self, name, element=None):
265         if not element:
266             element = self.root
267         element.remove_attribute(name) 
268         
269     def add_element(self, *args, **kwds):
270         """
271         Wrapper around etree.SubElement(). Adds an element to 
272         specified parent node. Adds element to root node is parent is 
273         not specified. 
274         """
275         return self.root.add_element(*args, **kwds)
276
277     def remove_elements(self, name, element = None):
278         """
279         Removes all occurences of an element from the tree. Start at 
280         specified root_node if specified, otherwise start at tree's root.   
281         """
282         if not element:
283             element = self.root
284
285         element.remove_elements(name)
286
287     def add_instance(self, *args, **kwds):
288         return self.root.add_instance(*args, **kwds)
289
290     def get_instance(self, *args, **kwds):
291         return self.root.get_instnace(*args, **kwds)
292
293     def get_element_attributes(self, elem=None, depth=0):
294         if elem == None:
295             elem = self.root
296         if not hasattr(elem, 'attrib'):
297             # this is probably not an element node with attribute. could be just and an
298             # attribute, return it
299             return elem
300         attrs = dict(elem.attrib)
301         attrs['text'] = str(elem.text).strip()
302         attrs['parent'] = elem.getparent()
303         if isinstance(depth, int) and depth > 0:
304             for child_elem in list(elem):
305                 key = str(child_elem.tag)
306                 if key not in attrs:
307                     attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
308                 else:
309                     attrs[key].append(self.get_element_attributes(child_elem, depth-1))
310         else:
311             attrs['child_nodes'] = list(elem)
312         return attrs
313
314     def append(self, elem):
315         return self.root.append(elem)
316
317     def iterchildren(self):
318         return self.root.iterchildren()    
319
320     def merge(self, in_xml):
321         pass
322
323     def __str__(self):
324         return self.toxml()
325
326     def toxml(self):
327         return etree.tostring(self.root.element, encoding='UTF-8', pretty_print=True)  
328     
329     # XXX smbaker, for record.load_from_string
330     def todict(self, elem=None):
331         if elem is None:
332             elem = self.root
333         d = {}
334         d.update(elem.attrib)
335         d['text'] = elem.text
336         for child in elem.iterchildren():
337             if child.tag not in d:
338                 d[child.tag] = []
339             d[child.tag].append(self.todict(child))
340
341         if len(d)==1 and ("text" in d):
342             d = d["text"]
343
344         return d
345         
346     def save(self, filename):
347         f = open(filename, 'w')
348         f.write(self.toxml())
349         f.close()
350
351 # no RSpec in scope 
352 #if __name__ == '__main__':
353 #    rspec = RSpec('/tmp/resources.rspec')
354 #    print rspec
355