Exemplo n.º 1
0
 def test_portypes(self):
     app = Application([TestService], 'tns')
     _wsdl = app.get_wsdl('')
     wsdl = etree.fromstring(_wsdl)
     porttype = wsdl.find('{http://schemas.xmlsoap.org/wsdl/}portType')
     srv = TestService()
     self.assertEquals(
         len(srv.public_methods), len(porttype.getchildren()))
Exemplo n.º 2
0
    def test_wsdl(self):
        app = Application([TestService],'tns')
        wsdl = app.get_wsdl('punk')
        elt = etree.fromstring(wsdl)
        simple_type = elt.xpath('//xs:simpleType', namespaces=app.nsmap)[0]

        # Avoid printing debug output during test runs.
        #print etree.tostring(elt, pretty_print=True)
        #print simple_type

        self.assertEquals(simple_type.attrib['name'], 'DaysOfWeekEnum')
        self.assertEquals(simple_type[0].tag, "{%s}restriction" % namespaces.ns_xsd)
        self.assertEquals([e.attrib['value'] for e in simple_type[0]], vals)
Exemplo n.º 3
0
    def test_wsdl(self):
        app = Application([TestService], 'tns')
        wsdl = app.get_wsdl('punk')
        elt = etree.fromstring(wsdl)
        simple_type = elt.xpath('//xs:simpleType', namespaces=app.nsmap)[0]

        # Avoid printing debug output during test runs.
        #print etree.tostring(elt, pretty_print=True)
        #print simple_type

        self.assertEquals(simple_type.attrib['name'], 'DaysOfWeekEnum')
        self.assertEquals(simple_type[0].tag,
                          "{%s}restriction" % namespaces.ns_xsd)
        self.assertEquals([e.attrib['value'] for e in simple_type[0]], vals)
Exemplo n.º 4
0
    def test_multiple_return(self):
        app = Application([MultipleReturnService], 'tns')
        app.get_wsdl('')
        srv = MultipleReturnService()
        message = srv.public_methods[0].out_message()

        self.assertEquals(len(message._type_info), 3)

        sent_xml = etree.Element('test')
        message.to_parent_element( ('a','b','c'), srv.get_tns(), sent_xml )
        sent_xml = sent_xml[0]

        response_data = message.from_xml(sent_xml)

        self.assertEquals(len(response_data), 3)
        self.assertEqual(response_data[0], 'a')
        self.assertEqual(response_data[1], 'b')
        self.assertEqual(response_data[2], 'c')
Exemplo n.º 5
0
    def __get_binding_application(self, binding_service):
        '''Builds an instance of soaplib.Application

        The Application built is populated with an instance of a Service Class
        based on DefinitionBase
        @param A class based on DefinitionBase
        '''

        binding_application = Application([binding_service],
                                          'binding_application')

        # The lxml Element nsmap is being overridden to remove the unneeded
        # namespaces
        binding_application.nsmap = XSDGenerator.model_schema_nsmap
        binding_application.prefmap = \
                dict([(b,a) for a,b in XSDGenerator.model_schema_nsmap.items()])

        binding_application.call_routes = {}

        return binding_application
Exemplo n.º 6
0
    def __get_binding_application(self, binding_service):
        '''Builds an instance of soaplib.Application

        The Application built is populated with an instance of a Service Class
        based on DefinitionBase
        @param A class based on DefinitionBase
        '''

        binding_application = Application([binding_service],
                                          'binding_application')

        # The lxml Element nsmap is being overridden to remove the unneeded
        # namespaces
        binding_application.nsmap = XSDGenerator.model_schema_nsmap
        binding_application.prefmap = \
                dict([(b,a) for a,b in XSDGenerator.model_schema_nsmap.items()])

        binding_application.call_routes = {}

        return binding_application
Exemplo n.º 7
0
    def __get_binding_application(self, binding_service, model):
        """Builds an instance of soaplib.Application

        The Application built is populated with an instance of a Service Class
        based on DefinitionBase
        @param binding_service:  class based on DefinitionBase
        @param model: An ClassModel
        """

        binding_application = Application([binding_service],
                                          model.get_namespace())

        # The lxml Element nsmap is being overridden to remove the unneeded
        # namespaces
        binding_application.nsmap = XSDGenerator.model_schema_nsmap
        binding_application.prefmap = \
                dict([(b,a) for a,b in XSDGenerator.model_schema_nsmap.items()])

        binding_application.call_routes = {}

        if self.custom_map:
            for prefix, namespace in self.custom_map.items():
                binding_application.set_namespace_prefix(namespace, prefix)


        return binding_application
Exemplo n.º 8
0
def build_app(service_list, tns, name):

    app = Application(service_list, tns, name)
    app.transport = 'http://schemas.xmlsoap.org/soap/http'
    return app
Exemplo n.º 9
0
 def __init__(self, tns, environ=None):
     super(DefinitionBase, self).__init__(environ)
     self.soap_app = Application(self, tns, False)
     self.soap_handler = BaseServer(self.soap_app)
Exemplo n.º 10
0
class SoapFolder(DefinitionBase):
    """Mix-In Class to Make a Folder into a SOAP Service Point

    Import this class into your Zope2 folder classes to make them SOAP-aware.
    Any methods in your folder class decorated with @soapmethod() will become
    callable over SOAP and the signature and docstring of that method will be
    reported as WSDL by a call to the index_html() method of that folder.

    Your class should also define a class attribute indicating the 'toplevel
    namespace' of your SOAP Service Point.  This name is arbitrary as far as
    this code goes, but appears in the SOAP response and the WSDL description
    generated.  This attribute looks like:   __tns__ = "PatientServices"
    """

    _v_soap_methods = None
    _v_cached_wsdl = None
    __wsdl__ = None


    def __init__(self, tns, environ=None):
        super(DefinitionBase, self).__init__(environ)
        self.soap_app = Application(self, tns, False)
        self.soap_handler = BaseServer(self.soap_app)


    def methods(self):
        """Returns a list of method descriptors for this object"""
        if self._v_soap_methods is None:
            self._v_soap_methods = self.build_public_methods()
        return self._v_soap_methods


    def service_description(self, REQUEST, RESPONSE):
        """ """

        if getattr(self, '__tns__', None) is None:
            self.__tns__ = self.get_tns(self.__class__)

        if self._v_soap_methods is None:
            self._v_soap_methods = self.build_public_methods()

        if self._v_cached_wsdl is None:
            self._v_cached_wsdl = self.soap_app.get_wsdl(self.absolute_url())
            self.__wsdl__ = None

        RESPONSE.setHeader('Content-Type', 'text/xml')
        return self._v_cached_wsdl

    def index_html(self, REQUEST, RESPONSE):
        """Handle an incoming SOAP request or a non-SOAP WSDL query."""

        if REQUEST.get('SOAPXML', None) == None:  # Not a SOAP Request, return WSDL
            return self.service_description(REQUEST, RESPONSE)

        try:
            # Deserialize the Body of the SOAP Request
            from soaplib.core._base import _from_soap
            header, payload = _from_soap(REQUEST.SOAPXML)

            # TODO: At this point I need dispatch method calls to the soaplib.Application
            # somehow....... :)
            ctx = MethodContext()

            content_type  = cgi.parse_header(REQUEST.get("Content-Type"))
            charset = content_type[1].get('charset',None)
            length = REQUEST.get("Content-Length")
            http_payload = REQUEST.read(int(length))

            if not charset:
                charset = "ascii"

            in_string = collapse_swa(content_type, http_payload)
            in_obj = self.soap_handler.get_in_object(ctx, in_string, charset)
            out_obj = self.soap_handler.get_out_object(ctx, in_obj)
            out_string = self.soap_handler.get_out_string(ctx, out_obj)
            
            return out_string

        except Exception, e:

            fault = Fault(faultstring=str(e))
            resp = etree.tostring(fault, encoding=string_encoding)

            RESPONSE.setStatus('InternalServerError', reason=faultstring)
            RESPONSE.setHeader('Content-Type', 'text/xml')
            return resp
Exemplo n.º 11
0
            #return the order unique id
            logger.info("Backoffice: Returning async request for submit order")
            return new_order.id

    @soap(Integer, Integer, Auth, _returns=String)
    def getBudgetResponse(self, order, price, auth):
        if is_valid_request(auth):
            create_budget(auth.user_id, order, price)
            verify_and_finalize_order(order)

    @soap(Integer, String, Auth, _returns=String)
    def setStatusOrder(self, order, status, auth):
        if is_valid_request(auth):
            Notificator(order).notificate_frontend(status)
            return "OK"


if __name__ == "__main__":
    host = sys.argv[1]
    port = int(sys.argv[2])

    soap_application = Application([MusicService, OrderService], 'tns')
    wsgi_application = wsgi.Application(soap_application)
    server = make_server(host, port, wsgi_application)
    logger.info("Backoffice serving on %s:%s" % (
        host,
        port,
    ))
    server.serve_forever()
Exemplo n.º 12
0
 def test_multiple_ns(self):
     svc = Application([MultipleNamespaceService], 'tns')
     wsdl = svc.get_wsdl("URL")
Exemplo n.º 13
0
'''


class SleepingService(DefinitionBase):
    @soap(Integer, _is_async=True)
    def sleep(self, seconds):
        msgid, replyto = get_callback_info()

        def run():
            time.sleep(seconds)

            client = make_service_client(replyto, self)
            client.woke_up('good morning', msgid=msgid)

        Thread(target=run).start()

    @soap(String, _is_callback=True)
    def woke_up(self, message):
        pass


if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server
        soap_app = Application([SleepingService], 'tns')
        wsgi_app = wsgi.Application(soap_app)
        server = make_server('localhost', 7789, wsgi_app)
        server.serve_forever()
    except ImportError:
        print "Error: example server code requires Python >= 2.5"
Exemplo n.º 14
0
        return user_database[userid]

    @soap(User)
    def modify_user(self, user):
        global user_database

        user_database[user.userid] = user

    @soap(Integer)
    def delete_user(self, userid):
        global user_database

        del user_database[userid]

    @soap(_returns=Array(User))
    def list_users(self):
        global user_database

        return [v for k, v in user_database.items()]


if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server
        soap_app = Application([UserManager], 'tns')
        wsgi_app = wsgi.Application(soap_app)
        server = make_server('localhost', 7789, wsgi_app)
        server.serve_forever()
    except ImportError:
        print "Error: example server code requires Python >= 2.5"
Exemplo n.º 15
0
def build_app(service_list, tns, name):

    app = Application(service_list, tns, name)
    app.transport = 'http://schemas.xmlsoap.org/soap/http'
    return app
Exemplo n.º 16
0
computerid_seq = 1


class Computer(ClassModel):
    __namespace__ = "assets"
    assetid = Integer
    description = String


class ComputerManager(DefinitionBase):

    @soap(Computer, _returns=Computer)
    def add_computer(self, computer):
        global computer_database
        global computerid_seq

        computer.assetid = computerid_seq
        computerid_seq += 1

        computer_database[computer.assetid] = computer

        return  computer.assetid


if __name__ == "__main__":
    from wsgiref.simple_server import make_server
    soap_app = Application([ComputerManager, UserManager],tns="itServices")
    
    wsgi_app = wsgi.Application(soap_app)
    server = make_server("localhost", 7789, wsgi_app)
    server.serve_forever()
Exemplo n.º 17
0
    def __init__(self, services, tns):
        """Create Django view for given SOAP soaplib services and tns"""

        return super(DjangoSoapApp, self).__init__(Application(services, tns))
Exemplo n.º 18
0
 def as_view(cls):
     soap_application = Application([cls], __name__)
     return DjangoSoapApp(soap_application)
Exemplo n.º 19
0
    def form_valid(self, form):
        slug = form.cleaned_data['slug']

        return HttpResponseRedirect(
            reverse('list_order', args=[slug])
        )


class ListOrderView(DetailView):
    context_object_name = 'order'
    model = Order
    template_name = 'list_order.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ListOrderView, self).dispatch(*args, **kwargs)


class OrderStatusService(DefinitionBase):
    @soap(Integer, String, _returns=String)
    def changeStatusOrder(self, order, status):
        Order.objects.filter(slug=int(order)).update(status=status)
        return "OK"


orderstatus_service = DjangoSOAPAdaptor(
    Application(
        [OrderStatusService], 'tns'
    )
)
Exemplo n.º 20
0
def build_app(service_list, tns, name):

    app = Application(service_list, tns, name)
    app.transport = 'http://schemas.xmlsoap.org/soap/http'
    app.update_pref_map("Hippity", "Hippity")
    app.update_pref_map("Hoppity","Hoppity")
    app.update_pref_map("MissingRPCPortService","MissingRPCPortService")
    app.update_pref_map("SinglePortNS","SinglePortNS")
    app.update_pref_map("DoublePort","DoublePort")


    return app
Exemplo n.º 21
0
def consturct_soaplib_application(service_list, tns):
    soap_app = Application(service_list, tns)
    soap_app.transport = "http://schemas.xmlsoap.org/soap/http"
    return soap_app
Exemplo n.º 22
0
 def test_override_param_names(self):
     app = Application([TestService], 'tns')
     _wsdl = app.get_wsdl('')
     for n in ['self', 'import', 'return', 'from']:
         self.assertTrue(n in _wsdl, '"%s" not in _wsdl' % n)
Exemplo n.º 23
0
class SoapFolder(DefinitionBase):
    """Mix-In Class to Make a Folder into a SOAP Service Point

    Import this class into your Zope2 folder classes to make them SOAP-aware.
    Any methods in your folder class decorated with @soapmethod() will become
    callable over SOAP and the signature and docstring of that method will be
    reported as WSDL by a call to the index_html() method of that folder.

    Your class should also define a class attribute indicating the 'toplevel
    namespace' of your SOAP Service Point.  This name is arbitrary as far as
    this code goes, but appears in the SOAP response and the WSDL description
    generated.  This attribute looks like:   __tns__ = "PatientServices"
    """

    _v_soap_methods = None
    _v_cached_wsdl = None
    __wsdl__ = None

    def __init__(self, tns, environ=None):
        super(DefinitionBase, self).__init__(environ)
        self.soap_app = Application(self, tns, False)
        self.soap_handler = BaseServer(self.soap_app)

    def methods(self):
        """Returns a list of method descriptors for this object"""
        if self._v_soap_methods is None:
            self._v_soap_methods = self.build_public_methods()
        return self._v_soap_methods

    def service_description(self, REQUEST, RESPONSE):
        """ """

        if getattr(self, '__tns__', None) is None:
            self.__tns__ = self.get_tns(self.__class__)

        if self._v_soap_methods is None:
            self._v_soap_methods = self.build_public_methods()

        if self._v_cached_wsdl is None:
            self._v_cached_wsdl = self.soap_app.get_wsdl(self.absolute_url())
            self.__wsdl__ = None

        RESPONSE.setHeader('Content-Type', 'text/xml')
        return self._v_cached_wsdl

    def index_html(self, REQUEST, RESPONSE):
        """Handle an incoming SOAP request or a non-SOAP WSDL query."""

        if REQUEST.get('SOAPXML',
                       None) == None:  # Not a SOAP Request, return WSDL
            return self.service_description(REQUEST, RESPONSE)

        try:
            # Deserialize the Body of the SOAP Request
            from soaplib.core._base import _from_soap
            header, payload = _from_soap(REQUEST.SOAPXML)

            # TODO: At this point I need dispatch method calls to the soaplib.Application
            # somehow....... :)
            ctx = MethodContext()

            content_type = cgi.parse_header(REQUEST.get("Content-Type"))
            charset = content_type[1].get('charset', None)
            length = REQUEST.get("Content-Length")
            http_payload = REQUEST.read(int(length))

            if not charset:
                charset = "ascii"

            in_string = collapse_swa(content_type, http_payload)
            in_obj = self.soap_handler.get_in_object(ctx, in_string, charset)
            out_obj = self.soap_handler.get_out_object(ctx, in_obj)
            out_string = self.soap_handler.get_out_string(ctx, out_obj)

            return out_string

        except Exception, e:

            fault = Fault(faultstring=str(e))
            resp = etree.tostring(fault, encoding=string_encoding)

            RESPONSE.setStatus('InternalServerError', reason=faultstring)
            RESPONSE.setHeader('Content-Type', 'text/xml')
            return resp
Exemplo n.º 24
0
    print 'dm invoke ok!'

    resInfo = ResultInfo()
    resInfo.reqNo = reqNo
    resInfo.resMsg = rs[0]

    #print resInfo
    return resInfo


class TestService(DefinitionBase):  #WebService Method
    @soap(TestRequestInfo, _returns=ResultInfo)
    def getResultInfo(self, reqInfo):
        resInfo = ResultInfo()
        resInfo = exeRules(reqInfo)
        #print resInfo
        return resInfo


if __name__ == '__main__':
    try:
        print '服务已启动'
        from wsgiref.simple_server import make_server
        soap_application = Application([TestService], 'tns')
        wsgi_application = wsgi.Application(soap_application)
        server = make_server('localhost', 8899, wsgi_application)
        server.serve_forever()

    except ImportError:
        print 'error'
Exemplo n.º 25
0
def consturct_soaplib_application(service_list, tns):
    soap_app = Application(service_list, tns)
    soap_app.transport = "http://schemas.xmlsoap.org/soap/http"
    return soap_app
Exemplo n.º 26
0
 def __init__(self, tns, environ=None):
     super(DefinitionBase, self).__init__(environ)
     self.soap_app = Application(self, tns, False)
     self.soap_handler = BaseServer(self.soap_app)