Bad. Need to get rid of the tab as well.
[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={}, 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.nodeValue):
93             siblingdict = self.appendToDictOrCreate(siblingdict, parent, nodeDom.nodeValue)
94         elif (nodeDom.hasChildNodes()):
95             for child in nodeDom.childNodes:
96                  siblingdict = self.toGenDict(child, None, siblingdict,curNodeName)
97
98             for attribute in nodeDom.attributes.keys():
99                 parentdict = self.appendToDictOrCreate(parentdict, curNodeName, nodeDom.getAttribute(attribute))
100
101         if (parentdict is not None):
102             parentdict = self.appendToDictOrCreate(parentdict, curNodeName, siblingdict)
103             return parentdict
104         else:
105             return siblingdict
106
107
108
109     def toDict(self, nodeDom = None):
110         """
111         convert this rspec to a dict and return it.
112         """
113         node = {}
114         if not nodeDom:
115              nodeDom = self.rootNode
116   
117         elementName = nodeDom.nodeName
118         if elementName and not elementName.startswith("#"):
119             # attributes have tags and values.  get {tag: value}, else {type: value}
120             node[elementName] = self._attributeDict(nodeDom)
121             # resolve the child nodes.
122             if nodeDom.hasChildNodes():
123                 for child in nodeDom.childNodes:
124                     childName = self._getName(child)
125                     # skip null children 
126                     if not childName:
127                         continue
128                     # initialize the possible array of children        
129                     if not node[elementName].has_key(childName):
130                         node[elementName][childName] = []
131                     # if child node has text child nodes
132                     # append the children to the array as strings
133                     if child.hasChildNodes() and isinstance(child.childNodes[0], minidom.Text):
134                         for nextchild in child.childNodes:
135                             node[elementName][childName].append(nextchild.data)
136                     # convert element child node to dict
137                     else:       
138                         childdict = self.toDict(child)
139                         for value in childdict.values():
140                             node[elementName][childName].append(value)
141                     #node[childName].append(self.toDict(child))
142         return node
143
144   
145     def toxml(self):
146         """
147         convert this rspec to an xml string and return it.
148         """
149         return self.rootNode.toxml()
150
151   
152     def toprettyxml(self):
153         """
154         print this rspec in xml in a pretty format.
155         """
156         return self.rootNode.toprettyxml()
157
158   
159     def parseFile(self, filename):
160         """
161         read a local xml file and store it as a dom object.
162         """
163         dom = minidom.parse(filename)
164         self.rootNode = dom.childNodes[0]
165
166
167     def parseString(self, xml):
168         """
169         read an xml string and store it as a dom object.
170         """
171         xml = xml.replace('\n', '').replace('\t', '').strip()
172         dom = minidom.parseString(xml)
173         self.rootNode = dom.childNodes[0]
174
175  
176     def _httpGetXSD(self, xsdURI):
177         # split the URI into relevant parts
178         host = xsdURI.split("/")[2]
179         if xsdURI.startswith("https"):
180             conn = httplib.HTTPSConnection(host,
181                 httplib.HTTPSConnection.default_port)
182         elif xsdURI.startswith("http"):
183             conn = httplib.HTTPConnection(host,
184                 httplib.HTTPConnection.default_port)
185         conn.request("GET", xsdURI)
186         # If we can't download the schema, raise an exception
187         r1 = conn.getresponse()
188         if r1.status != 200: 
189             raise Exception
190         return r1.read().replace('\n', '').replace('\t', '').strip() 
191
192
193     def _parseXSD(self, xsdURI):
194         """
195         Download XSD from URL, or if file, read local xsd file and set schemaDict
196         """
197         # Since the schema definiton is a global namespace shared by and agreed upon by
198         # others, this should probably be a URL.  Check for URL, download xsd, parse, or 
199         # if local file, use local file.
200         schemaDom = None
201         if xsdURI.startswith("http"):
202             try: 
203                 schemaDom = minidom.parseString(self._httpGetXSD(xsdURI))
204             except Exception, e:
205                 # logging.debug("%s: web file not found" % xsdURI)
206                 # logging.debug("Using local file %s" % self.xsd")
207                 print e
208                 print "Can't find %s on the web. Continuing." % xsdURI
209         if not schemaDom:
210             if os.path.exists(xsdURI):
211                 # logging.debug("using local copy.")
212                 print "Using local %s" % xsdURI
213                 schemaDom = minidom.parse(xsdURI)
214             else:
215                 raise Exception("Can't find xsd locally")
216         self.schemaDict = self.toDict(schemaDom.childNodes[0])
217
218
219     def dict2dom(self, rdict, include_doc = False):
220         """
221         convert a dict object into a dom object.
222         """
223      
224         def elementNode(tagname, rd):
225             element = minidom.Element(tagname)
226             for key in rd.keys():
227                 if isinstance(rd[key], StringTypes) or isinstance(rd[key], int):
228                     element.setAttribute(key, str(rd[key]))
229                 elif isinstance(rd[key], dict):
230                     child = elementNode(key, rd[key])
231                     element.appendChild(child)
232                 elif isinstance(rd[key], list):
233                     for item in rd[key]:
234                         if isinstance(item, dict):
235                             child = elementNode(key, item)
236                             element.appendChild(child)
237                         elif isinstance(item, StringTypes) or isinstance(item, int):
238                             child = minidom.Element(key)
239                             text = minidom.Text()
240                             text.data = item
241                             child.appendChild(text)
242                             element.appendChild(child) 
243             return element
244         
245         # Minidom does not allow documents to have more then one
246         # child, but elements may have many children. Because of
247         # this, the document's root node will be the first key/value
248         # pair in the dictionary.  
249         node = elementNode(rdict.keys()[0], rdict.values()[0])
250         if include_doc:
251             rootNode = minidom.Document()
252             rootNode.appendChild(node)
253         else:
254             rootNode = node
255         return rootNode
256
257  
258     def parseDict(self, rdict, include_doc = True):
259         """
260         Convert a dictionary into a dom object and store it.
261         """
262         self.rootNode = self.dict2dom(rdict, include_doc)
263  
264  
265     def getDictsByTagName(self, tagname, dom = None):
266         """
267         Search the dom for all elements with the specified tagname
268         and return them as a list of dicts
269         """
270         if not dom:
271             dom = self.rootNode
272         dicts = []
273         doms = dom.getElementsByTagName(tagname)
274         dictlist = [self.toDict(d) for d in doms]
275         for item in dictlist:
276             for value in item.values():
277                 dicts.append(value)
278         return dicts
279
280     def getDictByTagNameValue(self, tagname, value, dom = None):
281         """
282         Search the dom for the first element with the specified tagname
283         and value and return it as a dict.
284         """
285         tempdict = {}
286         if not dom:
287             dom = self.rootNode
288         dicts = self.getDictsByTagName(tagname, dom)
289         
290         for rdict in dicts:
291             if rdict.has_key('name') and rdict['name'] in [value]:
292                 return rdict
293               
294         return tempdict
295
296
297     def filter(self, tagname, attribute, blacklist = [], whitelist = [], dom = None):
298         """
299         Removes all elements where:
300         1. tagname matches the element tag
301         2. attribute matches the element attribte
302         3. attribute value is in valuelist  
303         """
304
305         tempdict = {}
306         if not dom:
307             dom = self.rootNode
308        
309         if dom.localName in [tagname] and dom.attributes.has_key(attribute):
310             if whitelist and dom.attributes.get(attribute).value not in whitelist:
311                 dom.parentNode.removeChild(dom)
312             if blacklist and dom.attributes.get(attribute).value in blacklist:
313                 dom.parentNode.removeChild(dom)
314            
315         if dom.hasChildNodes():
316             for child in dom.childNodes:
317                 self.filter(tagname, attribute, blacklist, whitelist, child) 
318
319
320     def validateDicts(self):
321         types = {
322             'EInt' : int,
323             'EString' : str,
324             'EByteArray' : list,
325             'EBoolean' : bool,
326             'EFloat' : float,
327             'EDate' : date}
328
329
330     def pprint(self, r = None, depth = 0):
331         """
332         Pretty print the dict
333         """
334         line = ""
335         if r == None: r = self.dict
336         # Set the dept
337         for tab in range(0,depth): line += "    "
338         # check if it's nested
339         if type(r) == dict:
340             for i in r.keys():
341                 print line + "%s:" % i
342                 self.pprint(r[i], depth + 1)
343         elif type(r) in (tuple, list):
344             for j in r: self.pprint(j, depth + 1)
345         # not nested so just print.
346         else:
347             print line + "%s" %  r
348     
349
350
351 class RecordSpec(Rspec):
352
353     root_tag = 'record'
354     def parseDict(self, rdict, include_doc = False):
355         """
356         Convert a dictionary into a dom object and store it.
357         """
358         self.rootNode = self.dict2dom(rdict, include_doc)
359
360     def dict2dom(self, rdict, include_doc = False):
361         record_dict = rdict
362         if not len(rdict.keys()) == 1:
363             record_dict = {self.root_tag : rdict}
364         return Rspec.dict2dom(self, record_dict, include_doc)
365
366         
367 # vim:ts=4:expandtab
368