source: TI07-MOLES/trunk/PythonCode/wsgi/eXistInterface.py @ 2364

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI07-MOLES/trunk/PythonCode/wsgi/eXistInterface.py@2448
Revision 2364, 6.6 KB checked in by lawrence, 13 years ago (diff)

Sundry modifications to get browse working again and to use a
config file to identify the appropriate repositories (for
a given ndg uri, what repository holds the browse info? this
is by way of a temporary expedient).

Line 
1# Code inspired by example on eXist website.
2import urllib2, base64, urllib, urlparse, httplib, xmlrpclib, types
3
4class   InstanceObject(object):
5    def __init__(self, **kw):
6        self.dict={}
7        self.dict.update(kw)
8    def __getattr__(self,arg):
9        return self.dict[arg]
10
11class  eXist_Connector(object):
12    """Access class for eXist"""
13    def __init__(self,constants=None):
14        ''' Instantiates the eXist connector using supplied constants '''
15        if constants is None: raise 'NoExistConstants'
16        authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
17        authinfo.add_password(None,
18                                  constants.host,
19                                  constants.userid,
20                                  constants.password)
21        authHandler = urllib2.HTTPBasicAuthHandler(authinfo)
22        opener = urllib2.build_opener(authHandler)
23        s = constants.userid+':'+constants.password
24        z = base64.encodestring(s)[:-1] # strip trailing 12
25        opener.addheaders.append(('Authorization', 'Basic %s' % z))
26        self.http_headers = {'Authorization':'Basic %s' % z}
27        self.opener = opener
28        # also create an xmlrpc Server object
29       
30        xmlrpc_uri = '%s%s:%s@%s:%d%s' % ( 
31                                            'http://',
32                                            constants.userid,
33                                            constants.password,
34                                            constants.host,
35                                            constants.port,
36                                            constants.xmlrpc_base_path
37                                        )
38        self.xmlrpc = xmlrpclib.Server(xmlrpc_uri)
39
40    def executeQuery(self, xquery, params={}):
41        '''Execute an xquery string, return session and summary information'''
42        xquery=xmlrpclib.Binary(xquery)
43        id = self.xmlrpc.executeQuery(xquery, params)
44        summary = self.xmlrpc.querySummary(id)
45        return id,summary
46
47    def release(self,id):
48        ''' Release an executeQuery session '''
49        self.xmlrpc.releaseQueryResult(id)
50       
51    def retrieve(self,id,pos,params={}):
52        ''' Retrieve a specific document from an executeQuery result set '''
53        return self.xmlrpc.retrieve(id,pos,params).data
54 
55    def executeChunkedQuery(self,xquery,start,number,params={}):
56        ''' Execute a query, return a specific part of the result set, and
57        dump the session automagically '''
58        xquery=xmlrpclib.Binary(xquery)
59        r=self.xmlrpc.query(xquery,number,start,params)
60        return r
61   
62    def querySummary(self,id):
63        ''' Returns a summary of query results for the result-set referenced by id (which was returned by a previous query '''
64        return self.xmlrpc.querySummary(id)
65   
66    def getHits(self,id):
67        ''' Return the number of hits associated with the query that created session id '''
68        return self.xmlrpc.getHits(id)
69   
70    def getDoc(self,collectionName,documentName):
71        ''' Lightweight interface to the getDocument method '''
72        name='%s/%s'%(collectionName,documentName)
73        r=self.xmlrpc.getDocumentAsString(name,{})
74        return r
75   
76# unfortunately it looks like the exist server doesn't support introspection
77#    def showMethods(self):
78#        print self.xmlrpc.system.listMethods()
79       
80class ndg_eXist(eXist_Connector):
81    ''' Adds ndg methods to a "standard" exist Connector '''
82    def __init__(self,db='glue.badc.rl.ac.uk',passwordFile='passwords.txt'):
83        f=file(passwordFile,'r')
84        pw={}
85        for line in f.readlines():
86            host,userid,password=line.strip().split(' ')
87            pw[host]=(userid,password)
88        if db not in pw:
89            raise ValueError('Unable to find eXist password for repository [%s]'%db)
90        eXistConstants = InstanceObject(host=db,
91                                userid=pw[db][0],
92                                password=pw[db][1],
93                                base_path="/exist/servlet",
94                                xmlrpc_base_path="/exist/xmlrpc",
95                                port=8080)
96       
97        eXist_Connector.__init__(self,eXistConstants)
98        self.ids={}
99       
100    def __buildquery(self,query,target=None):
101        '''Create an NDG full text query '''
102        if target is not None:
103            s="//%s[. &='%s']"%(target,query)
104        else: s="/*[. &='%s']"%query
105        return s#xmlrpclib.Binary(s)
106
107    def __buildParamSearch(self,param,value,target):
108        s="for $x in document()//%s where $x[.%s &= '%s'] return $x"%(target,param,value)
109        return s
110
111    def full_text(self,query,target=None):
112        ''' Carry out a full text search within the "target" collection '''
113        id,summary=self.executeQuery(self.__buildquery(query,target))
114        self.ids[id]=0
115        return id,summary
116
117    def retrieveNext(self,id,pos=None):
118        ''' Takes a sessionID from an existing query and gets the next document '''
119        if pos is not None: self.ids[id]=pos
120        try:
121            r=self.retrieve(id, self.ids[id])
122            self.ids[id]+=1
123            return r
124        except xmlrpclib.Fault:
125            return None
126        except KeyError:
127            return None
128   
129    def sessionRelease(self,id):
130        ''' Releases a session and removes the position counter '''
131        try:
132            self.release(id)
133            del self.ids[id]
134            return 1
135        except:
136            return 0
137   
138    def chunkedFullText(self,query,start=1,number=10,target='DIF'):
139        ''' Execute a chunked full text query and return the result
140        set '''
141        return self.executeChunkedQuery(self.__buildquery(query,target),start,number,params={})
142   
143   
144    def getDIF(self,entryID):
145        ''' Get a specific DIF document from a repository by using the entryID '''
146        xq='''for $DE in collection()/DIF[Entry_ID='%s'] return $DE'''%entryID
147        xquery='''for $DE in collection('/db/testdif1')/DIF[Entry_ID='%s'] return $DE'''%entryID
148        id,summary=self.executeQuery(xq)#xquery)
149        if summary['hits']==1:
150            r=self.retrieve(id,0,{})
151            self.sessionRelease(id)
152        else:
153            r=summary['hits']
154        return r
155       
156   
157import unittest
158
159class TestCase(unittest.TestCase):
160   
161    def testFullText(self):
162           
163        ''' Exercises some of the methods based on something we hope might exist in the database '''
164       
165        existDB=ndg_eXist(db='glue.badc.rl.ac.uk')
166        id,summary=existDB.full_text('neodc')
167       
168        r=existDB.retrieveNext(id)
169        d=summary['documents'][0][0]
170        print d
171        doc=existDB.getDoc('/db/discovery/moles',d)
172       
173        ok=existDB.sessionRelease(id)
174        self.assertEqual(1,ok)
175
176if __name__=="__main__":
177    unittest.main()
178 
Note: See TracBrowser for help on using the repository browser.