home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2012 January / maximum-cd-2012-01.iso / DiscContents / digsby_setup.exe / lib / ZSI / ServiceContainer.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-10-05  |  15.5 KB  |  473 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. import urlparse
  5. import types
  6. import os
  7. import sys
  8. import cStringIO as StringIO
  9. import thread
  10. import re
  11. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  12. from ZSI import ParseException, FaultFromException, FaultFromZSIException, Fault
  13. from ZSI import _copyright, _seqtypes, _get_element_nsuri_name, resolvers
  14. from ZSI import _get_idstr
  15. from ZSI.address import Address
  16. from ZSI.parse import ParsedSoap
  17. from ZSI.writer import SoapWriter
  18. from ZSI.dispatch import _ModPythonSendXML, _ModPythonSendFault, _CGISendXML, _CGISendFault
  19. from ZSI.dispatch import SOAPRequestHandler as BaseSOAPRequestHandler
  20.  
  21. class NoSuchService(Exception):
  22.     pass
  23.  
  24.  
  25. class UnknownRequestException(Exception):
  26.     pass
  27.  
  28.  
  29. class PostNotSpecified(Exception):
  30.     pass
  31.  
  32.  
  33. class SOAPActionNotSpecified(Exception):
  34.     pass
  35.  
  36.  
  37. class WSActionException(Exception):
  38.     pass
  39.  
  40.  
  41. class WSActionNotSpecified(WSActionException):
  42.     pass
  43.  
  44.  
  45. class NotAuthorized(Exception):
  46.     pass
  47.  
  48.  
  49. class ServiceAlreadyPresent(Exception):
  50.     pass
  51.  
  52.  
  53. class SOAPContext:
  54.     
  55.     def __init__(self, container, xmldata, ps, connection, httpheaders, soapaction):
  56.         self.container = container
  57.         self.xmldata = xmldata
  58.         self.parsedsoap = ps
  59.         self.connection = connection
  60.         self.httpheaders = httpheaders
  61.         self.soapaction = soapaction
  62.  
  63.  
  64. _contexts = dict()
  65.  
  66. def GetSOAPContext():
  67.     return _contexts[thread.get_ident()]
  68.  
  69.  
  70. def _Dispatch(ps, server, SendResponse, SendFault, post, action, nsdict = { }, **kw):
  71.     localURL = 'http://%s:%d%s' % (server.server_name, server.server_port, post)
  72.     address = action
  73.     service = server.getNode(post)
  74.     isWSResource = False
  75.     if isinstance(service, WSAResource):
  76.         isWSResource = True
  77.         service.setServiceURL(localURL)
  78.         address = Address()
  79.         
  80.         try:
  81.             address.parse(ps)
  82.         except Exception:
  83.             e = None
  84.             return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  85.  
  86.         if action and action != address.getAction():
  87.             e = WSActionException('SOAP Action("%s") must match WS-Action("%s") if specified.' % (action, address.getAction()))
  88.             return SendFault(FaultFromException(e, 0, None), **kw)
  89.         action = address.getAction()
  90.     
  91.     if isinstance(service, ServiceInterface) is False:
  92.         e = NoSuchService('no service at POST(%s) in container: %s' % (post, server))
  93.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  94.     if not service.authorize(None, post, action):
  95.         return SendFault(Fault(Fault.Server, 'Not authorized'), code = 401)
  96.     
  97.     try:
  98.         method = service.getOperation(ps, address)
  99.     except Exception:
  100.         service.authorize(None, post, action)
  101.         e = service.authorize(None, post, action)
  102.         isinstance(service, ServiceInterface) is False
  103.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  104.  
  105.     
  106.     try:
  107.         if isWSResource is True:
  108.             (request, result) = method(ps, address)
  109.         else:
  110.             (request, result) = method(ps)
  111.     except Exception:
  112.         service.authorize(None, post, action)
  113.         e = service.authorize(None, post, action)
  114.         isinstance(service, ServiceInterface) is False
  115.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  116.  
  117.     service.verify(ps)
  118.     if result is None:
  119.         return SendResponse('', **kw)
  120.     sw = SoapWriter(nsdict = nsdict)
  121.     
  122.     try:
  123.         sw.serialize(result)
  124.     except Exception:
  125.         result is None
  126.         e = result is None
  127.         service.authorize(None, post, action)
  128.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  129.         isinstance(service, ServiceInterface) is False
  130.  
  131.     if isWSResource is True:
  132.         action = service.getResponseAction(ps, action)
  133.         addressRsp = Address(action = action)
  134.         
  135.         try:
  136.             addressRsp.setResponseFromWSAddress(address, localURL)
  137.             addressRsp.serialize(sw)
  138.         except Exception:
  139.             result is None
  140.             e = result is None
  141.             service.authorize(None, post, action)
  142.             return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  143.             isinstance(service, ServiceInterface) is False
  144.         
  145.  
  146.     result is None<EXCEPTION MATCH>Exception
  147.     service.sign(sw)
  148.     
  149.     try:
  150.         soapdata = str(sw)
  151.         return SendResponse(soapdata, **kw)
  152.     except Exception:
  153.         result is None
  154.         e = result is None
  155.         result is None
  156.         return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
  157.         service.authorize(None, post, action)
  158.  
  159.  
  160.  
  161. def AsServer(port = 80, services = ()):
  162.     address = ('', port)
  163.     sc = ServiceContainer(address, services)
  164.     sc.serve_forever()
  165.  
  166.  
  167. class ServiceInterface:
  168.     soapAction = { }
  169.     wsAction = { }
  170.     root = { }
  171.     
  172.     def __init__(self, post):
  173.         self.post = post
  174.  
  175.     
  176.     def authorize(self, auth_info, post, action):
  177.         return 1
  178.  
  179.     
  180.     def __str__(self):
  181.         return '%s(%s) POST(%s)' % (self.__class__.__name__, _get_idstr(self), self.post)
  182.  
  183.     
  184.     def sign(self, sw):
  185.         pass
  186.  
  187.     
  188.     def verify(self, ps):
  189.         pass
  190.  
  191.     
  192.     def getPost(self):
  193.         return self.post
  194.  
  195.     
  196.     def getOperation(self, ps, action):
  197.         opName = self.getOperationName(ps, action)
  198.         return getattr(self, opName)
  199.  
  200.     
  201.     def getOperationName(self, ps, action):
  202.         if not self.root.get(_get_element_nsuri_name(ps.body_root)):
  203.             pass
  204.         method = self.soapAction.get(action)
  205.         if method is None:
  206.             raise UnknownRequestException, 'failed to map request to a method: action(%s), root%s' % (action, _get_element_nsuri_name(ps.body_root))
  207.         method is None
  208.         return method
  209.  
  210.  
  211.  
  212. class ServiceSOAPBinding(ServiceInterface):
  213.     
  214.     def __init__(self, post):
  215.         ServiceInterface.__init__(self, post)
  216.  
  217.     
  218.     def __call___(self, action, ps):
  219.         return self.getOperation(ps, action)(ps)
  220.  
  221.  
  222.  
  223. class WSAResource(ServiceSOAPBinding):
  224.     encoding = 'UTF-8'
  225.     
  226.     def __init__(self, post):
  227.         ServiceSOAPBinding.__init__(self, post)
  228.  
  229.     
  230.     def __call___(self, action, ps, address):
  231.         return self.getOperation(ps, action)(ps, address)
  232.  
  233.     
  234.     def getServiceURL(self):
  235.         return self._url
  236.  
  237.     
  238.     def setServiceURL(self, url):
  239.         self._url = url
  240.  
  241.     
  242.     def getOperation(self, ps, address):
  243.         action = address.getAction()
  244.         opName = self.getOperationName(ps, action)
  245.         return getattr(self, opName)
  246.  
  247.     
  248.     def getResponseAction(self, ps, action):
  249.         opName = self.getOperationName(ps, action)
  250.         if self.wsAction.has_key(opName) is False:
  251.             raise WSActionNotSpecified, 'wsAction dictionary missing key(%s)' % opName
  252.         self.wsAction.has_key(opName) is False
  253.         return self.wsAction[opName]
  254.  
  255.     
  256.     def do_POST(self):
  257.         soapAction = self.headers.getheader('SOAPAction')
  258.         post = self.path
  259.         if not post:
  260.             raise PostNotSpecified, 'HTTP POST not specified in request'
  261.         post
  262.         if soapAction:
  263.             soapAction = soapAction.strip('\'"')
  264.         
  265.         post = post.strip('\'"')
  266.         
  267.         try:
  268.             ct = self.headers['content-type']
  269.             if ct.startswith('multipart/'):
  270.                 cid = resolvers.MIMEResolver(ct, self.rfile)
  271.                 xml = cid.GetSOAPPart()
  272.                 ps = ParsedSoap(xml, resolver = cid.Resolve, readerclass = DomletteReader)
  273.             else:
  274.                 length = int(self.headers['content-length'])
  275.                 ps = ParsedSoap(self.rfile.read(length), readerclass = DomletteReader)
  276.         except ParseException:
  277.             e = None
  278.             self.send_fault(FaultFromZSIException(e))
  279.         except Exception:
  280.             e = None
  281.             self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
  282.  
  283.         thread_id = thread.get_ident()
  284.         _contexts[thread_id] = SOAPContext(self.server, xml, ps, self.connection, self.headers, soapAction)
  285.         
  286.         try:
  287.             _Dispatch(ps, self.server, self.send_xml, self.send_fault, post = post, action = soapAction)
  288.         except Exception:
  289.             e = None
  290.             self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
  291.  
  292.         if _contexts.has_key(thread_id):
  293.             del _contexts[thread_id]
  294.         
  295.  
  296.  
  297.  
  298. class SOAPRequestHandler(BaseSOAPRequestHandler):
  299.     
  300.     def do_POST(self):
  301.         soapAction = self.headers.getheader('SOAPAction')
  302.         post = self.path
  303.         if not post:
  304.             raise PostNotSpecified, 'HTTP POST not specified in request'
  305.         post
  306.         if soapAction:
  307.             soapAction = soapAction.strip('\'"')
  308.         
  309.         post = post.strip('\'"')
  310.         
  311.         try:
  312.             ct = self.headers['content-type']
  313.             if ct.startswith('multipart/'):
  314.                 cid = resolvers.MIMEResolver(ct, self.rfile)
  315.                 xml = cid.GetSOAPPart()
  316.                 ps = ParsedSoap(xml, resolver = cid.Resolve)
  317.             else:
  318.                 length = int(self.headers['content-length'])
  319.                 xml = self.rfile.read(length)
  320.                 ps = ParsedSoap(xml)
  321.         except ParseException:
  322.             e = None
  323.             self.send_fault(FaultFromZSIException(e))
  324.         except Exception:
  325.             e = None
  326.             self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
  327.  
  328.         thread_id = thread.get_ident()
  329.         _contexts[thread_id] = SOAPContext(self.server, xml, ps, self.connection, self.headers, soapAction)
  330.         
  331.         try:
  332.             _Dispatch(ps, self.server, self.send_xml, self.send_fault, post = post, action = soapAction)
  333.         except Exception:
  334.             e = None
  335.             self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
  336.  
  337.         if _contexts.has_key(thread_id):
  338.             del _contexts[thread_id]
  339.         
  340.  
  341.     
  342.     def do_GET(self):
  343.         if self.path.lower().endswith('?wsdl'):
  344.             service_path = self.path[:-5]
  345.             service = self.server.getNode(service_path)
  346.             if hasattr(service, '_wsdl'):
  347.                 wsdl = service._wsdl
  348.                 proto = 'http'
  349.                 if hasattr(self.server, 'proto'):
  350.                     proto = self.server.proto
  351.                 
  352.                 serviceUrl = '%s://%s:%d%s' % (proto, self.server.server_name, self.server.server_port, service_path)
  353.                 soapAddress = '<soap:address location="%s"/>' % serviceUrl
  354.                 wsdlre = re.compile('\\<soap:address[^\\>]*>', re.IGNORECASE)
  355.                 wsdl = re.sub(wsdlre, soapAddress, wsdl)
  356.                 self.send_xml(wsdl)
  357.             else:
  358.                 self.send_error(404, 'WSDL not available for that service [%s].' % self.path)
  359.         else:
  360.             self.send_error(404, 'Service not found [%s].' % self.path)
  361.  
  362.  
  363.  
  364. class ServiceContainer(HTTPServer):
  365.     
  366.     class NodeTree:
  367.         
  368.         def __init__(self):
  369.             self._NodeTree__dict = { }
  370.  
  371.         
  372.         def __str__(self):
  373.             return str(self._NodeTree__dict)
  374.  
  375.         
  376.         def listNodes(self):
  377.             print self._NodeTree__dict.keys()
  378.  
  379.         
  380.         def getNode(self, url):
  381.             path = urlparse.urlsplit(url)[2]
  382.             if path.startswith('/'):
  383.                 path = path[1:]
  384.             
  385.             if self._NodeTree__dict.has_key(path):
  386.                 return self._NodeTree__dict[path]
  387.             raise NoSuchService, 'No service(%s) in ServiceContainer' % path
  388.  
  389.         
  390.         def setNode(self, service, url):
  391.             path = urlparse.urlsplit(url)[2]
  392.             if path.startswith('/'):
  393.                 path = path[1:]
  394.             
  395.             if not isinstance(service, ServiceSOAPBinding):
  396.                 raise TypeError, 'A Service must implement class ServiceSOAPBinding'
  397.             isinstance(service, ServiceSOAPBinding)
  398.             if self._NodeTree__dict.has_key(path):
  399.                 raise ServiceAlreadyPresent, 'Service(%s) already in ServiceContainer' % path
  400.             self._NodeTree__dict.has_key(path)
  401.             self._NodeTree__dict[path] = service
  402.  
  403.         
  404.         def removeNode(self, url):
  405.             path = urlparse.urlsplit(url)[2]
  406.             if path.startswith('/'):
  407.                 path = path[1:]
  408.             
  409.             if self._NodeTree__dict.has_key(path):
  410.                 node = self._NodeTree__dict[path]
  411.                 del self._NodeTree__dict[path]
  412.                 return node
  413.             raise NoSuchService, 'No service(%s) in ServiceContainer' % path
  414.  
  415.  
  416.     
  417.     def __init__(self, server_address, services = [], RequestHandlerClass = SOAPRequestHandler):
  418.         HTTPServer.__init__(self, server_address, RequestHandlerClass)
  419.         self._nodes = self.NodeTree()
  420.         (map,)((lambda s: self.setNode(s)), services)
  421.  
  422.     
  423.     def __str__(self):
  424.         return '%s(%s) nodes( %s )' % (self.__class__, _get_idstr(self), str(self._nodes))
  425.  
  426.     
  427.     def __call__(self, ps, post, action, address = None):
  428.         method = self.getCallBack(ps, post, action)
  429.         if isinstance(method.im_self, WSAResource) or isinstance(method.im_self, SimpleWSResource):
  430.             return method(ps, address)
  431.         return method(ps)
  432.  
  433.     
  434.     def setNode(self, service, url = None):
  435.         if url is None:
  436.             url = service.getPost()
  437.         
  438.         self._nodes.setNode(service, url)
  439.  
  440.     
  441.     def getNode(self, url):
  442.         return self._nodes.getNode(url)
  443.  
  444.     
  445.     def removeNode(self, url):
  446.         self._nodes.removeNode(url)
  447.  
  448.  
  449.  
  450. class SimpleWSResource(ServiceSOAPBinding):
  451.     
  452.     def getNode(self, post):
  453.         return self._nodes.getNode(post)
  454.  
  455.     
  456.     def setNode(self, service, post):
  457.         self._nodes.setNode(service, post)
  458.  
  459.     
  460.     def getCallBack(self, ps, post, action):
  461.         node = self.getNode(post)
  462.         if node is None:
  463.             raise NoSuchFunction
  464.         node is None
  465.         if node.authorize(None, post, action):
  466.             return node.getOperation(ps, action)
  467.         raise NotAuthorized, 'Authorization failed for method %s' % action
  468.  
  469.  
  470. if __name__ == '__main__':
  471.     print _copyright
  472.  
  473.