Package rubacon :: Package parsers :: Module InformationParser
[hide private]
[frames] | no frames]

Source Code for Module rubacon.parsers.InformationParser

 1   
 2  from ..backend.XMLStorage import XMLStorage 
 3  import os,sys, marshal 
 4  import xml.sax 
 5   
 6  # Read information from the xml files. Information files must follow the meta-model given in the XMI file. 
 7   
 8  #  
 9  #  The information is parsed into a dictionary of lists 
10  #  the key value is the class name and the list entries 
11  #  are the instances of this information. One instance is 
12  #  represented as a dictionary containing the attributes. 
13  # 
14  # TODO make the methods static. 
15 -class InformationParser(object):
16 17 # @AttributeType string 18 # The default storage for information. 19 # TODO: parameterize in the config file for additional flexibility. 20 ___STORAGE = 'data/db.information' 21 22 # Clear the storage used for information files. This is needed, because several information files can be read for scalability.
23 - def clearStorage(self):
24 """Clear the storage for information""" 25 os.remove(self.___STORAGE)
26 27 # @ReturnType void 28 # @ParamType aFilename string 29 # Parse the file to the given repository.
30 - def parse(self, aFilename = "sample/sample_info.xml"):
31 """Parse the given info file and write it to the storage. 32 33 The structure of this file must match the model in the storage! 34 """ 35 inf = open('data/db.model') 36 a = marshal.load(inf) 37 inf.close() 38 # Just read the classnames into a list: 39 classList = [] 40 attrList = {} 41 for c in a['classDefs']: 42 classList.append(c['name']) 43 attrList[c['name']] = c['attrs'] 44 45 # Start parsing the file: 46 ih = information_handler(classList) 47 xml.sax.parse(aFilename, ih) 48 ouf = open(self.___STORAGE, 'wb') 49 marshal.dump(ih.resultHash, ouf) 50 ouf.close() 51 return ih.resultHash
52
53 -class information_handler(xml.sax.ContentHandler):
54 """Parse the information file to a list of objects"""
55 - def __init__(self, classList):
56 """Use the classnames and their attributes to 57 validate the structure.""" 58 self.classList = classList 59 self.resultHash = {}
60
61 - def startElement(self, name, attrs):
62 """start the parsing of an element""" 63 64 # This is the document element and it 65 # is not defined in the model of the application! 66 if name == 'information': 67 return 68 69 if not name in self.classList: 70 print >> sys.stderr, "Structure of information file invalid:" 71 print >> sys.stderr, "'%s' is not defined in the model." % name 72 return 73 74 # add the attrs to the info hash: 75 if not name in self.resultHash: 76 self.resultHash[name] = [] 77 entryList = self.resultHash[name] 78 entryHash = {} 79 for key,value in attrs.items(): 80 entryHash[key] = value 81 entryList.append(entryHash)
82