]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/python/oils/utils/csedit.py
updating to use new osrf api
[Evergreen.git] / Open-ILS / src / python / oils / utils / csedit.py
1 # -----------------------------------------------------------------------
2 # Copyright (C) 2007  Georgia Public Library Service
3 # Bill Erickson <billserickson@gmail.com>
4
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 # -----------------------------------------------------------------------
15
16 from osrf.log import *
17 from osrf.json import *
18 from oils.utils.idl import oilsGetIDLParser
19 from osrf.ses import ClientSession
20 from oils.const import *
21 import re
22
23 ACTIONS = ['create', 'retrieve', 'batch_retrieve', 'update', 'delete', 'search']
24
25 class CSEditor(object):
26     def __init__(self, **args):
27
28         self.app = args.get('app', OILS_APP_CSTORE)
29         self.authtoken = args.get('authtoken', args.get('auth'))
30         self.requestor = args.get('requestor')
31         self.connect = args.get('connect')
32         self.xact = args.get('xact')
33         self.__session = None
34
35     def die_event(self):
36         pass
37     def checkauth(self):
38         pass
39
40
41     # -------------------------------------------------------------------------
42     # Creates a session if one does not already exist.  If necessary, connects
43     # to the remote service and starts a transaction
44     # -------------------------------------------------------------------------
45     def session(self, ses=None):
46         if not self.__session:
47             self.__session = ClientSession(self.app)
48
49         if self.connect or self.xact:
50             self.log(log_debug,'connecting to ' + self.app)
51             self.__session.connect() 
52
53         if self.xact:
54             self.log(log_info, "starting new db transaction")
55             self.request(self.app + '.transaction.begin')
56
57         return self.__session
58    
59
60     # -------------------------------------------------------------------------
61     # Logs string with some meta info
62     # -------------------------------------------------------------------------
63     def log(self, func, string):
64         s = "editor[";
65         if self.xact: s += "1|"
66         else: s += "0|"
67         if self.requestor: s += str(self.requestor.id())
68         else: s += "0"
69         s += "]"
70         func("%s %s" % (s, string))
71
72
73     # -------------------------------------------------------------------------
74     # Rolls back the existing db transaction
75     # -------------------------------------------------------------------------
76     def rollback(self):
77         if self.__session and self.xact:
78              self.log(log_info, "rolling back db transaction")
79              self.request(self.app + '.transaction.rollback')
80              self.disconnect()
81              
82     # -------------------------------------------------------------------------
83     # Commits the existing db transaction
84     # -------------------------------------------------------------------------
85     def commit(self):
86         if self.__session and self.xact:
87             self.log(log_info, "comitting db transaction")
88             self.request(self.app + '.transaction.commit')
89             self.disconnect()
90
91
92     # -------------------------------------------------------------------------
93     # Disconnects from the remote service
94     # -------------------------------------------------------------------------
95     def disconnect(self):
96         if self.__session:
97             self.__session.disconnect()
98             self.__session = None
99
100
101     # -------------------------------------------------------------------------
102     # Sends a request
103     # -------------------------------------------------------------------------
104     def request(self, method, params=[]):
105
106         # XXX improve param logging here
107
108         self.log(log_info, "request %s %s" % (method, unicode(params)))
109
110         if self.xact and self.session().state != OSRF_APP_SESSION_CONNECTED:
111             self.log(log_error, "csedit lost its connection!")
112
113         val = None
114
115         try:
116             req = self.session().request2(method, params)
117             resp = req.recv()
118             val = resp.content()
119
120         except Exception, e:
121             self.log(log_error, "request error: %s" % unicode(e))
122             raise e
123
124         return val
125
126
127     # -------------------------------------------------------------------------
128     # Returns true if our requestor is allowed to perform the request action
129     # 'org' defaults to the requestors ws_ou
130     # -------------------------------------------------------------------------
131     def allowed(self, perm, org=None):
132         pass # XXX
133
134
135     def runMethod(self, action, type, arg, options={}):
136
137         method = "%s.direct.%s.%s" % (self.app, type, action)
138
139         if options.get('idlist'):
140             method = method.replace('search', 'id_list')
141             del options['idlist']
142
143         if action == 'search':
144             method = method.replace('$', '.atomic')
145
146         if action == 'batch_retrieve':
147             method = method.replace('batch_retrieve', 'search')
148             method += '.atomic'
149             arg = {'id' : arg}
150
151         params = [arg];
152         if len(options.keys()):
153             params.append(options)
154
155         val = self.request( method, params )
156
157         return val
158
159     def rawSearch(self, args):
160         method = "%s.json_query.atomic" % self.app
161         self.log(log_debug, "rawSearch args: %s" % unicode(args))
162         return self.request(method, [args])
163
164     def rawSearch2(self, hint, fields, where, from_=None):
165         if not from_:   
166             from_ = {'%s' % hint : {}}
167
168         args = {
169             'select' : { '%s' % hint : fields },
170             'from' : from_,
171             'where' : { "+%s" % hint : where }
172         }
173         return self.rawSearch(args)
174
175
176     def fieldSearch(self, hint, fields, where):
177         return self.rawSearch2(hint, fields, where)
178
179
180
181 # -------------------------------------------------------------------------
182 # Creates a class method for each action on each type of fieldmapper object
183 # -------------------------------------------------------------------------
184 def oilsLoadCSEditor():
185     obj = oilsGetIDLParser().IDLObject
186
187     for k, fm in obj.iteritems():
188         for action in ACTIONS:
189
190             fmname = fm['fieldmapper'].replace('::', '_')
191             type = fm['fieldmapper'].replace('::', '.')
192             name = "%s_%s" % (action, fmname)
193
194             s = 'def %s(self, arg, **options):\n' % name
195             s += '\treturn self.runMethod("%s", "%s", arg, dict(options))\n' % (action, type)
196             s += 'setattr(CSEditor, "%s", %s)' % (name, name)
197
198             exec(s)
199