Sigh, annoying little runt bug
[sfa.git] / sfa / util / rspec.py
1 ### $Id$
2 ### $URL$
3
4 import sys
5 import pprint
6 import os
7 import httplib
8 from xml.dom import minidom
9 from types import StringTypes, ListType
10
11 class Rspec:
12
13     def __init__(self, xml = None, xsd = None, NSURL = None):
14         '''
15         Class to manipulate RSpecs.  Reads and parses rspec xml into python dicts
16         and reads python dicts and writes rspec xml
17
18         self.xsd = # Schema.  Can be local or remote file.
19         self.NSURL = # If schema is remote, Name Space URL to query (full path minus filename)
20         self.rootNode = # root of the DOM
21         self.dict = # dict of the RSpec.
22         self.schemaDict = {} # dict of the Schema
23         '''
24  
25         self.xsd = xsd
26         self.rootNode = None
27         self.dict = {}
28         self.schemaDict = {}
29         self.NSURL = NSURL 
30         if xml: 
31             if type(xml) == file:
32                 self.parseFile(xml)
33             if type(xml) == str:
34                 self.parseString(xml)
35             self.dict = self.toDict() 
36         if xsd:
37             self._parseXSD(self.NSURL + self.xsd)
38
39
40     def _getText(self, nodelist):
41         rc = ""
42         for node in nodelist:
43             if node.nodeType == node.TEXT_NODE:
44                 rc = rc + node.data
45         return rc
46   
47     # The rspec is comprised of 2 parts, and 1 reference:
48     # attributes/elements describe individual resources
49     # complexTypes are used to describe a set of attributes/elements
50     # complexTypes can include a reference to other complexTypes.
51   
52   
53     def _getName(self, node):
54         '''Gets name of node. If tag has no name, then return tag's localName'''
55         name = None
56         if not node.nodeName.startswith("#"):
57             if node.localName:
58                 name = node.localName
59             elif node.attributes.has_key("name"):
60                 name = node.attributes.get("name").value
61         return name     
62  
63  
64     # Attribute.  {name : nameofattribute, {items: values})
65     def _attributeDict(self, attributeDom):
66         '''Traverse single attribute node.  Create a dict {attributename : {name: value,}]}'''
67         node = {} # parsed dict
68         for attr in attributeDom.attributes.keys():
69             node[attr] = attributeDom.attributes.get(attr).value
70         return node
71   
72  
73     def appendToDictOrCreate(self, dict, key, value):
74         if (dict.has_key(key)):
75             dict[key].append(value)
76         else:
77             dict[key]=[value]
78         return dict
79
80     def toGenDict(self, nodeDom=None, parentdict=None, siblingdict={}, parent=None):
81         """
82         convert an XML to a nested dict:
83           * Non-terminal nodes (elements with string children and attributes) are simple dictionaries
84           * Terminal nodes (the rest) are nested dictionaries
85         """
86
87         if (not nodeDom):
88             nodeDom=self.rootNode
89
90         curNodeName = nodeDom.localName
91
92         if (nodeDom.hasChildNodes()):
93             childdict={}
94             for child in nodeDom.childNodes[:-1]:
95                 if (child.nodeValue):
96                     siblingdict = self.appendToDictOrCreate(siblingdict, curNodeName, child.nodeValue)
97                 else:
98                     childdict = self.toGenDict(child, None, childdict, curNodeName)
99
100             child = nodeDom.childNodes[-1]
101             if (child.nodeValue):
102                 siblingdict = self.appendToDictOrCreate(siblingdict, curNodeName, child.nodeValue)
103             else:
104                 siblingdict = self.toGenDict(child, siblingdict, childdict, curNodeName)
105
106             for attribute in nodeDom.attributes.keys():
107                 siblingdict = self.appendToDictOrCreate(siblingdict, attribute, nodeDom.getAttribute(attribute))
108
109         if (parentdict is not None):
110             parentdict = self.appendToDictOrCreate(parentdict, parent, siblingdict)
111             return parentdict
112         else:
113             return siblingdict
114
115
116
117     def toDict(self, nodeDom = None):
118         """
119         convert this rspec to a dict and return it.
120         """
121         node = {}
122         if not nodeDom:
123              nodeDom = self.rootNode
124   
125         elementName = nodeDom.nodeName
126         if elementName and not elementName.startswith("#"):
127             # attributes have tags and values.  get {tag: value}, else {type: value}
128             node[elementName] = self._attributeDict(nodeDom)
129             # resolve the child nodes.
130             if nodeDom.hasChildNodes():
131                 for child in nodeDom.childNodes:
132                     childName = self._getName(child)
133                     # skip null children 
134                     if not childName:
135                         continue
136                     # initialize the possible array of children        
137                     if not node[elementName].has_key(childName):
138                         node[elementName][childName] = []
139                     # if child node has text child nodes
140                     # append the children to the array as strings
141                     if child.hasChildNodes() and isinstance(child.childNodes[0], minidom.Text):
142                         for nextchild in child.childNodes:
143                             node[elementName][childName].append(nextchild.data)
144                     # convert element child node to dict
145                     else:       
146                         childdict = self.toDict(child)
147                         for value in childdict.values():
148                             node[elementName][childName].append(value)
149                     #node[childName].append(self.toDict(child))
150         return node
151
152   
153     def toxml(self):
154         """
155         convert this rspec to an xml string and return it.
156         """
157         return self.rootNode.toxml()
158
159   
160     def toprettyxml(self):
161         """
162         print this rspec in xml in a pretty format.
163         """
164         return self.rootNode.toprettyxml()
165
166   
167     def parseFile(self, filename):
168         """
169         read a local xml file and store it as a dom object.
170         """
171         dom = minidom.parse(filename)
172         self.rootNode = dom.childNodes[0]
173
174
175     def parseString(self, xml):
176         """
177         read an xml string and store it as a dom object.
178         """
179         xml = xml.replace('\n', '').replace('\t', '').strip()
180         dom = minidom.parseString(xml)
181         self.rootNode = dom.childNodes[0]
182
183  
184     def _httpGetXSD(self, xsdURI):
185         # split the URI into relevant parts
186         host = xsdURI.split("/")[2]
187         if xsdURI.startswith("https"):
188             conn = httplib.HTTPSConnection(host,
189                 httplib.HTTPSConnection.default_port)
190         elif xsdURI.startswith("http"):
191             conn = httplib.HTTPConnection(host,
192                 httplib.HTTPConnection.default_port)
193         conn.request("GET", xsdURI)
194         # If we can't download the schema, raise an exception
195         r1 = conn.getresponse()
196         if r1.status != 200: 
197             raise Exception
198         return r1.read().replace('\n', '').replace('\t', '').strip() 
199
200
201     def _parseXSD(self, xsdURI):
202         """
203         Download XSD from URL, or if file, read local xsd file and set schemaDict
204         """
205         # Since the schema definiton is a global namespace shared by and agreed upon by
206         # others, this should probably be a URL.  Check for URL, download xsd, parse, or 
207         # if local file, use local file.
208         schemaDom = None
209         if xsdURI.startswith("http"):
210             try: 
211                 schemaDom = minidom.parseString(self._httpGetXSD(xsdURI))
212             except Exception, e:
213                 # logging.debug("%s: web file not found" % xsdURI)
214                 # logging.debug("Using local file %s" % self.xsd")
215                 print e
216                 print "Can't find %s on the web. Continuing." % xsdURI
217         if not schemaDom:
218             if os.path.exists(xsdURI):
219                 # logging.debug("using local copy.")
220                 print "Using local %s" % xsdURI
221                 schemaDom = minidom.parse(xsdURI)
222             else:
223                 raise Exception("Can't find xsd locally")
224         self.schemaDict = self.toDict(schemaDom.childNodes[0])
225
226
227     def dict2dom(self, rdict, include_doc = False):
228         """
229         convert a dict object into a dom object.
230         """
231      
232         def elementNode(tagname, rd):
233             element = minidom.Element(tagname)
234             for key in rd.keys():
235                 if isinstance(rd[key], StringTypes) or isinstance(rd[key], int):
236                     element.setAttribute(key, str(rd[key]))
237                 elif isinstance(rd[key], dict):
238                     child = elementNode(key, rd[key])
239                     element.appendChild(child)
240                 elif isinstance(rd[key], list):
241                     for item in rd[key]:
242                         if isinstance(item, dict):
243                             child = elementNode(key, item)
244                             element.appendChild(child)
245                         elif isinstance(item, StringTypes) or isinstance(item, int):
246                             child = minidom.Element(key)
247                             text = minidom.Text()
248                             text.data = item
249                             child.appendChild(text)
250                             element.appendChild(child) 
251             return element
252         
253         # Minidom does not allow documents to have more then one
254         # child, but elements may have many children. Because of
255         # this, the document's root node will be the first key/value
256         # pair in the dictionary.  
257         node = elementNode(rdict.keys()[0], rdict.values()[0])
258         if include_doc:
259             rootNode = minidom.Document()
260             rootNode.appendChild(node)
261         else:
262             rootNode = node
263         return rootNode
264
265  
266     def parseDict(self, rdict, include_doc = True):
267         """
268         Convert a dictionary into a dom object and store it.
269         """
270         self.rootNode = self.dict2dom(rdict, include_doc)
271  
272  
273     def getDictsByTagName(self, tagname, dom = None):
274         """
275         Search the dom for all elements with the specified tagname
276         and return them as a list of dicts
277         """
278         if not dom:
279             dom = self.rootNode
280         dicts = []
281         doms = dom.getElementsByTagName(tagname)
282         dictlist = [self.toDict(d) for d in doms]
283         for item in dictlist:
284             for value in item.values():
285                 dicts.append(value)
286         return dicts
287
288     def getDictByTagNameValue(self, tagname, value, dom = None):
289         """
290         Search the dom for the first element with the specified tagname
291         and value and return it as a dict.
292         """
293         tempdict = {}
294         if not dom:
295             dom = self.rootNode
296         dicts = self.getDictsByTagName(tagname, dom)
297         
298         for rdict in dicts:
299             if rdict.has_key('name') and rdict['name'] in [value]:
300                 return rdict
301               
302         return tempdict
303
304
305     def filter(self, tagname, attribute, blacklist = [], whitelist = [], dom = None):
306         """
307         Removes all elements where:
308         1. tagname matches the element tag
309         2. attribute matches the element attribte
310         3. attribute value is in valuelist  
311         """
312
313         tempdict = {}
314         if not dom:
315             dom = self.rootNode
316        
317         if dom.localName in [tagname] and dom.attributes.has_key(attribute):
318             if whitelist and dom.attributes.get(attribute).value not in whitelist:
319                 dom.parentNode.removeChild(dom)
320             if blacklist and dom.attributes.get(attribute).value in blacklist:
321                 dom.parentNode.removeChild(dom)
322            
323         if dom.hasChildNodes():
324             for child in dom.childNodes:
325                 self.filter(tagname, attribute, blacklist, whitelist, child) 
326
327
328     def validateDicts(self):
329         types = {
330             'EInt' : int,
331             'EString' : str,
332             'EByteArray' : list,
333             'EBoolean' : bool,
334             'EFloat' : float,
335             'EDate' : date}
336
337
338     def pprint(self, r = None, depth = 0):
339         """
340         Pretty print the dict
341         """
342         line = ""
343         if r == None: r = self.dict
344         # Set the dept
345         for tab in range(0,depth): line += "    "
346         # check if it's nested
347         if type(r) == dict:
348             for i in r.keys():
349                 print line + "%s:" % i
350                 self.pprint(r[i], depth + 1)
351         elif type(r) in (tuple, list):
352             for j in r: self.pprint(j, depth + 1)
353         # not nested so just print.
354         else:
355             print line + "%s" %  r
356     
357
358
359 class RecordSpec(Rspec):
360
361     root_tag = 'record'
362     def parseDict(self, rdict, include_doc = False):
363         """
364         Convert a dictionary into a dom object and store it.
365         """
366         self.rootNode = self.dict2dom(rdict, include_doc)
367
368     def dict2dom(self, rdict, include_doc = False):
369         record_dict = rdict
370         if not len(rdict.keys()) == 1:
371             record_dict = {self.root_tag : rdict}
372         return Rspec.dict2dom(self, record_dict, include_doc)
373
374         
375 # vim:ts=4:expandtab
376