/usr/share/pyshared/ZSI/twisted/client.py is in python-zsi 2.1~a1-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | ############################################################################
# Joshua R. Boverhof, LBNL
# See LBNLCopyright for copyright notice!
###########################################################################
import time
# twisted & related imports
from zope.interface import classProvides, implements, Interface
from twisted.web import client
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import log
from twisted.python.failure import Failure
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI.fault import FaultFromFaultMessage
from ZSI.wstools.Namespaces import WSA
from WSresource import HandlerChainInterface, CheckInputArgs
#
# Stability: Unstable
#
class HTTPPageGetter(client.HTTPPageGetter):
def handleStatus_500(self):
"""potentially a SOAP:Fault.
"""
log.err('HTTP Error 500')
def handleStatus_404(self):
"""client error, not found
"""
log.err('HTTP Error 404')
client.HTTPClientFactory.protocol = HTTPPageGetter
def getPage(url, contextFactory=None, *args, **kwargs):
"""Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See HTTPClientFactory to see what extra args can be passed.
"""
scheme, host, port, path = client._parse(url)
factory = client.HTTPClientFactory(url, *args, **kwargs)
if scheme == 'https':
if contextFactory is None:
raise RuntimeError, 'must provide a contextFactory'
conn = reactor.connectSSL(host, port, factory, contextFactory)
else:
conn = reactor.connectTCP(host, port, factory)
return factory
class ClientDataHandler:
"""
class variables:
readerClass -- factory class to create reader for ParsedSoap instances.
writerClass -- ElementProxy implementation to use for SoapWriter
instances.
"""
classProvides(HandlerChainInterface)
readerClass = None
writerClass = None
@classmethod
def processResponse(cls, soapdata, **kw):
"""called by deferred, returns pyobj representing reply.
Parameters and Key Words:
soapdata -- SOAP Data
replytype -- reply type of response
"""
if len(soapdata) == 0:
raise TypeError('Received empty response')
# log.msg("_" * 33, time.ctime(time.time()),
# "RESPONSE: \n%s" %soapdata, debug=True)
ps = ParsedSoap(soapdata, readerclass=cls.readerClass)
if ps.IsAFault() is True:
log.msg('Received SOAP:Fault', debug=True)
raise FaultFromFaultMessage(ps)
return ps
@classmethod
def processRequest(cls, obj, nsdict={}, header=True,
**kw):
tc = None
if kw.has_key('requesttypecode'):
tc = kw['requesttypecode']
elif kw.has_key('requestclass'):
tc = kw['requestclass'].typecode
else:
tc = getattr(obj.__class__, 'typecode', None)
sw = SoapWriter(nsdict=nsdict, header=header,
outputclass=cls.writerClass)
sw.serialize(obj, tc)
return sw
class WSAddressHandler:
"""Minimal WS-Address handler. Most of the logic is in
the ZSI.address.Address class.
class variables:
uri -- default WSA Addressing URI
"""
implements(HandlerChainInterface)
uri = WSA.ADDRESS
def processResponse(self, ps, wsaction=None, soapaction=None, **kw):
addr = self.address
addr.parse(ps)
action = addr.getAction()
if not action:
raise WSActionException('No WS-Action specified in Request')
if not soapaction:
return ps
soapaction = soapaction.strip('\'"')
if soapaction and soapaction != wsaction:
raise WSActionException(\
'SOAP Action("%s") must match WS-Action("%s") if specified.'%(
soapaction, wsaction)
)
return ps
def processRequest(self, sw, wsaction=None, url=None, endPointReference=None, **kw):
from ZSI.address import Address
if sw is None:
self.address = None
return
if not sw.header:
raise RuntimeError, 'expecting SOAP:Header'
self.address = addr = Address(url, wsAddressURI=self.uri)
addr.setRequest(endPointReference, wsaction)
addr.serialize(sw, typed=False)
return sw
class DefaultClientHandlerChain:
@CheckInputArgs(HandlerChainInterface)
def __init__(self, *handlers):
self.handlers = handlers
self.debug = len(log.theLogPublisher.observers) > 0
self.flow = None
@staticmethod
def parseResponse(ps, replytype):
return ps.Parse(replytype)
def processResponse(self, arg, replytype, **kw):
"""
Parameters:
arg -- deferred
replytype -- typecode
"""
if self.debug:
log.msg('--->PROCESS REQUEST\n%s' %arg, debug=1)
for h in self.handlers:
arg.addCallback(h.processResponse, **kw)
arg.addCallback(self.parseResponse, replytype)
def processRequest(self, arg, **kw):
"""
Parameters:
arg -- XML Soap data string
"""
if self.debug:
log.msg('===>PROCESS RESPONSE: %s' %str(arg), debug=1)
if arg is None:
return
for h in self.handlers:
arg = h.processRequest(arg, **kw)
s = str(arg)
if self.debug:
log.msg(s, debug=1)
return s
class DefaultClientHandlerChainFactory:
protocol = DefaultClientHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(ClientDataHandler)
class WSAddressClientHandlerChainFactory:
protocol = DefaultClientHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(ClientDataHandler,
WSAddressHandler())
class Binding:
"""Object that represents a binding (connection) to a SOAP server.
"""
agent='ZSI.twisted client'
factory = DefaultClientHandlerChainFactory
defer = False
def __init__(self, url=None, nsdict=None, contextFactory=None,
tracefile=None, **kw):
"""Initialize.
Keyword arguments include:
url -- URL of resource, POST is path
nsdict -- namespace entries to add
contextFactory -- security contexts
tracefile -- file to dump packet traces
"""
self.url = url
self.nsdict = nsdict or {}
self.contextFactory = contextFactory
self.http_headers = {'content-type': 'text/xml',}
self.trace = tracefile
def addHTTPHeader(self, key, value):
self.http_headers[key] = value
def getHTTPHeaders(self):
return self.http_headers
def Send(self, url, opname, pyobj, nsdict={}, soapaction=None, chain=None,
**kw):
"""Returns a ProcessingChain which needs to be passed to Receive if
Send is being called consecutively.
"""
url = url or self.url
cookies = None
if chain is not None:
cookies = chain.flow.cookies
d = {}
d.update(self.nsdict)
d.update(nsdict)
if soapaction is not None:
self.addHTTPHeader('SOAPAction', soapaction)
chain = self.factory.newInstance()
soapdata = chain.processRequest(pyobj, nsdict=nsdict,
soapaction=soapaction, **kw)
if self.trace:
print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
print >>self.trace, soapdata
f = getPage(str(url), contextFactory=self.contextFactory,
postdata=soapdata, agent=self.agent,
method='POST', headers=self.getHTTPHeaders(),
cookies=cookies)
if isinstance(f, Failure):
return f
chain.flow = f
self.chain = chain
return chain
def Receive(self, replytype, chain=None, **kw):
"""This method allows code to act in a synchronous manner, it waits to
return until the deferred fires but it doesn't prevent other queued
calls from being executed. Send must be called first, which sets up
the chain/factory.
WARNING: If defer is set to True, must either call Receive
immediately after Send (ie. no intervening Sends) or pass
chain in as a paramter.
Parameters:
replytype -- TypeCode
KeyWord Parameters:
chain -- processing chain, optional
"""
chain = chain or self.chain
d = chain.flow.deferred
if self.trace:
def trace(soapdata):
print >>self.trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
print >>self.trace, soapdata
return soapdata
d.addCallback(trace)
chain.processResponse(d, replytype, **kw)
if self.defer:
return d
failure = []
append = failure.append
def errback(result):
"""Used with Response method to suppress 'Unhandled error in
Deferred' messages by adding an errback.
"""
append(result)
return None
d.addErrback(errback)
# spin reactor
while not d.called:
reactor.runUntilCurrent()
t2 = reactor.timeout()
t = reactor.running and t2
reactor.doIteration(t)
pyobj = d.result
if len(failure):
failure[0].raiseException()
return pyobj
def trace():
if trace:
print >>trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
for i in (self.reply_code, self.reply_msg,):
print >>trace, str(i)
print >>trace, "-------"
print >>trace, str(self.reply_headers)
print >>trace, self.data
|