Exemple #1
0
def _Dispatch(ps,
              server,
              SendResponse,
              SendFault,
              post,
              action,
              nsdict={},
              **kw):
    '''Send ParsedSoap instance to ServiceContainer, which dispatches to
    appropriate service via post, and method via action.  Response is a
    self-describing pyobj, which is passed to a SoapWriter.

    Call SendResponse or SendFault to send the reply back, appropriately.
        server -- ServiceContainer instance

    '''
    localURL = 'http://%s:%d%s' % (server.server_name, server.server_port,
                                   post)
    address = action
    service = server.getNode(post)
    isWSResource = False
    if isinstance(service, WSAResource):
        isWSResource = True
        service.setServiceURL(localURL)
        address = Address()
        try:
            address.parse(ps)
        except Exception, e:
            return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
        if action and action != address.getAction():
            e = WSActionException('SOAP Action("%s") must match WS-Action("%s") if specified.' \
                %(action,address.getAction()))
            return SendFault(FaultFromException(e, 0, None), **kw)
        action = address.getAction()
    def dispatch(self, req):
        path = req.uri[1:]
        if (path[-1] == "/"):
            path = path[:-1]

        if not configs.has_key(path):
            if req.method == "POST":
                self.send_fault(
                    Fault(Fault.Client,
                          "Unknown Database Path %s" % (repr(configs.keys()))),
                    req)
            else:
                # Construct simple table of contents page
                xml = ['<databases>']
                for k in configs:
                    xml.append("<database><path>%s</path></database>" % k)
                xml.append('</databases>')
                txt = ''.join(xml)
                self.send_xml(txt, req)
        else:
            xreq = None
            config = configs[path]
            if (req.method == "POST"):
                try:
                    data = req.read()
                    dstr = StringIO.StringIO(data)
                    ps = ParsedSoap(dstr, readerclass=reader)
                except Exception, e:
                    try:
                        self.send_fault(FaultFromException(e, 0), req)
                    except Exception, e:
                        self.send_fault(FaultFromException(e, 0), req)
                    return
                callname = ps.body_root.localName
                classname = callname[0].upper() + callname[1:]
                try:
                    try:
                        mod = SRW.protocolModules[ps.body_root.namespaceURI]
                    except KeyError:
                        log("%r -> %r" % (ps.body_root.namespaceURI, data))
                        self.send_fault(Fault(Fault.Client, 'Bad Namespace'),
                                        req)
                        return
                    config = config[ps.body_root.namespaceURI]
                    objType = getattr(mod, classname)
                    xreq = ps.Parse(objType)
                    xreq.configure(config)
                    xreq.calledAt = path
                    result = self.call(xreq)
                except AttributeError, err:
                    # result = self.processUnknownOperation(classname, err, config)
                    self.send_fault(
                        Fault(Fault.Client,
                              'Unknown Operation (%s)' % str(err)), req)
                    return
Exemple #3
0
    def do_POST(self):
        '''The POST command.  This is called by HTTPServer, not twisted.
        action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
        '''
        global _contexts

        soapAction = self.headers.getheader('SOAPAction')
        post = self.path
        if not post:
            raise PostNotSpecified('HTTP POST not specified in request')
        if soapAction:
            soapAction = soapAction.strip('\'"')
        post = post.strip('\'"')
        try:
            ct = self.headers['content-type']
            if ct.startswith('multipart/'):
                cid = resolvers.MIMEResolver(ct, self.rfile)
                xml = cid.GetSOAPPart()
                ps = ParsedSoap(xml,
                                resolver=cid.Resolve,
                                readerclass=DomletteReader)
            else:
                length = int(self.headers['content-length'])
                ps = ParsedSoap(self.rfile.read(length),
                                readerclass=DomletteReader)
        except ParseException as e:
            self.send_fault(FaultFromZSIException(e))
        except Exception as e:
            # Faulted while processing; assume it's in the header.
            self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
        else:
            # Keep track of calls
            thread_id = _thread.get_ident()
            _contexts[thread_id] = SOAPContext(self.server, xml, ps,
                                               self.connection, self.headers,
                                               soapAction)

            try:
                _Dispatch(ps,
                          self.server,
                          self.send_xml,
                          self.send_fault,
                          post=post,
                          action=soapAction)
            except Exception as e:
                self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))

            # Clean up after the call
            if thread_id in _contexts:
                del _contexts[thread_id]
class SOAPRequestHandler(BaseSOAPRequestHandler):
    '''SOAP handler.
    '''
    def do_POST(self):
        '''The POST command.
        action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
        '''
        soapAction = self.headers.getheader('SOAPAction')
        post = self.path
        if not post:
            raise PostNotSpecified, 'HTTP POST not specified in request'
        if soapAction:
            soapAction = soapAction.strip('\'"')
        post = post.strip('\'"')
        try:
            ct = self.headers['content-type']
            if ct.startswith('multipart/'):
                cid = resolvers.MIMEResolver(ct, self.rfile)
                xml = cid.GetSOAPPart()
                ps = ParsedSoap(xml, resolver=cid.Resolve)
            else:
                length = int(self.headers['content-length'])
                xml = self.rfile.read(length)
                ps = ParsedSoap(xml)
        except ParseException, e:
            self.send_fault(FaultFromZSIException(e))
        except Exception, e:
            # Faulted while processing; assume it's in the header.
            self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
class MySOAPRequestHandler(SOAPRequestHandler):
    def _getOperacio(self, parsedSoap):
        operacio = parsedSoap.body_root.getElementsByTagName("operacio").item(
            0).firstChild.nodeValue
        return operacio

    def _getLlistaPdfs(self, parsedSoap):
        llistatNodeList = parsedSoap.body_root.getElementsByTagName(
            "llistaPdfs_b64")
        llistatPDFs = []
        if llistatNodeList.length > 0:
            llistatPdfsNodeList = parsedSoap.body_root.getElementsByTagName(
                "pdf_b64")
            for i in range(llistatPdfsNodeList.length):
                pdf = llistatPdfsNodeList.item(i).firstChild.nodeValue
                llistatPDFs.append(pdf)
        return llistatPDFs

    def do_GET(self):
        #Return the WSDL file. We expect to get the location from the
        #invocation URL ("path").
        #wsdlfile = os.path.join('.', self.path.replace('/', "", 1) + ".wsdl")
        #wsdlfile = os.path.join('.', "./ws.wsdl")
        wsdlfile = os.path.join('.',
                                "./wsdl/ED_INT040_PDfUtils_merge_WSDL.wsdl")
        print ">>>>> using wsdl file", wsdlfile
        wsdl = open(wsdlfile).read()
        self.send_xml(wsdl)

    def do_POST(self):
        soapAction = self.headers.getheader('SOAPAction')
        post = self.path
        if not post:
            raise PostNotSpecified('HTTP POST not specified in request')
        if soapAction:
            soapAction = soapAction.strip('\'"')
            #Forzado porque SAP no lo envía bien.
            soapAction = "http://PdfUtils.csi.org/merge2Pdfs"
        post = post.strip('\'"')
        try:
            ct = self.headers['content-type']
            if ct.startswith('multipart/'):
                cid = resolvers.MIMEResolver(ct, self.rfile)
                xml = cid.GetSOAPPart()
                ps = ParsedSoap(xml, resolver=cid.Resolve)
            else:
                length = int(self.headers['content-length'])
                xml = self.rfile.read(length)
                ps = ParsedSoap(xml)

        except ParseException, e:
            self.send_fault(FaultFromZSIException(e))
        except Exception, e:
            # Faulted while processing; assume it's in the header.
            self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
Exemple #6
0
class t2TestCase(unittest.TestCase):
    "Test case wrapper for old ZSI t2 test case"

    def checkt2(self):
        try:
            ps = ParsedSoap(IN)
        except ParseException, e:
            print >> OUT, FaultFromZSIException(e).AsSOAP()
            self.fail()
        except Exception, e:
            # Faulted while processing; assume it's in the
            # header.
            print >> OUT, FaultFromException(e, 1).AsSOAP()
            self.fail()
Exemple #7
0
    def do_POST(self):
        '''The POST command.
        '''
        try:
            ct = self.headers['content-type']
            if ct.startswith('multipart/'):
                cid = resolvers.MIMEResolver(ct, self.rfile)
                xml = cid.GetSOAPPart()
                ps = ParsedSoap(xml, resolver=cid.Resolve)
            else:
                length = int(self.headers['content-length'])
                ps = ParsedSoap(self.rfile.read(length))
        except ParseException as e:
            self.send_fault(FaultFromZSIException(e))
            return
        except Exception as e:
            # Faulted while processing; assume it's in the header.
            self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
            return

        _Dispatch(ps, self.server.modules, self.send_xml, self.send_fault,
                  docstyle=self.server.docstyle, nsdict=self.server.nsdict,
                  typesmodule=self.server.typesmodule, rpc=self.server.rpc)
Exemple #8
0
class SOAPRequestHandler(BaseSOAPRequestHandler):
    '''SOAP handler.
    '''
    def _read_chunk_size(self):
        current_size = ""
        while '\n' not in current_size:
            current_size += self.rfile.read(1)
        current_size = int(current_size, 16)
        return current_size

    def _fix_chunked_encoding(self):
        from StringIO import StringIO
        if self.headers.get('transfer-encoding', '') != 'chunked':
            return
        full_data = ""
        while True:
            current_size = self._read_chunk_size()
            if current_size == 0:
                break
            full_data += self.rfile.read(current_size)
            self.rfile.read(2)  # CRLF after chunk

        self.rfile = StringIO(full_data)
        self.headers['content-length'] = str(len(full_data))
        return full_data

    def do_POST(self):
        '''The POST command.
        action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
        '''
        self._fix_chunked_encoding()

        logger.debug("Request Host: {}".format(self.client_address))
        logger.debug("Request URI: {}".format(self.requestline))
        for key, value in self.headers.items():
            logger.debug("Request Header: {}: {}".format(key, value))
        content_type = self.headers.get("content-type", '')
        action_matchobj = re.search("action=\"(urn:\w+)\"", content_type)
        if action_matchobj is not None:
            # SOAP 1.2
            soapAction = action_matchobj.group(1)
        else:
            # SOAP 1.1
            soapAction = self.headers.getheader('SOAPAction')
            if soapAction:
                soapAction = soapAction.strip('\'"')
        self._soapAction = soapAction
        post = self.path
        if not post:
            raise PostNotSpecified, 'HTTP POST not specified in request'
        post = post.strip('\'"')
        try:
            ct = self.headers['content-type']
            if ct.startswith('multipart/'):
                cid = resolvers.MIMEResolver(ct, self.rfile)
                xml = cid.GetSOAPPart()
                ps = ParsedSoap(xml, resolver=cid.Resolve)
            else:
                length = int(self.headers['content-length'])
                xml = self.rfile.read(length)
                logger.debug("Request Body: {}".format(xml))
                ps = ParsedSoap(xml)
        except ParseException, e:
            self.send_fault(FaultFromZSIException(e))
        except Exception, e:
            # Faulted while processing; assume it's in the header.
            self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
Exemple #9
0
class WSAResource(ServiceSOAPBinding):
    '''Simple WSRF service, performs method resolutions based
    on WS-Action values rather than SOAP Action.

    class variables:
        encoding
        wsAction -- Must override to set output Action values.
        soapAction -- Must override to set input Action values.
    '''
    encoding = "UTF-8"

    def __init__(self, post):
        '''
        post -- POST value
        '''
        assert isinstance(self.soapAction, dict), "soapAction must be a dict"
        assert isinstance(self.wsAction, dict), "wsAction must be a dict"
        ServiceSOAPBinding.__init__(self, post)

    def __call___(self, action, ps, address):
        return self.getOperation(ps, action)(ps, address)

    def getServiceURL(self):
        return self._url

    def setServiceURL(self, url):
        self._url = url

    def getOperation(self, ps, address):
        '''Returns a method of class.
        address -- ws-address
        '''
        action = address.getAction()
        opName = self.getOperationName(ps, action)
        return getattr(self, opName)

    def getResponseAction(self, ps, action):
        '''Returns response WS-Action if available
           action -- request WS-Action value.
        '''
        opName = self.getOperationName(ps, action)
        if self.wsAction.has_key(opName) is False:
            raise WSActionNotSpecified, 'wsAction dictionary missing key(%s)' % opName
        return self.wsAction[opName]

    def do_POST(self):
        '''The POST command.  This is called by HTTPServer, not twisted.
        action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
        '''
        global _contexts

        soapAction = self.headers.getheader('SOAPAction')
        post = self.path
        if not post:
            raise PostNotSpecified, 'HTTP POST not specified in request'
        if soapAction:
            soapAction = soapAction.strip('\'"')
        post = post.strip('\'"')
        try:
            ct = self.headers['content-type']
            if ct.startswith('multipart/'):
                cid = resolvers.MIMEResolver(ct, self.rfile)
                xml = cid.GetSOAPPart()
                ps = ParsedSoap(xml,
                                resolver=cid.Resolve,
                                readerclass=DomletteReader)
            else:
                length = int(self.headers['content-length'])
                ps = ParsedSoap(self.rfile.read(length),
                                readerclass=DomletteReader)
        except ParseException, e:
            self.send_fault(FaultFromZSIException(e))
        except Exception, e:
            # Faulted while processing; assume it's in the header.
            self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
Exemple #10
0
        service.setServiceURL(localURL)
        address = Address()
        try:
            address.parse(ps)
        except Exception, e:
            return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
        if action and action != address.getAction():
            e = WSActionException('SOAP Action("%s") must match WS-Action("%s") if specified.' \
                %(action,address.getAction()))
            return SendFault(FaultFromException(e, 0, None), **kw)
        action = address.getAction()

    if isinstance(service, ServiceInterface) is False:
        e = NoSuchService('no service at POST(%s) in container: %s' %
                          (post, server))
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)

    if not service.authorize(None, post, action):
        return SendFault(Fault(Fault.Server, "Not authorized"), code=401)
        #try:
        #    raise NotAuthorized()
        #except Exception, e:
        #return SendFault(FaultFromException(e, 0, None), code=401, **kw)
        ##return SendFault(FaultFromException(NotAuthorized(), 0, None), code=401, **kw)

    try:
        method = service.getOperation(ps, address)
    except Exception, e:
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)

    try:
            # Keep track of calls
            thread_id = thread.get_ident()
            _contexts[thread_id] = SOAPContext(self.server, xml, ps,
                                               self.connection, self.headers,
                                               soapAction)

            try:
                #Entregamos la petición al dispatcher.
                _Dispatch(ps,
                          self.server,
                          self.send_xml,
                          self.send_fault,
                          post=post,
                          action=soapAction)
            except Exception, e:
                self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))

            # Clean up after the call
            if thread_id in _contexts:
                del _contexts[thread_id]


#Funcion que configura el servidor y lo ejecuta en loop.
def AsServer(port=80,
             services=(),
             RequestHandlerClass=SOAPRequestHandler,
             direccion):
    address = (direccion, port)
    sc = ServiceContainer(address, RequestHandlerClass=RequestHandlerClass)
    for service in services:
        path = service.getPost()
Exemple #12
0
def _Dispatch(ps,
              server,
              SendResponse,
              SendFault,
              post,
              action,
              nsdict={},
              **kw):
    '''Send ParsedSoap instance to ServiceContainer, which dispatches to
    appropriate service via post, and method via action.  Response is a
    self-describing pyobj, which is passed to a SoapWriter.

    Call SendResponse or SendFault to send the reply back, appropriately.
        server -- ServiceContainer instance

    '''
    localURL = 'http://%s:%d%s' % (server.server_name, server.server_port,
                                   post)
    address = action
    service = server.getNode(post)
    isWSResource = False
    if isinstance(service, WSAResource):
        isWSResource = True
        service.setServiceURL(localURL)
        address = Address()
        try:
            address.parse(ps)
        except Exception as e:
            return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
        if action and action != address.getAction():
            e = WSActionException('SOAP Action("%s") must match WS-Action("%s") if specified.' \
                %(action,address.getAction()))
            return SendFault(FaultFromException(e, 0, None), **kw)
        action = address.getAction()

    if isinstance(service, ServiceInterface) is False:
        e = NoSuchService('no service at POST(%s) in container: %s' %
                          (post, server))
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)

    if not service.authorize(None, post, action):
        return SendFault(Fault(Fault.Server, "Not authorized"), code=401)
        #try:
        #    raise NotAuthorized()
        #except Exception, e:
        #return SendFault(FaultFromException(e, 0, None), code=401, **kw)
        ##return SendFault(FaultFromException(NotAuthorized(), 0, None), code=401, **kw)

    try:
        method = service.getOperation(ps, address)
    except Exception as e:
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)

    try:
        if isWSResource is True:
            _, result = method(ps, address)
        else:
            _, result = method(ps)
    except Exception as e:
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)

    # Verify if Signed
    service.verify(ps)

    # If No response just return.
    if result is None:
        return SendResponse('', **kw)

    sw = SoapWriter(nsdict=nsdict)
    try:
        sw.serialize(result)
    except Exception as e:
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)

    if isWSResource is True:
        action = service.getResponseAction(ps, action)
        addressRsp = Address(action=action)
        try:
            addressRsp.setResponseFromWSAddress(address, localURL)
            addressRsp.serialize(sw)
        except Exception as e:
            return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)

    # Create Signatures
    service.sign(sw)

    try:
        soapdata = str(sw)
        return SendResponse(soapdata, **kw)
    except Exception as e:
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
Exemple #13
0
def _Dispatch(ps, modules, SendResponse, SendFault, nsdict={}, typesmodule=None,
              gettypecode=gettypecode, rpc=False, docstyle=False, **kw):
    '''Find a handler for the SOAP request in ps; search modules.
    Call SendResponse or SendFault to send the reply back, appropriately.

    Behaviors:
        default -- Call "handler" method with pyobj representation of body root, and return
            a self-describing request (w/typecode).  Parsing done via a typecode from
            typesmodule, or Any.

        docstyle -- Call "handler" method with ParsedSoap instance and parse result with an
          XML typecode (DOM). Behavior, wrap result in a body_root "Response" appended message.

        rpc -- Specify RPC wrapper of result. Behavior, ignore body root (RPC Wrapper)
           of request, parse all "parts" of message via individual typecodes.  Expect
           the handler to return the parts of the message, whether it is a dict, single instance,
           or a list try to serialize it as a Struct but if this is not possible put it in an Array.
           Parsing done via a typecode from typesmodule, or Any.

    '''
    global _client_binding
    try:
        what = str(ps.body_root.localName)

        # See what modules have the element name.
        if modules is None:
            modules = ( sys.modules['__main__'], )

        handlers = [ getattr(m, what) for m in modules if hasattr(m, what) ]
        if len(handlers) == 0:
            raise TypeError("Unknown method " + what)

        # Of those modules, see who's callable.
        handlers = [ h for h in handlers if callable(h) ]
        if len(handlers) == 0:
            raise TypeError("Unimplemented method " + what)
        if len(handlers) > 1:
            raise TypeError("Multiple implementations found: %s" % handlers)
        handler = handlers[0]

        _client_binding = ClientBinding(ps)
        if docstyle:
            result = handler(ps.body_root)
            tc = TC.XML(aslist=1, pname=what+'Response')
        elif not rpc:
            try:
                tc = gettypecode(typesmodule, ps.body_root)
            except Exception:
                tc = TC.Any()

            try:
                arg = tc.parse(ps.body_root, ps)
            except EvaluateException as ex:
                SendFault(FaultFromZSIException(ex), **kw)
                return

            try:
                result = handler(arg)
            except Exception as ex:
                SendFault(FaultFromZSIException(ex), **kw)
                return

            try:
                tc = result.typecode
            except AttributeError as ex:
                SendFault(FaultFromZSIException(ex), **kw)
                return

        elif typesmodule is not None:
            kwargs = {}
            for e in _child_elements(ps.body_root):
                try:
                    tc = gettypecode(typesmodule, e)
                except Exception:
                    tc = TC.Any()

                try:
                    kwargs[str(e.localName)] = tc.parse(e, ps)
                except EvaluateException as ex:
                    SendFault(FaultFromZSIException(ex), **kw)
                    return

            result = handler(**kwargs)
            aslist = False
            # make sure data is wrapped, try to make this a Struct
            if isinstance(result,_seqtypes):
                for _ in result:
                    aslist = hasattr(result, 'typecode')
                    if aslist: break
            elif not isinstance(result, dict):
                aslist = not hasattr(result, 'typecode')
                result = (result,)

            tc = TC.Any(pname=what+'Response', aslist=aslist)
        else:
            # if this is an Array, call handler with list
            # if this is an Struct, call handler with dict
            tp = _find_type(ps.body_root)
            isarray = ((isinstance(tp, (tuple,list)) and tp[1] == 'Array') or _find_arraytype(ps.body_root))
            data = _child_elements(ps.body_root)
            tc = TC.Any()
            if isarray and len(data) == 0:
                result = handler()
            elif isarray:
                try: arg = [ tc.parse(e, ps) for e in data ]
                except EvaluateException as e:
                    #SendFault(FaultFromZSIException(e), **kw)
                    SendFault(RuntimeError("THIS IS AN ARRAY: %s" %isarray))
                    return

                result = handler(*arg)
            else:
                try: kwarg = dict([ (str(e.localName),tc.parse(e, ps)) for e in data ])
                except EvaluateException as e:
                    SendFault(FaultFromZSIException(e), **kw)
                    return

                result = handler(**kwarg)

            # reponse typecode
            #tc = getattr(result, 'typecode', TC.Any(pname=what+'Response'))
            tc = TC.Any(pname=what+'Response')

        sw = SoapWriter(nsdict=nsdict)
        sw.serialize(result, tc)
        return SendResponse(str(sw), **kw)
    except Fault as e:
        return SendFault(e, **kw)
    except Exception as e:
        # Something went wrong, send a fault.
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
Exemple #14
0
        try:
            player = ps.Parse(Player)
        except EvaluateException, e:
            print >> OUT, FaultFromZSIException(e).AsSOAP()
            self.fail()

        try:
            import operator
            total = reduce(operator.add, player.Scores, 0)
            result = Average(foo(total, len(player.Scores)))
            sw = SoapWriter().serialize(result)
            str(sw)
            #print >>OUT, str(sw)
        except Exception, e:
            print >> OUT, FaultFromException(e, 0, sys.exc_info()[2]).AsSOAP()
            self.fail()


def makeTestSuite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(t2TestCase, "check"))
    return suite


class Player:
    '''Input class.'''
    def __init__(self, name=None):
        pass