예제 #1
0
    def run(self):
        dispatcher = SoapDispatcher(
            'op_adapter_soap_disp',
            location=self.address,
            action=self.address,
            namespace="http://smartylab.co.kr/products/op/adapter",
            prefix="tns",
            trace=True,
            ns=True)
        dispatcher.register_function('adapt',
                                     self.adapt,
                                     returns={'out': str},
                                     args={
                                         'nodeID': str,
                                         'resourceName': str,
                                         'duration': str,
                                         'options': str
                                     })
        print("Starting a SOAP server for adapter layer of OP...")
        httpd = HTTPServer(("", int(PORT_NUMBER)), SOAPHandler)
        httpd.dispatcher = dispatcher

        print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME,
                                                         PORT_NUMBER)
        httpd.serve_forever()
예제 #2
0
파일: soap.py 프로젝트: gwythaint/r4d
class R4DSoapService(object):
    def __init__(self, db):
        log.debug("R4DSoapService.__init__")
        self.__dispatcher = SoapDispatcher(
            'r4d',
            location="http://localhost:8008/",
            action='http://localhost:8008/',
            namespace="http://ci-rt.linutronix.de/r4d.wsdl",
            prefix="r4d",
            pretty=True,
            debug=True)
        self.db = db

    def soap(self, f, name=None, returns=None, args=None, doc=None):
        if not name:
            name = self.__name__
        self.__dispatcher.register_function(name,
                                            f,
                                            returns=returns,
                                            args=args,
                                            doc=doc)

    def server(self, listen, port):
        httpd = HTTPServer((listen, port), SOAPHandler)
        httpd.dispatcher = self.__dispatcher
        httpd.serve_forever()
예제 #3
0
	def run(self):
		address_port = self._address + ':{}/'.format(self._port)

		self._dispatcher = SoapDispatcher(
			name = 'GameCreator',
			location = address_port,
			action = address_port,
			namespace ='lost-world.dk',
			prefix = 'ns0',
			documentation = 'hm',
			trace = True,
			debug = True,
			ns = True,
		)

		self._dispatcher.register_function(
			'create_game',
			self.create_game,
			returns = {'ids': str},
			args = {'game_id': str, 'amount_players': int},
		)

		print("Starting SOAP server...")
		with HTTPServer((self._address, self._port), SOAPHandler) as http_server:
			http_server.dispatcher = self._dispatcher
			http_server.serve_forever()
예제 #4
0
class R4DSoapService (object):
    def __init__(self):
        log.debug ("R4DSoapService.__init__")
        self.__dispatcher = SoapDispatcher (
            'r4d',
            location = "http://localhost:8008/",
            action = 'http://localhost:8008/',
            namespace = "http://ci-rt.linutronix.de/r4d.wsdl",
            prefix="r4d",
            pretty = True,
            debug = log.level is logging.DEBUG)

    def soap (self, f, name = None, returns = None, args = None, doc = None):
        if not name:
            name = self.__name__
        self.__dispatcher.register_function (name, f,
                                             returns = returns,
                                             args = args, doc = doc)

        log.info(f"Added SOAP Service '{name}'")

    def server_start(self, listen, port, user, passwd):
        httpd = HTTPServer ((listen, port), partial(CustomSOAPHandler, auth=(user, passwd)))
        httpd.dispatcher = self.__dispatcher

        log.info("Server runs.")
        httpd.serve_forever ()
예제 #5
0
    def setUp(self):
        self.dispatcher = SoapDispatcher(
            name="PySimpleSoapSample",
            location="http://localhost:8008/",
            action='http://localhost:8008/',  # SOAPAction
            namespace="http://example.com/pysimplesoapsamle/",
            prefix="ns0",
            documentation='Example soap service using PySimpleSoap',
            debug=True,
            ns=True)

        self.dispatcher.register_function(
            'Adder',
            adder,
            returns={'AddResult': {
                'ab': int,
                'dd': str
            }},
            args={
                'p': {
                    'a': int,
                    'b': int
                },
                'dt': Date,
                'c': [{
                    'd': Decimal
                }]
            })

        self.dispatcher.register_function('Dummy',
                                          dummy,
                                          returns={'out0': str},
                                          args={'in0': str})

        self.dispatcher.register_function('Echo', echo)
예제 #6
0
 def run(self):
     dispatcher = SoapDispatcher('op_adapter_soap_disp', location = self.address, action = self.address,
             namespace = "http://smartylab.co.kr/products/op/adapter", prefix="tns", trace = True, ns = True)
     dispatcher.register_function('adapt', self.adapt, returns={'out': str},
             args={'nodeID': str, 'resourceName': str, 'duration': str, 'options': str})
     print("Starting a SOAP server for adapter layer of OP...")
     httpd = HTTPServer(("", 8008), SOAPHandler)
     httpd.dispatcher = dispatcher
     httpd.serve_forever()
예제 #7
0
 def __init__(self):
     log.debug ("R4DSoapService.__init__")
     self.__dispatcher = SoapDispatcher (
         'r4d',
         location = "http://localhost:8008/",
         action = 'http://localhost:8008/',
         namespace = "http://ci-rt.linutronix.de/r4d.wsdl",
         prefix="r4d",
         pretty = True,
         debug = log.level is logging.DEBUG)
예제 #8
0
파일: views.py 프로젝트: 08haozi/uliweb
 def soap(self):
     from pysimplesoap.server import SoapDispatcher
     import uliweb.contrib.soap as soap
     from uliweb.utils.common import import_attr
     from uliweb import application as app, response, url_for
     from functools import partial
     
     global __soap_dispatcher__
     
     if not __soap_dispatcher__:
         location = "%s://%s%s" % (
             request.environ['wsgi.url_scheme'],
             request.environ['HTTP_HOST'],
             request.path)
         namespace = functions.get_var(self.config).get('namespace') or location
         documentation = functions.get_var(self.config).get('documentation')
         dispatcher = SoapDispatcher(
             name = functions.get_var(self.config).get('name'),
             location = location,
             action = '', # SOAPAction
             namespace = namespace,
             prefix=functions.get_var(self.config).get('prefix'),
             documentation = documentation,
             exception_handler = partial(exception_handler, response=response),
             ns = True)
         for name, (func, returns, args, doc) in soap.__soap_functions__.get(self.config, {}).items():
             if isinstance(func, (str, unicode)):
                 func = import_attr(func)
             dispatcher.register_function(name, func, returns, args, doc)
     else:
         dispatcher = __soap_dispatcher__
         
     if 'wsdl' in request.GET:
         # Return Web Service Description
         response.headers['Content-Type'] = 'text/xml'
         response.write(dispatcher.wsdl())
         return response
     elif request.method == 'POST':
         def _call(func, args):
             rule = SimpleRule()
             rule.endpoint = func
             mod, handler_cls, handler = app.prepare_request(request, rule)
             result = app.call_view(mod, handler_cls, handler, request, response, _wrap_result, kwargs=args)
             r = _fix_soap_datatype(result)
             return r
         # Process normal Soap Operation
         response.headers['Content-Type'] = 'text/xml'
         log.debug("---request message---")
         log.debug(request.data)
         result = dispatcher.dispatch(request.data, call_function=_call)
         log.debug("---response message---")
         log.debug(result)
         response.write(result)
         return response
예제 #9
0
def main():
    dispatcher = SoapDispatcher(
        'my_dispatcher',
        location='http://'+host+':8888/',
        action='http://'+host+'8888/',
        namespace='http://security.com/security_sort.wsdl', prefix='ns0',trace=True,ns=True)
    dispatcher.register_function('Security', show_security, returns={'resp': unicode}, args={'datas': security()})
    handler = WSGISOAPHandler(dispatcher)
    wsgi_app = tornado.wsgi.WSGIContainer(handler)
    tornado_app = tornado.web.Application([('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)),])
    server = tornado.httpserver.HTTPServer(tornado_app)
    server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
예제 #10
0
    def test_multi_ns(self):
        dispatcher = SoapDispatcher(
            name="MTClientWS",
            location="http://localhost:8008/ws/MTClientWS",
            action='http://localhost:8008/ws/MTClientWS',  # SOAPAction
            namespace="http://external.mt.moboperator",
            prefix="external",
            documentation='moboperator MTClientWS',
            namespaces={
                'external': 'http://external.mt.moboperator',
                'model': 'http://model.common.mt.moboperator'
            },
            ns=True,
            pretty=False,
            debug=True)

        dispatcher.register_function('activateSubscriptions',
                                     self._multi_ns_func,
                                     returns=self._multi_ns_func.returns,
                                     args=self._multi_ns_func.args)
        dispatcher.register_function(
            'updateDeliveryStatus',
            self._updateDeliveryStatus,
            returns=self._updateDeliveryStatus.returns,
            args=self._updateDeliveryStatus.args)

        self.assertEqual(dispatcher.dispatch(REQ), MULTI_NS_RESP)
        self.assertEqual(dispatcher.dispatch(REQ1), MULTI_NS_RESP1)
예제 #11
0
    def setUpClass(cls):
        _, _, _, _, services = parse(os.path.abspath('tst/data/ne3s.wsdl'))
        service_name = 'NE3SOperationNotificationService'
        service = services[service_name]
        cls.response = {
            'managerRegistrationId': 'mgr',
            'managerRegistrationKey': 'ODYzNTQ0NTg0'
        }

        def handle_operation(**kwargs):
            return cls.response

        cls.dispatcher = SoapDispatcher(
            name='ut',
            location=
            'http://localhost:54321/services/NE3SOperationNotificationService',
            action='http://www.nokiasiemens.com/ne3s/1.0/',
            namespace='http://www.nokiasiemens.com/ne3s/1.0/',
            # namespaces={'ns': 'http://www.nokiasiemens.com/ne3s/1.0/',
            # 'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/'},
            documentation='NetAct simulator SOAP service',
            prefix='ns',
            debug=True)
        for port_name, port in service['ports'].iteritems():
            for operation_name, operation in port['operations'].iteritems():
                cls.dispatcher.register_function(
                    operation_name,
                    handle_operation,
                    returns=operation['output'].values()[0],
                    args=operation['input'].values()[0])
예제 #12
0
class ServerSoapFaultTest(unittest.TestCase):
    def setUp(self):
        self.dispatcher = SoapDispatcher('Test',
                                         action='http://localhost:8008/soap',
                                         location='http://localhost:8008/soap')

        def divider(a, b):
            if b == 0:
                raise SoapFault(faultcode='DivisionByZero',
                                faultstring='Division by zero not allowed',
                                detail='test')
            return float(a) / b

        self.dispatcher.register_function('Divider',
                                          divider,
                                          returns={'DivideResult': float},
                                          args={
                                              'a': int,
                                              'b': int
                                          })

    def test_exception(self):
        xml = """<?xml version="1.0" encoding="UTF-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
           <soap:Body>
             <Divider xmlns="http://example.com/sample.wsdl">
               <a>100</a><b>2</b>
            </Divider>
           </soap:Body>
        </soap:Envelope>"""
        response = SimpleXMLElement(self.dispatcher.dispatch(xml))
        self.assertEqual(str(response.DivideResult), '50.0')

        xml = """<?xml version="1.0" encoding="UTF-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
           <soap:Body>
             <Divider xmlns="http://example.com/sample.wsdl">
               <a>100</a><b>0</b>
            </Divider>
           </soap:Body>
        </soap:Envelope>"""
        response = SimpleXMLElement(self.dispatcher.dispatch(xml))
        body = getattr(getattr(response, 'soap:Body'), 'soap:Fault')
        self.assertIsNotNone(body)
        self.assertEqual(str(body.faultcode), 'Server.DivisionByZero')
        self.assertEqual(str(body.faultstring), 'Division by zero not allowed')
        self.assertEqual(str(body.detail), 'test')
예제 #13
0
def server_accepting_soap_requests():
    dispatcher = SoapDispatcher(
        name="WeatherServer",
        location="https://soapservice.christiansretsimpletestserver.xyz",
        action='',  # SOAPAction
        namespace="https://soapservice.christiansretsimpletestserver.xyz",
        prefix="ns0",
        trace=True,
        ns=True)
    dispatcher.register_function('CityWeatherReport',
                                 cityweatherreport,
                                 returns={'weather_report': str},
                                 args={'city_name': str})
    print('starting server')
    httpd = HTTPServer(("", 8050), SOAPHandler)
    httpd.dispatcher = dispatcher
    httpd.serve_forever()
예제 #14
0
 def test_multi_ns(self):
     dispatcher = SoapDispatcher(
         name = "MTClientWS",
         location = "http://localhost:8008/ws/MTClientWS",
         action = 'http://localhost:8008/ws/MTClientWS', # SOAPAction
         namespace = "http://external.mt.moboperator", prefix="external",
         documentation = 'moboperator MTClientWS',
         namespaces = {
             'external': 'http://external.mt.moboperator', 
             'model': 'http://model.common.mt.moboperator'
         },
         ns = True,
         pretty=False,
         debug=True)
     
     dispatcher.register_function('activateSubscriptions', 
         self._multi_ns_func,
         returns=self._multi_ns_func.returns,
         args=self._multi_ns_func.args)
     dispatcher.register_function('updateDeliveryStatus',
         self._updateDeliveryStatus,
         returns=self._updateDeliveryStatus.returns,
         args=self._updateDeliveryStatus.args)
     
     self.assertEqual(dispatcher.dispatch(REQ), MULTI_NS_RESP)
     self.assertEqual(dispatcher.dispatch(REQ1), MULTI_NS_RESP1)
예제 #15
0
class SoapThread(threading.Thread):

	def __init__(self, game_manager: GameManager, address: str, port: int):
		super().__init__()
		self._address = address
		self._port = port
		self._dispatcher = None #type: SoapDispatcher
		self._game_manager = game_manager #type: GameManager

	def create_game(self, game_id: str, amount_players: int = 1) -> t.Optional[str]:
		try:
			ids = self._game_manager.create_game(game_id, SetupInfo(num_players=amount_players))
			print(ids)
			return ','.join(ids)
		except CreateGameException:
			pass

	def run(self):
		address_port = self._address + ':{}/'.format(self._port)

		self._dispatcher = SoapDispatcher(
			name = 'GameCreator',
			location = address_port,
			action = address_port,
			namespace ='lost-world.dk',
			prefix = 'ns0',
			documentation = 'hm',
			trace = True,
			debug = True,
			ns = True,
		)

		self._dispatcher.register_function(
			'create_game',
			self.create_game,
			returns = {'ids': str},
			args = {'game_id': str, 'amount_players': int},
		)

		print("Starting SOAP server...")
		with HTTPServer((self._address, self._port), SOAPHandler) as http_server:
			http_server.dispatcher = self._dispatcher
			http_server.serve_forever()
예제 #16
0
    def setUp(self):
        self.dispatcher = SoapDispatcher('Test',
                                         action='http://localhost:8008/soap',
                                         location='http://localhost:8008/soap')

        def divider(a, b):
            if b == 0:
                raise SoapFault(faultcode='DivisionByZero',
                                faultstring='Division by zero not allowed',
                                detail='test')
            return float(a) / b

        self.dispatcher.register_function('Divider',
                                          divider,
                                          returns={'DivideResult': float},
                                          args={
                                              'a': int,
                                              'b': int
                                          })
예제 #17
0
    def setUp(self):
        self.disp = SoapDispatcher(
            name="PySimpleSoapSample",
            location="http://localhost:8008/",
            action='http://localhost:8008/',  # SOAPAction
            namespace="http://example.com/pysimplesoapsamle/", prefix="ns0",
            documentation='Example soap service using PySimpleSoap',
            debug=True,
            ns=True)

        self.disp.register_function('dummy', dummy,
                                    returns={'out0': str},
                                    args={'in0': str}
                                    )
        self.disp.register_function('dummy_response_element', dummy,
                                    returns={'out0': str},
                                    args={'in0': str},
                                    response_element_name='diffRespElemName'
                                    )
예제 #18
0
 def test_single_ns(self):
     dispatcher = SoapDispatcher(
         name = "MTClientWS",
         location = "http://localhost:8008/ws/MTClientWS",
         action = 'http://localhost:8008/ws/MTClientWS', # SOAPAction
         namespace = "http://external.mt.moboperator", prefix="external",
         documentation = 'moboperator MTClientWS',
         ns = True,
         pretty=False,
         debug=True)
     
     dispatcher.register_function('activateSubscriptions', 
         self._single_ns_func,
         returns=self._single_ns_func.returns,
         args=self._single_ns_func.args)
     
     # I don't fully know if that is a valid response for a given request,
     # but I tested it, to be sure that a multi namespace function
     # doesn't brake anything.
     self.assertEqual(dispatcher.dispatch(REQ), SINGLE_NS_RESP)
예제 #19
0
def init_service(port, servicename, userfunction, args, returns):
    # define service
    dispatcher = SoapDispatcher(
        servicename,
        location="http://localhost:%d/" % (port,),
        action="http://localhost:%d/" % (port,),  # SOAPAction
        namespace="http://example.com/%s.wsdl" % (servicename,),
        prefix="ns0",
        trace=True,
        ns=True,
    )

    # register the user function
    dispatcher.register_function(servicename, userfunction, returns=returns, args=args)

    # start service
    print("Starting server '%s' on port %i ..." % (servicename, port))
    httpd = HTTPServer(("", port), SOAPHandler)
    httpd.dispatcher = dispatcher
    httpd.serve_forever()
예제 #20
0
    def test_single_ns(self):
        dispatcher = SoapDispatcher(
            name="MTClientWS",
            location="http://localhost:8008/ws/MTClientWS",
            action='http://localhost:8008/ws/MTClientWS',  # SOAPAction
            namespace="http://external.mt.moboperator",
            prefix="external",
            documentation='moboperator MTClientWS',
            ns=True,
            pretty=False,
            debug=True)

        dispatcher.register_function('activateSubscriptions',
                                     self._single_ns_func,
                                     returns=self._single_ns_func.returns,
                                     args=self._single_ns_func.args)

        # I don't fully know if that is a valid response for a given request,
        # but I tested it, to be sure that a multi namespace function
        # doesn't brake anything.
        self.assertEqual(dispatcher.dispatch(REQ), SINGLE_NS_RESP)
예제 #21
0
def main():
    dispatcher = SoapDispatcher(
        'my_dispatcher',
        location='http://' + host + ':8888/',
        action='http://' + host + '8888/',
        namespace='http://security.com/security_sort.wsdl',
        prefix='ns0',
        trace=True,
        ns=True)
    dispatcher.register_function('Security',
                                 show_security,
                                 returns={'resp': unicode},
                                 args={'datas': security()})
    handler = WSGISOAPHandler(dispatcher)
    wsgi_app = tornado.wsgi.WSGIContainer(handler)
    tornado_app = tornado.web.Application([
        ('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)),
    ])
    server = tornado.httpserver.HTTPServer(tornado_app)
    server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
예제 #22
0
class TestSoapDispatcher(unittest.TestCase):
    def setUp(self):
        self.disp = SoapDispatcher(
            name="PySimpleSoapSample",
            location="http://localhost:8008/",
            action='http://localhost:8008/',  # SOAPAction
            namespace="http://example.com/pysimplesoapsamle/", prefix="ns0",
            documentation='Example soap service using PySimpleSoap',
            debug=True,
            ns=True)

        self.disp.register_function('dummy', dummy,
                                    returns={'out0': str},
                                    args={'in0': str}
                                    )
        self.disp.register_function('dummy_response_element', dummy,
                                    returns={'out0': str},
                                    args={'in0': str},
                                    response_element_name='diffRespElemName'
                                    )

    def test_zero(self):
        response = """<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><dummyResponse xmlns="http://example.com/pysimplesoapsamle/"><out0>Hello world</out0></dummyResponse></soap:Body></soap:Envelope>"""

        request = """\
<?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <soap:Body>
         <dummy xmlns="http://example.com/sample.wsdl">
           <in0 xsi:type="xsd:string">Hello world</in0>
        </dummy>
       </soap:Body>
    </soap:Envelope>"""
        self.assertEqual(self.disp.dispatch(request), response)

    def test_response_element_name(self):
        response = """<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><diffRespElemName xmlns="http://example.com/pysimplesoapsamle/"><out0>Hello world</out0></diffRespElemName></soap:Body></soap:Envelope>"""

        request = """\
<?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <soap:Body>
         <dummy_response_element xmlns="http://example.com/sample.wsdl">
           <in0 xsi:type="xsd:string">Hello world</in0>
        </dummy_response_element>
       </soap:Body>
    </soap:Envelope>"""
        self.assertEqual(self.disp.dispatch(request), response)
예제 #23
0
class SoapView(View):
    SOAP = SoapDispatcher(name="test",
                          action="http://127.0.0.1:8000/soap/",
                          location="http://127.0.0.1:8000/soap/",
                          namespace="namespace",
                          soap_ns="xs",
                          prefix="pys")
    NAME = None
    RESAULT = None
    NS = None
    ARG = None
    URL_KW = {}

    def dispatch(self, *args, **kwargs):
        # pdb.set_trace()
        request = args[0]
        location = request.META.get("HTTP_SOAPACTION", None)
        if self.NAME:
            self.SOAP.name = self.NAME
        if self.NS:
            self.SOAP.soap_ns = self.NS
        for k, v in kwargs.items():
            self.URL_KW[k] = v
        if location:
            self.SOAP.action = location
            self.SOAP.location = location

        self.SOAP.register_function("test",
                                    self.soap,
                                    self.RESAULT,
                                    args=self.ARG)
        return super(SoapView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        return HttpResponse(self.SOAP.wsdl(), content_type="text/xml")

    def post(self, request, *a, **kw):
        xml = self.SOAP.dispatch(request.body, fault={})
        return HttpResponse(xml, content_type="text/xml")

    @abstractmethod
    def soap(self, *a, **kw):
        pass
예제 #24
0
    def setUp(self):
        self.dispatcher = SoapDispatcher(
            name="PySimpleSoapSample",
            location="http://localhost:8008/",
            action='http://localhost:8008/',  # SOAPAction
            namespace="http://example.com/pysimplesoapsamle/", prefix="ns0",
            documentation='Example soap service using PySimpleSoap',
            debug=True,
            ns=True)

        self.dispatcher.register_function('Adder', adder,
            returns={'AddResult': {'ab': int, 'dd': str}},
            args={'p': {'a': int, 'b': int}, 'dt': Date, 'c': [{'d': Decimal}]})

        self.dispatcher.register_function('Dummy', dummy,
            returns={'out0': str},
            args={'in0': str})

        self.dispatcher.register_function('Echo', echo)
예제 #25
0
def get_wsapplication():
    dispatcher = SoapDispatcher(
        'thunder_counter_dispatcher',
        location=str(gConfig['webservice']['location']),
        action=str(gConfig['webservice']['action']),
        namespace=str(gConfig['webservice']['namespace']),
        prefix=str(gConfig['webservice']['prefix']),
        trace=True,
        ns=True)
    dispatcher.register_function('login',
                                 webservice_login,
                                 returns={'Result': str},
                                 args={
                                     'username': str,
                                     'password': str
                                 })
    dispatcher.register_function('GetFlashofDate',
                                 webservice_GetFlashofDate,
                                 returns={'Result': str},
                                 args={
                                     'in0': str,
                                     'in1': str
                                 })
    dispatcher.register_function('GetFlashofEnvelope',
                                 webservice_GetFlashofEnvelope,
                                 returns={'Result': str},
                                 args={
                                     'in0': str,
                                     'in1': str,
                                     'in2': str,
                                     'in3': str,
                                     'in4': str,
                                     'in5': str
                                 })
    wsapplication = WSGISOAPHandler(dispatcher)
    return wsapplication
예제 #26
0
def get_wsapplication():
    dispatcher = SoapDispatcher(
        'thunder_counter_dispatcher',
        location = str(gConfig['webservice']['location']),
        action = str(gConfig['webservice']['action']),
        namespace = str(gConfig['webservice']['namespace']), 
        prefix = str(gConfig['webservice']['prefix']),
        trace = True,
        ns = True)
    dispatcher.register_function('login', 
                                 webservice_login,
                                 returns={'Result': str}, 
                                 args={'username': str, 'password': str})    
    dispatcher.register_function('GetFlashofDate', 
                                 webservice_GetFlashofDate,
                                 returns={'Result': str}, 
                                 args={'in0': str, 'in1': str})    
    dispatcher.register_function('GetFlashofEnvelope', 
                                 webservice_GetFlashofEnvelope,
                                 returns={'Result': str}, 
                                 args={'in0': str, 'in1': str, 'in2': str,'in3': str, 'in4': str, 'in5': str})    
    wsapplication = WSGISOAPHandler(dispatcher)
    return wsapplication
예제 #27
0
from pysimplesoap.server import SoapDispatcher, SOAPHandler, WSGISOAPHandler
import logging
import const
from BaseHTTPServer import HTTPServer
dispatcher = SoapDispatcher(
'TransServer',
location = "http://%s:8050/" % const.TARGET_IP,
action = 'http://%s:8050/' % const.TARGET_IP, # SOAPAction
namespace = "http://example.com/sample.wsdl", prefix="ns0",
trace = True,
ns = True)

def on():
    return "on"
def off():
    return "off"

def status():
    return "1024"

# register the user function

dispatcher.register_function('on', on,
    args={},
    returns={'result': str} 
    )

dispatcher.register_function('off', off,
    args={},
    returns={'result': str} 
    )
예제 #28
0
def adder(a,b):
    "Add two values"
    return a+b

def multiplier(a,b):
    "Multiply two values"
    return a*b

#######################


dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8080/",
    action = 'http://localhost:8080/', # SOAPAction
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)

# register the user function
dispatcher.register_function('Adder', adder,
    returns={'AddResult': int}, 
    args={'a': int,'b': int},
    doc = 'Add two values...')

dispatcher.register_function('Multiplier', multiplier,
    returns={'MultResult': int}, 
    args={'a': int,'b': int},
    doc = 'Multiply two values...')
예제 #29
0
def get_tasks():
    print "###MESSAGE START###"

    #pass
    #print "ping: "+str(args)
    logging.warning("getTasks.")
    print "###MESSAGE END###"

    return list


dispatcher = SoapDispatcher(
    'server',
    location=
    "http://ppm-sanger-dev.dipr.partners.org:8080/gp/services/Analysis",
    action=('submitJob', 'ping', 'getTasks'),  # SOAPAction
    trace=True,
    ns=False)
'''	#namespace = "http://ppm-sanger-dev.dipr.partners.org:8080/gp/services/Analysis?wsdl",
	namespace = "http://hive49-206.dipr.partners.org:8080/gp/services/Analysis?wsdl",'''

# register submitJob
#dispatcher.register_function('submitJob', echo,
#	returns={'response': dict},
#	args={'request': dict})

# register submitJob
dispatcher.register_function('submitJob',
                             submit,
                             returns={'submitJobResponse': list},
예제 #30
0
def subtractor(a,b):
    "Subtract two numbers"
    return a-b

def multiplier(a,b):
    "Multiply two numbers"
    return a*b

def divider(a,b):
    "Divide two numbers"
    return float(a/b)

dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8008/",
    action = 'http://localhost:8008/',
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)

# register the user functions
dispatcher.register_function('Add', adder,
    returns={'AddResult': int}, 
    args={'a': int,'b': int})

dispatcher.register_function('Sub', subtractor,
    returns={'SubResult': int},
    args={'a': int,'b': int})

dispatcher.register_function('Mul', multiplier,
    returns={'MulResult': int},
예제 #31
0
		#print(xmlElm.children())
		#img = xmlElm.unmarshall({'img':array.array})
		print(img)
		with open("out\\" + name, 'wb') as f2:
			img.tofile(f2)
	except Exception as e:
		print e
	return 0

# If the program is run directly or passed as an argument to the python
# interpreter then create a server instance and show window
if __name__ == "__main__":
	dispatcher = SoapDispatcher(
		'my_dispatcher',
		location = "http://localhost:8008/",
		action = 'http://localhost:8008/', # SOAPAction
		namespace = "http://example.com/sample.wsdl", prefix="ns0",
		trace = True,
		ns = True)

	# register the user function
	dispatcher.register_function('uploadImages', uploadImages, 
		returns={'Result': int},
			args={'imgs_str': str})

	dispatcher.register_function('uploadImage', uploadImage, 
		returns={'Result': int},
			args={'name': str, 'imgstr': str})

	dispatcher.register_function('uploadConfigAndImages', uploadConfigAndImages, 
		returns={'Result': int},
예제 #32
0
        "-r", folder, "-d /data/uniprot_sprot", "-c"
    ])
    subprocess.call(shellCmd, shell=True)
    outFile = folder + "/out/" + list(os.listdir(folder + "/out"))[0]
    shellCmd = " ".join(
        ["./disulfxml", "-i", outFile, "-o", folder + "/sequence.xml"])
    subprocess.call(shellCmd, shell=True)
    with open(folder + "/sequence.xml") as f:
        out = f.read()
    return out


dispatcher = SoapDispatcher(
    'my_dispatcher',
    location="http://localhost:8008/",
    action='http://localhost:8008/',  # SOAPAction
    namespace="http://alex.tbl/webservice/disulfinder/disulfinder_soap.wsdl",
    prefix="di",
    trace=True,
    ns=True)

# register the user function
dispatcher.register_function('GetDsBonds',
                             getDsBonds,
                             returns={'getDisulfinderResponse': str},
                             args={'getDisulfinderRequest': str})

print "Starting server..."
httpd = HTTPServer(("", 8008), SOAPHandler)
httpd.dispatcher = dispatcher
httpd.serve_forever()
    result_matrix = [0] * (first_matrix_height*second_matrix_width)

    for _ in itertools.repeat(None, len(result_matrix)):
        index, res = receiveResult()
        result_matrix[index] = res

    print "%s seconds" % (time.time() - start_time)

    return {'result_matrix': result_matrix, 'result_matrix_width': second_matrix_width,
        'result_matrix_height': first_matrix_height}

dispatcher = SoapDispatcher(
    'multiplyMatrix',
    location = "http://localhost:%d/" % SERVER_PORT,
    action   = "http://localhost:%d/" % SERVER_PORT,
    trace    = True,
    ns       = True
)

dispatcher.register_function(
    'multiplyMatrix',
    multiplyMatrix,
    returns = { 'result_matrix': [int], 'result_matrix_width': int, 'result_matrix_height': int },
    args    = { 'first_matrix':  [int], 'first_matrix_width':  int, 'first_matrix_height':  int,
                'second_matrix': [int], 'second_matrix_width': int, 'second_matrix_height': int }
)

httpd = HTTPServer(("", SERVER_PORT), SOAPHandler)
httpd.dispatcher = dispatcher
예제 #34
0
from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import HTTPServer

def adder(a,b):
    "Add two values"
    return a+b

dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8008/",
    action = 'http://localhost:8008/', # SOAPAction
    namespace = "http://localhost/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)

# register the user function
dispatcher.register_function('Adder', adder,
    returns={'AddResult': int}, 
    args={'a': int,'b': int})

print "Starting server..."
httpd = HTTPServer(("", 8008), SOAPHandler)
httpd.dispatcher = dispatcher
httpd.serve_forever()
예제 #35
0
from BaseHTTPServer import HTTPServer
import os.path
import imp
from subprocess import Popen, PIPE, STDOUT,call 

def adder(a):
    if a == '1':
        if os.path.exists('/home/samara/Documentos/TG/TG-Background/Code/run_finger.py'):
            p = Popen(["python","/home/samara/Documentos/TG/TG-Background/Code/teste.py"], stdout=PIPE).communicate()[0]
            return p
        return 'NOT'
    return 'NOT'

dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8008/",
    action = 'http://localhost:8008/', # SOAPAction
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)

# register the user function
dispatcher.register_function('Adder', adder,
    returns={'result': str}, 
    args={'a': str})

print "Starting server..."
httpd = HTTPServer(("", 8008), SOAPHandler)
httpd.dispatcher = dispatcher
httpd.serve_forever()
예제 #36
0
class TestSoapDispatcher(unittest.TestCase):
    def eq(self, value, expectation, msg=None):
        if msg is not None:
            msg += ' %s' % value
            self.assertEqual(value, expectation, msg)
        else:
            self.assertEqual(value, expectation,
                             "%s\n---\n%s" % (value, expectation))

    def setUp(self):
        self.dispatcher = SoapDispatcher(
            name="PySimpleSoapSample",
            location="http://localhost:8008/",
            action='http://localhost:8008/',  # SOAPAction
            namespace="http://example.com/pysimplesoapsamle/",
            prefix="ns0",
            documentation='Example soap service using PySimpleSoap',
            debug=True,
            ns=True)

        self.dispatcher.register_function(
            'Adder',
            adder,
            returns={'AddResult': {
                'ab': int,
                'dd': str
            }},
            args={
                'p': {
                    'a': int,
                    'b': int
                },
                'dt': Date,
                'c': [{
                    'd': Decimal
                }]
            })

        self.dispatcher.register_function('Dummy',
                                          dummy,
                                          returns={'out0': str},
                                          args={'in0': str})

        self.dispatcher.register_function('Echo', echo)

    def test_classic_dialect(self):
        # adder local test (clasic soap dialect)
        resp = """<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><AdderResponse xmlns="http://example.com/pysimplesoapsamle/"><dd>5000000.3</dd><ab>3</ab><dt>2011-07-24</dt></AdderResponse></soap:Body></soap:Envelope>"""
        xml = """<?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
       <soap:Body>
         <Adder xmlns="http://example.com/sample.wsdl">
           <p><a>1</a><b>2</b></p><c><d>5000000.1</d><d>.2</d></c><dt>2010-07-24</dt>
        </Adder>
       </soap:Body>
    </soap:Envelope>"""
        self.eq(self.dispatcher.dispatch(xml), resp)

    def test_modern_dialect(self):
        # adder local test (modern soap dialect, SoapUI)
        resp = """<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:pys="http://example.com/pysimplesoapsamle/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><pys:AdderResponse><dd>15.021</dd><ab>12</ab><dt>1970-07-20</dt></pys:AdderResponse></soapenv:Body></soapenv:Envelope>"""
        xml = """
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pys="http://example.com/pysimplesoapsamle/">
   <soapenv:Header/>
   <soapenv:Body>
      <pys:Adder>
         <pys:p><pys:a>9</pys:a><pys:b>3</pys:b></pys:p>
         <pys:dt>1969-07-20<!--1969-07-20T21:28:00--></pys:dt>
         <pys:c><pys:d>10.001</pys:d><pys:d>5.02</pys:d></pys:c>
      </pys:Adder>
   </soapenv:Body>
</soapenv:Envelope>
    """
        self.eq(self.dispatcher.dispatch(xml), resp)

    def test_echo(self):
        # echo local test (generic soap service)
        resp = """<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><EchoResponse xmlns="http://example.com/pysimplesoapsamle/"><value xsi:type="xsd:string">Hello world</value></EchoResponse></soap:Body></soap:Envelope>"""
        xml = """<?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <soap:Body>
         <Echo xmlns="http://example.com/sample.wsdl">
           <value xsi:type="xsd:string">Hello world</value>
        </Echo>
       </soap:Body>
    </soap:Envelope>"""
        self.eq(self.dispatcher.dispatch(xml), resp)
예제 #37
0
파일: hue.py 프로젝트: athasach/sonoshue
from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import HTTPServer
from phue import Bridge
import os
import sys
import socket

dispatcher = SoapDispatcher('hue',
                            location="http://localhost:8080/",
                            namespace="http://www.sonos.com/Services/1.1",
                            trace=True,
                            debug=True)

lightActions = {
    'on': {
        'on': True
    },
    'off': {
        'on': False
    },
    'dim': {
        'on': True,
        'bri': 127
    },
    'red': {
        'on': True,
        'bri': 254,
        'hue': 0,
        'sat': 255
    },
    'green': {
예제 #38
0
def adder(a,b):
    "Add two values"
    return a+b

def hello(name):
	return "Hello {0}".format(name)


def list_individuos(name):
	return ["Eduardo", u"Fábio", "Teste"]


dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8008/",
    action = 'http://localhost:8008/', # SOAPAction
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)

# register the user function
dispatcher.register_function('Adder', adder,
    returns={'AddResult': int}, 
    args={'a': int,'b': int})


dispatcher.register_function('Hello', hello,
    returns={'Hello': str}, 
    args={'name': str})

예제 #39
0
        return diff

    def multiply(self, a,b):
        product = a*b
        return product

    def divide(self, a,b):
        if b != 0:
            quote = a/b
            return quote
        else:
            return "cannot divide by zero"



dispatcher = SoapDispatcher(
    'my_dispatcher',
    location="http://localhost:8008/",
    action='http://localhost:8008/', # SOAPAction
    namespace="http://example.com/sample.wsdl", prefix="ns0",
    trace=True,
    ns=True)

dispatcher.register_function('sum', Calculator().add, returns={'Result': int}, args={'a': int, 'b': int})
dispatcher.register_function('difference', Calculator().subtract, returns={'Result': int}, args={'a': int, 'b': int})
dispatcher.register_function('product', Calculator().multiply, returns={'Result': int}, args={'a': int, 'b': int})
dispatcher.register_function('quote', Calculator().divide, returns={'Result': int}, args={'a': int, 'b': int})

httpd = HTTPServer(("", 8008), SOAPHandler)
httpd.dispatcher = dispatcher
httpd.serve_forever()
from pysimplesoap.server import SoapDispatcher, WSGISOAPHandler

dispatcher = SoapDispatcher(
    name="PySimpleSoapSample",
    location="http://localhost:9100/",
    action='http://localhost:9100/',  # SOAPAction
    namespace="http://example.com/pysimplesoapsamle/",
    prefix="ns0",
    documentation='Example soap service using PySimpleSoap',
    trace=True,
    debug=True,
    ns=True)


# これをやっても、以下のエラーが出る
# AttributeError: 'str' object has no attribute 'decode'
class WSGISOAPPython3Handler(WSGISOAPHandler):
    def do_post(self, environ, start_response):
        length = int(environ['CONTENT_LENGTH'])
        request = environ['wsgi.input'].read(length)
        response = self.dispatcher.dispatch(str(request))
        start_response('200 OK', [('Content-Type', 'text/xml'),
                                  ('Content-Length', str(len(response)))])
        return [response]


def say_hello(RequestInterface):
    return RequestInterface.userName


dispatcher.register_function(
예제 #41
0
    def _start_soap_server(self):
        """
        To launch a SOAP server for the adapter
        :return:
        """
        dispatcher = SoapDispatcher('concert_adapter_soap_server', location = SOAP_SERVER_ADDRESS, action = SOAP_SERVER_ADDRESS,
                namespace = "http://smartylab.co.kr/products/op/adapter", prefix="tns", ns = True)

        # To register a method for LinkGraph Service Invocation
        dispatcher.register_function('invoke_adapter', self.receive_service_invocation, returns={'out': str},
            args={
                'LinkGraph': {
                    'name': str,
                    'nodes': [{
                        'Node': {
                            'id': str,
                            'uri': str,
                            'min': int,
                            'max': int,
                            'parameters': [{
                                'parameter': {
                                    'message': str,
                                    'frequency': int
                                }
                            }]
                        }
                    }],
                    'topics': [{
                        'Topic': {
                            'id': str,
                            'type': str
                        }
                    }],
                    'actions': [{
                        'Action': {
                            'id': str,           # action id
                            'type': str,         # action specification
                            'goal_type': str     # goal message type
                        }
                    }],
                    'services': [{
                        'Service': {
                            'id': str,          # service id
                            'type': str,        # service class
                            'persistency': str  # persistency
                        }
                    }],
                    'edges': [{
                        'Edge': {
                            'start': str,
                            'finish': str,
                            'remap_from': str,
                            'remap_to': str
                        }
                    }],
                    'methods': [{
                        'Method': {
                            'address': str,
                            'namespace': str,
                            'name': str,
                            'return_name': str,
                            'param': str
                        }
                    }]
                }
            }
        )

        # To register a method for Single Node Service Invocation
        dispatcher.register_function('send_topic_msg', self._send_topic_msg, returns={'out': str},
            args={
                'namespace': str,
                'message_val': str
            }
        )

        # To register a method for sending Action messages
        dispatcher.register_function('send_action_msg', self._send_action_msg, returns={'out': str},
            args={
                'namespace': str,
                'message_val': str
            }
        )


        # To register a method for sending Service messages
        dispatcher.register_function('send_service_msg', self._send_service_msg, returns={'out': str},
            args={
                'namespace': str,
                'message_val': str
            }
        )


        # To register a method for Releasing Allocated Resources
        dispatcher.register_function('release_allocated_resources', self.release_allocated_resources, returns={'out': bool}, args={})

        # To create SOAP Server
        rospy.loginfo("Starting a SOAP server...")
        self.httpd = HTTPServer(("", int(SOAP_SERVER_PORT)), SOAPHandler)
        self.httpd.dispatcher = dispatcher

        # To execute SOAP Server
        rospy.loginfo("The SOAP server started. [%s:%s]" % (SOAP_SERVER_ADDRESS, SOAP_SERVER_PORT))
        self.httpd.serve_forever()
예제 #42
0
from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import HTTPServer
from ServerOperations import ServOperation


def adder(a, b):
    "Add two values"
    return a + b


dispatcher = SoapDispatcher(
    'my_dispatcher',
    location="http://localhost:8000/",
    action='http://localhost:8000/',  # SOAPAction
    namespace="http://example.com/sample.wsdl",
    prefix="ns0",
    trace=True,
    ns=True)

# register the user function
dispatcher.register_function('Adder',
                             adder,
                             returns={'AdderResult': int},
                             args={
                                 'a': int,
                                 'b': int
                             })

Operation = ServOperation()
dispatcher.register_function(
    'Show',
예제 #43
0
파일: core.py 프로젝트: kn1m/Lab3-AK
from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import HTTPServer
from operations import create, read, update, delete

dispatcher = SoapDispatcher(
    'my_dispatcher',
    location="http://localhost:8008/",
    action='http://localhost:8008/',  # SOAPAction
    namespace="http://example.com/sample.wsdl", prefix="ns0",
    trace=True,
    ns=True)

# register the user functions
dispatcher.register_function('Create', create,
    returns={'Node': str},
    args={'doc_name': str, 'doc_content': str})

dispatcher.register_function('Read', read,
    returns={'Node': str},
    args={'doc_name': str})

dispatcher.register_function('Update', update,
    returns={'Node': str},
    args={'doc_name': str, 'doc_content': str})

dispatcher.register_function('Delete', delete,
    returns={'Node': str},
    args={'doc_name': str})

print "Starting server at 8008..."
def store_resume_on_server(uploaded_file_name=None, uploaded_file_value=None):

    tmp_folder_path = ConfigReader.TemporaryFileLoad
    path = os.path.join(tmp_folder_path, (uploaded_file_name).replace(
        " ", "").replace("(", "").replace(")", ""))
    fp = open(path, 'wb')
    data = uploaded_file_value
    fp.write(data.decode("base64"))
    fp.close()
    return path


dispatcher = SoapDispatcher(
    'my_dispatcher',
    location="http://localhost:9001/",
    action='http://localhost:9001/',  # SOAPAction
    namespace="http://example.com/sample.wsdl",
    prefix="ns0",
    # trace = True,
    ns=True)

dispatcher.register_function('ConverttoHtml',
                             ResumeToHtml,
                             returns={'path': str},
                             args={
                                 'uploaded_file_name': str,
                                 'uploaded_file_value': str
                             })

print "Starting server..."
httpd = HTTPServer(("", 9001), SOAPHandler)
httpd.dispatcher = dispatcher
예제 #45
0
        raise Exception("No FX Rates for currency") 
    fxRate = fxtable[destCurr]
    if recipricol:
        fxRate = 1 / fxRate
    return {'buy': fxRate,'sell':fxRate}

def getFXRate(cur1,cur2):
    "Get FX from cur1 to cur2"
    #return {'FXResult':{'buy':"0.1324", 'sell':"0.1555"}}
    return {'FXResult':currencyLookup(cur1,cur2)}
    #return "0.2425"

dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8008/",
    action = 'http://localhost:8008/', # SOAPAction
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)

# register the user function
dispatcher.register_function('GetFXRate', getFXRate,
    returns={'FXResult': {'buy': str, 'sell': str}}, 
    #returns={'FXResult': str}, 
    args={'cur1': str,'cur2': str})

def startServer():
    print("Starting server on port 8008...")
    httpd = HTTPServer(("", 8008), SOAPHandler)
    httpd.dispatcher = dispatcher
    httpd.serve_forever()
예제 #46
0
    if number == 9:
        username =  getpass.getuser()
        return str(username)

    # Last value
    return None

# ---------------------------------------------------------

# do not change anything unless you know what you're doing.
port=8008
dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8008/",
    action = 'http://localhost:8008/', # SOAPAction
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)

# do not change anything unless you know what you're doing.
dispatcher.register_function('get_value', get_value,
    returns={'resultaat': str},   # return data type
    args={'number': int}         # it seems that an argument is mandatory, although not needed as input for this function: therefore a dummy argument is supplied but not used.
    )

# Let this agent listen forever, do not change anything unless needed.
print "Starting server on port",port,"..."
httpd = HTTPServer(("", port), SOAPHandler)
httpd.dispatcher = dispatcher
httpd.serve_forever()
예제 #47
0
class TestSoapDispatcher(unittest.TestCase):
    def eq(self, value, expectation, msg=None):
        if msg is not None:
            msg += ' %s' % value
            self.assertEqual(value, expectation, msg)
        else:
            self.assertEqual(value, expectation, "%s\n---\n%s" % (value, expectation))

    def setUp(self):
        self.dispatcher = SoapDispatcher(
            name="PySimpleSoapSample",
            location="http://localhost:8008/",
            action='http://localhost:8008/',  # SOAPAction
            namespace="http://example.com/pysimplesoapsamle/", prefix="ns0",
            documentation='Example soap service using PySimpleSoap',
            debug=True,
            ns=True)

        self.dispatcher.register_function('Adder', adder,
            returns={'AddResult': {'ab': int, 'dd': str}},
            args={'p': {'a': int, 'b': int}, 'dt': Date, 'c': [{'d': Decimal}]})

        self.dispatcher.register_function('Dummy', dummy,
            returns={'out0': str},
            args={'in0': str})

        self.dispatcher.register_function('Echo', echo)

    def test_classic_dialect(self):
        # adder local test (classic soap dialect)
        resp = """<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><AdderResponse xmlns="http://example.com/pysimplesoapsamle/"><dd>5000000.3</dd><ab>3</ab><dt>2011-07-24</dt></AdderResponse></soap:Body></soap:Envelope>"""
        xml = """<?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
       <soap:Body>
         <Adder xmlns="http://example.com/sample.wsdl">
           <p><a>1</a><b>2</b></p><c><d>5000000.1</d><d>.2</d></c><dt>2010-07-24</dt>
        </Adder>
       </soap:Body>
    </soap:Envelope>"""
        self.eq(self.dispatcher.dispatch(xml), resp)

    def test_modern_dialect(self):
        # adder local test (modern soap dialect, SoapUI)
        resp = """<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:pys="http://example.com/pysimplesoapsamle/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><pys:AdderResponse><dd>15.021</dd><ab>12</ab><dt>1970-07-20</dt></pys:AdderResponse></soapenv:Body></soapenv:Envelope>"""
        xml = """
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pys="http://example.com/pysimplesoapsamle/">
   <soapenv:Header/>
   <soapenv:Body>
      <pys:Adder>
         <pys:p><pys:a>9</pys:a><pys:b>3</pys:b></pys:p>
         <pys:dt>1969-07-20<!--1969-07-20T21:28:00--></pys:dt>
         <pys:c><pys:d>10.001</pys:d><pys:d>5.02</pys:d></pys:c>
      </pys:Adder>
   </soapenv:Body>
</soapenv:Envelope>
    """
        self.eq(self.dispatcher.dispatch(xml), resp)

    def test_echo(self):
        # echo local test (generic soap service)
        resp = """<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><EchoResponse xmlns="http://example.com/pysimplesoapsamle/"><value xsi:type="xsd:string">Hello world</value></EchoResponse></soap:Body></soap:Envelope>"""
        xml = """<?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <soap:Body>
         <Echo xmlns="http://example.com/sample.wsdl">
           <value xsi:type="xsd:string">Hello world</value>
        </Echo>
       </soap:Body>
    </soap:Envelope>"""
        self.eq(self.dispatcher.dispatch(xml), resp)
예제 #48
0
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

from pysimplesoap.server import SoapDispatcher, SOAPHandler, WSGISOAPHandler
from django.http import HttpResponse


def func(data):
    return data


# dispatcher declaration: however you like to declare it ;)
dispatcher = SoapDispatcher(
    'my_dispatcher',
    location="http://localhost:8000/gapp/dispatcher_handler/",
    action='http://localhost:8000/gapp/dispatcher_handler/',
    namespace="http://blah.blah.org/blah/blah/local/",
    prefix="bl1",
    ns="bl2")

# register func
dispatcher.register_function('func',
                             func,
                             returns={'result': str},
                             args={'data': str})


@csrf_exempt
def dispatcher_handler(request):
    if request.method == "POST":
        response = HttpResponse(content_type="application/xml")
예제 #49
0
        r.set(key, val)
        return success
    return "Fail! Record with key \"" + key + "\" was not found!"


def delete(key):
    if r.exists(key):
        r.delete(key)
        return success
    return "Fail! Record with key \"" + key + "\" was not found!"


r = redis.StrictRedis(host='localhost', port=6379)

if __name__ == '__main__':
    dispatcher = SoapDispatcher(
        'di-di-dispatcher',
        location="http://localhost:8008/")

    dispatcher.register_function("testf", testf, returns={'MultResult': int}, args={'t': int})

    dispatcher.register_function("CreateRecord", create, returns={'Result': int}, args={"key": str, "val": str})
    dispatcher.register_function("ReadRecord", read, returns={'Result': int}, args={"key": str})
    dispatcher.register_function("UpdateRecord", update, returns={'Result': int}, args={"key": str, "val": str})
    dispatcher.register_function("DeleteRecord", delete, returns={'Result': int}, args={"key": str})

    server_address = ('', 8000)
    httpd = HTTPServer(server_address, SOAPHandler)
    httpd.dispatcher = dispatcher
    httpd.serve_forever()
예제 #50
0
    else:
        if current_path[-1] != '/':
            current_path = current_path + '/'
        cur_path = current_path + path
        if os.path.isdir(cur_path):
            current_path = cur_path
            if current_path[-1] != '/':
                current_path = current_path + '/'
            return True
        return False


dispatcher = SoapDispatcher(
    'my_dispatcher', 
    location='http://localhost:8008/', 
    action='http://localhost:8008/', 
    namespace='http://example.com/sample.wsdl', 
    prefix='ns0', 
    trace=True, 
    ns=True)

dispatcher.register_function('rm', rm, 
    returns={'Result': bool}, 
    args={'filename': str})

dispatcher.register_function('cp', cp, 
    returns={'Result': bool}, 
    args={'src': str, 'dest': str})

dispatcher.register_function('rename', rename, 
    returns={'Result': bool}, 
    args={'src': str, 'dest': str})
예제 #51
0
	
def bmiC(r):
    "Calculating BMI"
    if r<=18.5:
       Cat='UNDERWEIGHT'
    elif (r > 18.5) and (r < 25):
       Cat='NORMAL'
    else:
       Cat = 'OVERWEIGHT'
    
    return Cat
       
dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8012/",
    action = 'http://localhost:8012/', # SOAPAction
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)
# register the user function
dispatcher.register_function('Bmi', bmi,
    returns={'AddResult': float},
    args={'w': float,'h': float}) ## args type float
# register the user function 2
dispatcher.register_function('BmiC', bmiC,
    returns={'CatResult': str}, ## changed to str!
    args={'r': float}) ## arg type float
	
print "Starting server..."
httpd = HTTPServer(("", 8012), SOAPHandler)
httpd.dispatcher = dispatcher
예제 #52
0
from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import HTTPServer
from ldap import *



dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8000/",
    action = 'http://localhost:8000/', # SOAPAction
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)

dispatcher.register_function('Create', create, returns={'CreateResult': str},
                         args={'record_to_add': str, 'account': str})

dispatcher.register_function('Read', read, returns={'ReadResult': str}, args={'base_and_filter': str})

dispatcher.register_function('Update', update, returns={'UpdateResult': str},
                             args={'record_to_update': str, 'new_value': str, 'account': str})

dispatcher.register_function('Delete', delete, returns={'DeleteResult': str},
                             args={'record_to_delete': str, 'account': str})

if __name__ == "__main__":
    print "Starting server..."
    httpd = HTTPServer(("0.0.0.0", 8000), SOAPHandler)
    httpd.dispatcher = dispatcher
    httpd.serve_forever()
예제 #53
0
파일: server.py 프로젝트: SokratisT/cp8202
#################################################################
##                         SERVER                               #
##                                                              #
## Service 1: Convert currency from Canadian Dollar to American dollar and Indian Rupee #
##                                                              #
#################################################################
from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import HTTPServer
def crcy(c):
    "Calculating currency exchange"
    return (49.85*c)      
dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8020/",
    action = 'http://localhost:8020/', # SOAPAction
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)
# register the user function
dispatcher.register_function('crcy', crcy,
    returns={'AddResult': float},
    args={'c': float}) ## args type float

print "Starting server..."
httpd = HTTPServer(("", 8020), SOAPHandler)
httpd.dispatcher = dispatcher
httpd.serve_forever()

예제 #54
0
factory = PuzzleFactory(9, 3, 3)

def sudokuHelp(puzzle):
    print(puzzle)
    humanSolver = HumanSolver(Grid(9, 9, 3, 3))
    encoder = HintMessage()
    
    matrix = json.loads(puzzle)
    puzzleObj = factory.creatPuzzleByMatrix(matrix)
    hint = humanSolver.hint(puzzleObj)
    msg = encoder.getMsg(hint)
    print(msg)
    return json.dumps(msg)

dispatcher = SoapDispatcher(
    'my_dispatcher',
    location = "http://localhost:8008/",
    action = 'http://localhost:8008/', # SOAPAction
    namespace = "http://example.com/sample.wsdl", prefix="ns0",
    trace = True,
    ns = True)

# register the user function
dispatcher.register_function('SudokuHelp', sudokuHelp,
    returns={'hint': str}, 
    args={'puzzle': str})

print("Starting server...")
httpd = HTTPServer(("", 8008), SOAPHandler)
httpd.dispatcher = dispatcher
httpd.serve_forever()