'''\
urllib-based transport plugin for xmlrpclib.py (with test code)
xmlrpc_urllib_transport.py
jjk  07/02/99  001  from xmlrpc_test_urllib.py 002

urllib transport was needed to get past proxy server

for xmlrpclib __version__ = "0.9.8"

****************************
*** USE AT YOUR OWN RISK ***
****************************
'''

import xmlrpclib

class UrllibTransport(xmlrpclib.Transport):
    '''Handles an HTTP transaction to an XML-RPC server via urllib (urllib includes proxy-server support) jjk  07/02/99'''

    def __init__(self, proxies={}):
        self.proxies = proxies
	
    def request(self, host, handler, request_body, verbose):
        '''issue XML-RPC request jjk  07/02/99'''
        self.user_agent = "Podnova"
	self.verbose = verbose
        import urllib2
        
        proxy_support = urllib2.ProxyHandler(self.proxies)
        authinfo = urllib2.HTTPBasicAuthHandler()
        opener = urllib2.build_opener(proxy_support, authinfo, urllib2.HTTPHandler)
        opener.addheaders = [('User-agent', self.user_agent)]
        urllib2.install_opener(opener)
        
        f = urllib2.urlopen(''.join(('http://',host,handler)), request_body)
        return(self.parse_response(f))

def test():
	'''test UrllibTransport for xmlrpclib
	Use proxy for external address, no proxy for local address
	jjk  07/02/99'''
	import os
	raw_input('start xmlrpcserver.py (test mode) on local machine, then press enter')
	testhosts = [
		(0, "http://localhost:8000"),	   # don't use proxy, local host
		#(0, "http://mdcmap.mocons.gov:8000"),   # don't use proxy, another host on local network
		(1, "http://betty.userland.com"),	#use proxy, userland's XML-RPC server
		]
	try: proxies = os.environ['http_proxy']
	except KeyError: proxies = None
	for useproxy, host in testhosts:
		print 
		print 'testing host:', host
		if (useproxy): 
			if (proxies):
				os.environ['HTTP_PROXY'] = proxies
		else:
			try: del os.environ['HTTP_PROXY']
			except KeyError: pass
		server = xmlrpclib.Server(host, transport=UrllibTransport())
		print server
		try: print server.examples.getStateName(41)
		except xmlrpclib.Error, v: print "ERROR", v
		
if (__name__=='__main__'):
	import pdb
	test()
