source: TI12-security/trunk/python/Tests/VocabServer/VocabServerAPIService_client.py @ 1546

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/Tests/VocabServer/VocabServerAPIService_client.py@4692
Revision 1546, 11.9 KB checked in by pjkersha, 14 years ago (diff)

Tests/VocabServer?:
Working version for whatListsCat method. ZSI code connects to Java WS with doc/lit wrapped WSDL. Note,
urllib2Client adaptor for ZSI client to work across a http proxy.

Tests/Echo?: corrected http_proxy -> http keyword in proxies dictionary of ProxyHandler?.

Line 
1##################################################
2# VocabServerAPIService_client.py
3# generated by ZSI.generate.wsdl2python
4##################################################
5
6
7
8import urlparse, types
9from ZSI.TCcompound import ComplexType, Struct
10from ZSI import client
11import ZSI
12
13from VocabServerAPIService_messages import *
14
15from ZSI import _copyright, _seqtypes, ParsedSoap, SoapWriter, TC, ZSI_SCHEMA_URI,\
16    EvaluateException, FaultFromFaultMessage, _child_elements, _attrs,\
17    _get_idstr, _get_postvalue_from_absoluteURI, FaultException, WSActionException
18from ZSI.auth import AUTH
19from ZSI.TC import AnyElement, AnyType, String, TypeCode, _get_global_element_declaration,\
20    _get_type_definition
21import base64, httplib, Cookie, time
22from ZSI.address import Address
23
24import urllib, urllib2
25
26
27class URLlib2Binding(client.Binding):
28    def Send(self, url, opname, obj, nsdict={}, soapaction=None, wsaction=None, 
29             endPointReference=None, **kw):
30        '''Send a message.  If url is None, use the value from the
31        constructor (else error). obj is the object (data) to send.
32        Data may be described with a requesttypecode keyword, or a
33        requestclass keyword; default is the class's typecode (if
34        there is one), else Any.
35
36        Optional WS-Address Keywords
37            wsaction -- WS-Address Action, goes in SOAP Header.
38            endPointReference --  set by calling party, must be an
39                EndPointReference type instance.
40
41        '''
42        url = url or self.url
43        # Get the TC for the obj.
44        if kw.has_key('requesttypecode'):
45            tc = kw['requesttypecode']
46        elif kw.has_key('requestclass'):
47            tc = kw['requestclass'].typecode
48        elif type(obj) == types.InstanceType:
49            tc = getattr(obj.__class__, 'typecode')
50            if tc is None: tc = TC.Any(opname, aslist=1)
51        else:
52            tc = TC.Any(opname, aslist=1)
53
54        endPointReference = endPointReference or self.endPointReference
55
56        # Serialize the object.
57        d = {}
58
59        d.update(self.nsdict)
60        d.update(nsdict)
61
62        useWSAddress = self.wsAddressURI is not None
63        sw = SoapWriter(nsdict=d, header=True, outputclass=self.writerclass, 
64                 encodingStyle=kw.get('encodingStyle'),)
65        if kw.has_key('_args'):
66            sw.serialize(kw['_args'], tc)
67        else:
68            sw.serialize(obj, tc)
69
70        # Determine the SOAP auth element.  SOAP:Header element
71        if self.auth_style & AUTH.zsibasic:
72            sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass),
73                _AuthHeader.typecode)
74
75        # Serialize WS-Address
76        if useWSAddress is True:
77            if self.soapaction and wsaction.strip('\'"') != self.soapaction:
78                raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match'\
79                    %(self.soapaction,wsaction)
80            self.address = Address(url, self.wsAddressURI)
81            self.address.setRequest(endPointReference, wsaction)
82            self.address.serialize(sw)
83
84        # WS-Security Signature Handler
85        if self.sig_handler is not None:
86            self.sig_handler.sign(sw)
87        soapdata = str(sw)
88
89        scheme,netloc,path,nil,nil,nil = urlparse.urlparse(url)
90
91        # self.transport httplib.HTTPConnection derived class set-up removed
92        # from HERE - this now handled by urllib2.urlopen()
93        self.SendSOAPData(soapdata, url, soapaction, **kw)
94
95    def SendSOAPData(self, soapdata, url, soapaction, headers={}, **kw):
96        # Tracing?
97        if self.trace:
98            print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
99            print >>self.trace, soapdata
100
101
102        #scheme,netloc,path,nil,nil,nil = urlparse.urlparse(url)
103        path = _get_postvalue_from_absoluteURI(url)
104 
105       
106        # Create a request   
107        req = urllib2.Request(url, data=soapdata)
108
109        req.add_header("Content-length", "%d" % len(soapdata))
110        req.add_header("Content-type", 'text/xml; charset=utf-8')
111       
112        # TODO: equivalent method for cookies using urllib2
113        #self.__addcookies()
114
115        for header,value in headers.items():
116            req.add_header(header, value)
117
118        SOAPActionValue = '"%s"' % (soapaction or self.soapaction)
119        req.add_header("SOAPAction", SOAPActionValue)
120       
121        # client.Binding has Authentication handler set-up code here -
122        # urllib2.HTTPBasicAuthHandler can do this instead?
123
124        for header,value in self.user_headers:
125            req.add_header(header, value)
126       
127        # Check for custom urllib2 handler class
128        if 'urlHandler' in kw:
129            if not isinstance(kw['urlHandler'], urllib2.BaseHandler):
130                raise TypeError, \
131            "URL Handler class %s must be derived from urllib2.BaseHandler" %\
132                                    kw['urlHandler']
133           
134            # Make an opener and make it the default so that urllib2.urlopen
135            # will use it
136            urlOpener = urllib2.build_opener(kw['urlHandler'])
137            urllib2.install_opener(urlOpener)
138           
139        # Send request [and receive response all in one (!) - implications
140        # for client.Binding architecture + functionality??]
141        self.response = urllib2.urlopen(req)
142         
143        # Clear prior receive state.
144        self.data, self.ps = None, None
145       
146       
147    def ReceiveRaw(self, **kw):
148        '''Read a server reply, unconverted to any format and return it.
149        '''
150        if self.data: return self.data
151        trace = self.trace
152       
153        if hasattr(self, 'response') and self.response is not None:
154            self.reply_code, self.reply_msg, self.reply_headers, self.data = \
155                self.response.code, self.response.msg, self.response.headers,\
156                self.response.read()
157           
158            # Reset response for next call
159            self.response = None
160            if trace:
161                print >>trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
162                for i in (self.reply_code, self.reply_msg,):
163                    print >>trace, str(i)
164                print >>trace, "-------"
165                print >>trace, str(self.reply_headers)
166                print >>trace, self.data
167
168            return self.data
169       
170        # else Send didn't use SendSOAPData...
171        while 1:
172            response = self.h.getresponse()
173            self.reply_code, self.reply_msg, self.reply_headers, self.data = \
174                response.status, response.reason, response.msg, response.read()
175            if trace:
176                print >>trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
177                for i in (self.reply_code, self.reply_msg,):
178                    print >>trace, str(i)
179                print >>trace, "-------"
180                print >>trace, str(self.reply_headers)
181                print >>trace, self.data
182            saved = None
183            for d in response.msg.getallmatchingheaders('set-cookie'):
184                if d[0] in [ ' ', '\t' ]:
185                    saved += d.strip()
186                else:
187                    if saved: self.cookies.load(saved)
188                    saved = d.strip()
189            if saved: self.cookies.load(saved)
190            if response.status == 401:
191                if not callable(self.http_callbacks.get(response.status,None)):
192                    raise RuntimeError, 'HTTP Digest Authorization Failed'
193                self.http_callbacks[response.status](response)
194                continue
195            if response.status != 100: break
196
197            # The httplib doesn't understand the HTTP continuation header.
198            # Horrible internals hack to patch things up.
199            self.h._HTTPConnection__state = httplib._CS_REQ_SENT
200            self.h._HTTPConnection__response = None
201        return self.data
202   
203   
204# Locator
205class VocabServerAPIServiceLocator:
206    VocabServerAPI_address = "http://grid.bodc.nerc.ac.uk/axis/services/VocabServerAPI"
207    def getVocabServerAPIAddress(self):
208        return VocabServerAPIServiceLocator.VocabServerAPI_address
209    def getVocabServerAPI(self, url=None, **kw):
210        return VocabServerAPISoapBindingSOAP(url or VocabServerAPIServiceLocator.VocabServerAPI_address, **kw)
211
212# Methods
213class VocabServerAPISoapBindingSOAP:
214    def __init__(self, url, **kw):
215        kw.setdefault("readerclass", None)
216        kw.setdefault("writerclass", None)
217        # no resource properties
218        #self.binding = client.Binding(url=url, **kw)
219        self.binding = URLlib2Binding(url=url, **kw)
220        # no ws-addressing
221
222    # op: <ZSI.wstools.WSDLTools.Message instance at 0xb6d6bbcc>
223    def whatLists(self, in0):
224
225        request = whatListsRequest()
226        request.in0 = in0
227
228        kw = {}
229        # no input wsaction
230        self.binding.Send(None, None, request, soapaction="", **kw)
231        # no output wsaction
232        response = self.binding.Receive(whatListsResponse.typecode)
233        whatListsReturn = response.whatListsReturn
234        return whatListsReturn
235
236    # op: <ZSI.wstools.WSDLTools.Message instance at 0xb6d7308c>
237    def getList(self, in0,in1,in2):
238
239        request = getListRequest()
240        request.in0 = in0
241        request.in1 = in1
242        request.in2 = in2
243
244        kw = {}
245        # no input wsaction
246        self.binding.Send(None, None, request, soapaction="", **kw)
247        # no output wsaction
248        response = self.binding.Receive(getListResponse.typecode)
249        getListReturn = response.getListReturn
250        return getListReturn
251
252    # op: <ZSI.wstools.WSDLTools.Message instance at 0xb6d658ac>
253    def verifyTerm(self, in0,in1,in2):
254
255        request = verifyTermRequest()
256        request.in0 = in0
257        request.in1 = in1
258        request.in2 = in2
259
260        kw = {}
261        # no input wsaction
262        self.binding.Send(None, None, request, soapaction="", **kw)
263        # no output wsaction
264        response = self.binding.Receive(verifyTermResponse.typecode)
265        verifyTermReturn = response.verifyTermReturn
266        return verifyTermReturn
267
268    # op: <ZSI.wstools.WSDLTools.Message instance at 0xb6d6be2c>
269    def pvMap(self, in0,in1,in2):
270
271        request = pvMapRequest()
272        request.in0 = in0
273        request.in1 = in1
274        request.in2 = in2
275
276        kw = {}
277        # no input wsaction
278        self.binding.Send(None, None, request, soapaction="", **kw)
279        # no output wsaction
280        response = self.binding.Receive(pvMapResponse.typecode)
281        pvMapReturn = response.pvMapReturn
282        return pvMapReturn
283
284    # op: <ZSI.wstools.WSDLTools.Message instance at 0xb6d6beec>
285    def getPhenomDict(self, in0):
286
287        request = getPhenomDictRequest()
288        request.in0 = in0
289
290        kw = {}
291        # no input wsaction
292        self.binding.Send(None, None, request, soapaction="", **kw)
293        # no output wsaction
294        response = self.binding.Receive(getPhenomDictResponse.typecode)
295        getPhenomDictReturn = response.getPhenomDictReturn
296        return getPhenomDictReturn
297
298    # op: <ZSI.wstools.WSDLTools.Message instance at 0xb6d7348c>
299    def whatListsCat(self):
300
301        request = whatListsCatRequest()
302
303        kw = {}
304        proxies = {'http': 'http://wwwcache2.rl.ac.uk:8080'}
305        kw = {'urlHandler': urllib2.ProxyHandler(proxies=proxies)}
306
307        # no input wsaction
308        self.binding.Send(None, None, request, soapaction="", **kw)
309        # no output wsaction
310        response = self.binding.Receive(whatListsCatResponse.typecode)
311        whatListsCatReturn = response.whatListsCatReturn
312        return whatListsCatReturn
313
314    # op: <ZSI.wstools.WSDLTools.Message instance at 0xb6d7320c>
315    def searchVocab(self, in0,in1,in2):
316
317        request = searchVocabRequest()
318        request.in0 = in0
319        request.in1 = in1
320        request.in2 = in2
321
322        kw = {}
323        # no input wsaction
324        self.binding.Send(None, None, request, soapaction="", **kw)
325        # no output wsaction
326        response = self.binding.Receive(searchVocabResponse.typecode)
327        searchVocabReturn = response.searchVocabReturn
328        return searchVocabReturn
Note: See TracBrowser for help on using the repository browser.