source: TI05-delivery/ows_framework/trunk/ows_server/ows_server/models/Utilities.py @ 3605

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI05-delivery/ows_framework/trunk/ows_server/ows_server/models/Utilities.py@3605
Revision 3605, 7.1 KB checked in by cbyrom, 11 years ago (diff)

Add utility function to check if a tab is actually required - i.e. if
it is not already displayed.

Line 
1from collections import deque # python 2.4
2try: #python 2.5
3    from xml.etree import ElementTree as ET
4except ImportError:
5    try:
6        # if you've installed it yourself it comes this way
7        import ElementTree as ET
8    except ImportError:
9        # if you've egged it this is the way it comes
10        from elementtree import ElementTree as ET
11from ndgUtils.ETxmlView import *
12
13import ConfigParser, os, re, urllib, logging
14
15class myConfig:
16   
17   ''' Handle missing sections and variables in a config file a bit gracefully. Also
18   instantiates a logger if necessary '''
19   
20   def __init__(self,configfile,logName='NDGLOG'):
21       self.config=ConfigParser.ConfigParser()
22       if not os.path.exists(configfile): 
23           raise ValueError("Config file [%s] doesn't exist in [%s]"%(configfile,os.getcwd()))
24       self.config.read(configfile)
25       logfile=self.get('logging','debugLog',None)
26       # move to a wsgi logger ... safer I think in a multithread environment
27       #
28       #self.logfile=None #deprecated
29       self.logger=None
30       self.logfile=logfile
31       #
32       if logfile is not None:
33           #logger=logging.getLogger(logName)
34           #handler=logging.FileHandler(logfile)
35           #formatter=logging.Formatter('%(asctime)s %(levelname)s %(message)s')
36           #handler.setFormatter(formatter)
37           #logger.addHandler(handler)
38           #logger.setLevel(logging.INFO)
39           #self.logger=logger
40           self.logger=None
41       
42   def get(self,section,key,default=None):
43       ''' Return a config file value for key frm section '''
44       try:
45           return self.config.get(section,key)
46       except:
47           return default
48       
49   def log(self,string):
50       ''' Log some debug information '''
51       if self.logger is None: return
52       if string is not None:
53          self.logger.info(string)
54       else:
55          self.logger.info('empty log entry')
56         
57   def getLog(self):
58       return self.logger
59
60class RingBuffer(deque):
61    #deque is a python 2.4 class!
62    #credit http://www.onlamp.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html
63    def __init__(self, size_max):
64        deque.__init__(self)
65        self.size_max = size_max
66    def append(self, datum):
67        deque.append(self, datum)
68        if len(self) > self.size_max:
69            self.popleft( )
70    def tolist(self):
71        return list(self)
72    def remove(self,value):
73        try: # python 2.5
74            deque.remove(self,value)
75        except: # python 2.4
76            #yuck, two copies ...
77            x=self.tolist()
78            x.remove(value)
79            self.clear()
80            for i in x:self.append(i)
81           
82
83def wrapGetText(element,xpathExpression,multiple=0):
84        ''' Wraps a call to ET to get a text object in an error handler '''
85        def none2txt(i):
86            if i is None: return ''
87            return i
88        if element is None:
89            if multiple:
90                 return ['',]
91            else: return ''
92        if multiple:
93                r=element.findall(xpathExpression)
94        else:
95                r=[element.find(xpathExpression),]
96        try:
97                rr=[i.text for i in r]
98        except:
99                rr=['',]
100        rr=map(none2txt,rr) 
101        if multiple: 
102                return rr
103        else: return rr[0] 
104
105def getURLdict(cgiFieldStorage):
106    ''' takes a cgi field storage object and converts it to a dictionary '''
107    result={}
108    for item in cgiFieldStorage:
109            result[item]=cgiFieldStorage[item].value
110    return result
111##
112### convert the followign two methods into one class that can handle
113## xml directly too if necessary
114##
115def DIFid2NDGid(string):
116    ''' takes a dif thing parses it and produces an ET ndg element id ...
117    and use this in dif ... '''
118    s=string.split(':')
119    try:
120        r='''<DIFid><schemeIdentifier>%s</schemeIdentifier>
121         <repositoryIdentifier>%s</repositoryIdentifier>
122         <localIdentifier>%s</localIdentifier></DIFid>'''%(s[1],s[0],s[2])
123        return ET.fromstring(r)
124    except:
125        r='''<DIFid><schemeIdentifier>DIF</schemeIdentifier>
126        <repositoryIdentifier>Unknown</repositoryIdentifier>
127        <localIdentifier>%s</localIdentifier></DIFid>'''%string
128        return ET.fromstring(r)
129
130def EnumerateString(string):
131    ''' Takes a string, and if it's got a number on the end, increments it,
132    otherwise adds a number on the end, used to differentiate strings which
133    would otherwise be identical '''
134    def addNum(matchObj):
135        s=matchObj.group()
136        return str(int(s)+1)
137    r=re.sub('\d+$',addNum,string)
138    if r==string: r=r+'1'
139    return r
140
141def dateParse(string,instruction):
142    ''' Simple date manipulations on a string, if it is understood ...
143       if instruction = YYYY, return the year '''
144    s=string.split('-')
145    if instruction=='YYYY':
146        if len(s)==3: # expecting year,mon,day or day,mon,year ...
147            if int(s[0])>int(s[2]): 
148                return s[0]
149            else:
150                return s[2]
151        else:
152            return string # unknown format as yet ...
153    else:
154        return 'unknown instruction to dateParse %s'%instruction
155
156def idget(xml,dataType='DIF'):
157    ''' Given an xml document (string), parse it using ElementTree and
158    find the identifier within it. Supports dataTypes of 'DIF' ...
159    (actually only DIF for now).
160    '''
161    et=loadET(xml)
162    helper=nsdumb(et)
163    if dataType=='DIF':
164        return helper.getText(et,'Entry_ID')
165    else:
166        raise TypeError,'idget does not support datatype [%s]'%dataType
167   
168
169def recreateListFromUnicode(string):
170    ''' Parse a list that has been passed as unicode over http and
171    recreate it in its list form
172    '''
173    if not string:
174        return
175   
176    newList = []
177    element = []
178    for c in string:
179        if c == '[' or c == ' ' or c == ']' or c == '\'':
180            continue
181        elif c == ',':
182            if (len(element) > 0):
183                newList.append(''.join(element))
184                element = []
185            continue
186        element.append(c)
187
188    # don't forget the last element
189    if (len(element) > 0):
190        newList.append(''.join(element))
191       
192    return newList
193
194def isTabRequired(pageTabs, string):
195    for tab in pageTabs:
196        if tab[0] == string:
197            return False
198   
199    return True
200       
201
202       
203import unittest
204
205class TestCase(unittest.TestCase):
206    """ Tests as required """
207
208    configFile='examples/example.config'
209    difFile='examples/neodc.eg1.dif'
210   
211    def setUp(self):
212        # If pkg_resources is available assume the module is eggified and
213        # get a stream to the input data from the egg.
214        #try:
215        #    import pkg_resources
216        #    f = pkg_resources.resource_stream(__name__, self.configFile)
217        #except ImportError:
218            # Else take the input file from __file__
219            #import os
220        self.config=myConfig(self.configFile)
221        f=file(self.difFile,'r')
222        self.difxml=f.read()
223            #f=file(os.path.join(os.path.basepath(__file__), self.configFile))
224
225        #self.config=myConfig(f)
226
227    def testConfig(self):
228        print 'Discovery Icon [%s]'%self.config.get('DISCOVERY','icon')
229       
230    def testidget(self):
231        self.assertEqual(idget(self.difxml),'NOCSDAT192')
232
233
234if __name__=="__main__":
235    unittest.main()
236
237
238
Note: See TracBrowser for help on using the repository browser.