Beispiel #1
0
class ImageConverterService(spyne.Service):
    """Spyne SOAP service to convert png images to jpg images.

    This service's purpose is to showcase file access via GSS.

    Note that the class name is _not_ important for the endpoint URL of the
    service (that's defined by __service_url_path__), but it will show up in
    the service WSDL as the service name.
    """
    __service_url_path__ = '/ImageConverter'
    __in_protocol__ = Soap11(validator='soft')
    __out_protocol__ = Soap11()

    @spyne.srpc(Unicode, Unicode, Unicode, _returns=Unicode,
                _out_variable_name="file_content")
    def imageconvert_png2jpg(sessionToken, extra_pars_str, gss_ID):
        """Converts a png image specified by a gss ID to a jpg image."""

        # Implementation starts here ...
        gss_ID_new = 'fake!'
        # ... and ends here

        return gss_ID_new
    def test_customized_class_with_empty_subclass(self):
        class SummaryStatsOfDouble(ComplexModel):
            _type_info = [('Min', XmlAttribute(Integer, use='required')),
                          ('Max', XmlAttribute(Integer, use='required')),
                          ('Avg', XmlAttribute(Integer, use='required'))]

        class SummaryStats(SummaryStatsOfDouble):
            ''' this is an empty base class '''

        class Payload(ComplexModel):
            _type_info = [('Stat1', SummaryStats.customize(nillable=False)),
                          ('Stat2', SummaryStats), ('Stat3', SummaryStats),
                          ('Dummy', Unicode)]

        class JackedUpService(ServiceBase):
            @rpc(_returns=Payload)
            def GetPayload(ctx):
                return Payload()

        Application([JackedUpService],
                    tns='kickass.ns',
                    in_protocol=Soap11(validator='lxml'),
                    out_protocol=Soap11())
Beispiel #3
0
    def test_simple_message(self):
        m = ComplexModel.produce(
            namespace=None,
            type_name='myMessage',
            members={'s': String, 'i': Integer}
        )
        m.resolve_namespace(m, 'test')

        m_inst = m(s="a", i=43)

        e = etree.Element('test')
        Soap11().to_parent(None, m, m_inst, e, m.get_namespace())
        e=e[0]

        self.assertEquals(e.tag, '{%s}myMessage' % m.get_namespace())

        self.assertEquals(e.find('{%s}s' % m.get_namespace()).text, 'a')
        self.assertEquals(e.find('{%s}i' % m.get_namespace()).text, '43')

        values = Soap11().from_element(None, m, e)

        self.assertEquals('a', values.s)
        self.assertEquals(43, values.i)
Beispiel #4
0
    def test_soap_bare_empty_output(self):
        class SomeService(ServiceBase):
            @rpc(String, _body_style='bare')
            def some_call(ctx, s):
                assert s == 'abc'

        app = Application([SomeService],
                          'tns',
                          in_protocol=Soap11(),
                          out_protocol=Soap11(cleanup_namespaces=True))

        req = """
        <senv:Envelope  xmlns:senv="http://schemas.xmlsoap.org/soap/envelope/"
                        xmlns:tns="tns">
            <senv:Body>
                <tns:some_call>abc</tns:some_call>
            </senv:Body>
        </senv:Envelope>
        """

        server = WsgiApplication(app)
        resp = etree.fromstring(''.join(
            server(
                {
                    'QUERY_STRING': '',
                    'PATH_INFO': '/call',
                    'REQUEST_METHOD': 'GET',
                    'SERVER_NAME': 'localhost',
                    'wsgi.input': StringIO(req)
                }, start_response, "http://null")))

        print etree.tostring(resp, pretty_print=True)

        assert resp[0].tag == '{http://schemas.xmlsoap.org/soap/envelope/}Body'
        assert len(resp[0]) == 1
        assert resp[0][0].tag == '{tns}some_call' + RESPONSE_SUFFIX
        assert len(resp[0][0]) == 0
Beispiel #5
0
    def _test_xml_data(self):
        tns = 'kickass.ns'

        class ProductEdition(ComplexModel):
            __namespace__ = tns
            id = XmlAttribute(Uuid)
            name = XmlData(Unicode)

        class Product(ComplexModel):
            __namespace__ = tns
            id = XmlAttribute(Uuid)
            edition = ProductEdition
            sample = XmlAttribute(Unicode, attribute_of='edition')

        class ExampleService(ServiceBase):
            @rpc(Product, _returns=Product)
            def say_my_uuid(ctx, product):
                pass

        app = Application([ExampleService],
                          tns='kickass.ns',
                          in_protocol=Soap11(validator='lxml'),
                          out_protocol=Soap11())

        schema = XmlSchema(app.interface)
        schema.build_interface_document()

        doc = schema.get_interface_document()['tns']
        print(etree.tostring(doc, pretty_print=True))

        assert len(
            doc.xpath(
                '/xs:schema/xs:complexType[@name="Product"]'
                '/xs:sequence/xs:element[@name="edition"]'
                '/xs:complexType/xs:simpleContent/xs:extension'
                '/xs:attribute[@name="id"]',
                namespaces={'xs': ns.xsd})) == 1
Beispiel #6
0
    def test_soap_bare_wrapped_array_output(self):
        class SomeService(ServiceBase):
            @rpc(_body_style='bare', _returns=Array(String))
            def some_call(ctx):
                return ['abc', 'def']

        app = Application([SomeService],
                          'tns',
                          in_protocol=Soap11(),
                          out_protocol=Soap11(cleanup_namespaces=True))

        req = """
        <soap11env:Envelope  xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/"
                        xmlns:tns="tns">
            <soap11env:Body>
                <tns:some_call/>
            </soap11env:Body>
        </soap11env:Envelope>
        """

        server = WsgiApplication(app)
        resp = etree.fromstring(''.join(
            server(
                {
                    'QUERY_STRING': '',
                    'PATH_INFO': '/call',
                    'REQUEST_METHOD': 'POST',
                    'CONTENT_TYPE': 'text/xml',
                    'wsgi.input': BytesIO(req)
                }, start_response, "http://null")))

        print(etree.tostring(resp, pretty_print=True))

        assert resp[0].tag == '{http://schemas.xmlsoap.org/soap/envelope/}Body'
        assert resp[0][0].tag == '{tns}some_call' + RESPONSE_SUFFIX
        assert resp[0][0][0].text == 'abc'
        assert resp[0][0][1].text == 'def'
Beispiel #7
0
    def test_bare(self):
        ns = {
            'wsdl': 'http://schemas.xmlsoap.org/wsdl/',
            'xs': 'http://www.w3.org/2001/XMLSchema',
        }

        class InteropBare(ServiceBase):
            @srpc(String, _returns=String, _body_style='bare')
            def echo_simple_bare(ss):
                return ss

            @srpc(Array(String), _returns=Array(String), _body_style='bare')
            def echo_complex_bare(ss):
                return ss

        app = Application([InteropBare],
                          tns='tns',
                          in_protocol=Soap11(),
                          out_protocol=Soap11())
        app.transport = 'None'

        wsdl = Wsdl11(app.interface)
        wsdl.build_interface_document('url')
        wsdl = etree.fromstring(wsdl.get_interface_document())

        schema = wsdl.xpath(
            '/wsdl:definitions/wsdl:types/xs:schema[@targetNamespace]',
            namespaces=ns)
        assert len(
            schema[0].xpath('xs:complexType[@name="string%s"]' % ARRAY_SUFFIX,
                            namespaces=ns)) > 0
        elts = schema[0].xpath('xs:element[@name="echo_complex_bare%s"]' %
                               RESPONSE_SUFFIX,
                               namespaces=ns)

        assert len(elts) > 0
        assert elts[0].attrib['type'] == 'tns:stringArray'
Beispiel #8
0
    def test_namespaces(self):
        m = ComplexModel.produce(
            namespace="some_namespace",
            type_name='myMessage',
            members={'s': String, 'i': Integer},
        )

        mi = m()
        mi.s = 'a'

        e = etree.Element('test')
        Soap11().to_parent(None, m, mi, e, m.get_namespace())
        e=e[0]

        self.assertEquals(e.tag, '{some_namespace}myMessage')
Beispiel #9
0
    def test_call(self):
        queue = set()

        class MessageService(ServiceBase):
            @srpc(String, String)
            def send_message(s, k):
                queue.add((s,k))

        application = Application([MessageService], 'some_tns',
            interface=Wsdl11(), in_protocol=Soap11(), out_protocol=Soap11())

        server = NullServer(application)

        queue.clear()
        server.service.send_message("zabaaa", k="hobaa")
        assert set([("zabaaa","hobaa")]) == queue

        queue.clear()
        server.service.send_message(k="hobaa")
        assert set([(None,"hobaa")]) == queue

        queue.clear()
        server.service.send_message("zobaaa", s="hobaa")
        assert set([("hobaa", None)]) == queue
Beispiel #10
0
    def test_attribute_of(self):
        class SomeObject(ComplexModel):
            c = String
            a = XmlAttribute(Integer, attribute_of='c')

        class SomeService(ServiceBase):
            @srpc(SomeObject)
            def echo_simple_bare(ss):
                pass

        app = Application([SomeService], tns='tns',
                                    in_protocol=Soap11(), out_protocol=Soap11())
        app.transport = 'None'

        wsdl = Wsdl11(app.interface)
        wsdl.build_interface_document('url')

        wsdl = etree.fromstring(wsdl.get_interface_document())
        print etree.tostring(wsdl, pretty_print=True)
        assert len(wsdl.xpath(
            "/wsdl:definitions/wsdl:types/xs:schema[@targetNamespace='%s']"
            "/xs:complexType[@name='SomeObject']/xs:sequence/xs:element[@name='c']"
            '/xs:complexType/xs:simpleContent/xs:extension/xs:attribute[@name="a"]'
            % (SomeObject.get_namespace()), namespaces=const_nsmap)) > 0
Beispiel #11
0
    def setUp(self):
        class SomeService(ServiceBase):
            @srpc(String(pattern='a'))
            def some_method(s):
                pass

            @srpc(String(pattern='a', max_occurs=2))
            def some_other_method(s):
                pass

        self.application = Application(
            [SomeService],
            in_protocol=HttpRpc(validator='soft'),
            out_protocol=Soap11(),
            name='Service',
            tns='tns',
        )
Beispiel #12
0
    def __run_service(self, service):
        app = Application([service], 'tns', in_protocol=HttpRpc(),
                                                          out_protocol=Soap11())
        server = WsgiApplication(app)

        return_string = b''.join(server({
            'QUERY_STRING': '',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'POST',
            'CONTENT_TYPE': 'text/xml; charset=utf8',
            'SERVER_NAME': 'localhost',
            'wsgi.input': BytesIO(b""),
        }, start_response, "http://null"))

        elt = etree.fromstring(return_string)
        print(etree.tostring(elt, pretty_print=True))

        return elt, app.interface.nsmap
Beispiel #13
0
    def test_fault_deserialization_missing_fault_actor(self):
        element = etree.fromstring("""<soap:Envelope
                        xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <soap:Fault>
      <faultcode>soap:Client</faultcode>
      <faultstring>Some String</faultstring>
      <detail>
        <Detail xmlns="some_ns">
          <Policy>Some_Policy</Policy>
        </Detail>
      </detail>
    </soap:Fault>
  </soap:Body>
</soap:Envelope>""")

        ret = Soap11().from_element(Fault, element[0][0])
        assert ret.faultcode == "soap:Client"
Beispiel #14
0
    def assert_soap_ok(self, suffix, _operation_name = None, _in_message_name=None):
        '''helper to test soap requests'''

        # setup
        app = self.get_app(Soap11(validator='lxml'), suffix, _operation_name, _in_message_name)

        function_name, operation_name, request_name = self.get_function_names(suffix, _operation_name, _in_message_name)

        soap_input_body = """
        <SOAP-ENV:Envelope xmlns:ns0="spyne.examples.echo" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
           <SOAP-ENV:Header/>
           <ns1:Body>
              <ns0:{0}>
                 <ns0:string>test</ns0:string>
                 <ns0:times>2</ns0:times>
              </ns0:{0}>
           </ns1:Body>
        </SOAP-ENV:Envelope>""".format(request_name)

        # check wsdl
        wsdl = app.get('/?wsdl')
        self.assertEqual(wsdl.status_int, 200, wsdl)
        self.assertTrue(request_name in wsdl, '{0} not found in wsdl'.format(request_name))

        soap_strings = [
            '<wsdl:operation name="{0}"'.format(operation_name),
            '<soap:operation soapAction="{0}"'.format(operation_name),
            '<wsdl:input name="{0}">'.format(request_name),
            '<xs:element name="{0}"'.format(request_name),
            '<xs:complexType name="{0}">'.format(request_name),
        ]
        for soap_string in soap_strings:
            self.assertTrue(soap_string in wsdl, '{0} not in {1}'.format(soap_string, wsdl))
        if request_name != operation_name:
            wrong_string = '<wsdl:operation name="{0}"'.format(request_name)
            self.assertFalse(wrong_string in wsdl, '{0} in {1}'.format(wrong_string, wsdl))

        output_name = '<wsdl:output name="{0}Response"'.format(self.default_function_name)
        self.assertTrue(output_name in wsdl, 'REQUEST_SUFFIX or _in_message_name changed the output name, it should be: {0}'.format(output_name))

        # check soap operation succeeded
        resp = app.post('/', soap_input_body)
        self.assert_response_ok(resp)
Beispiel #15
0
    def __run_service(self, service):
        app = Application([service],
                          'tns',
                          in_protocol=HttpRpc(),
                          out_protocol=Soap11())
        server = WsgiApplication(app)
        return_string = ''.join(
            server(
                {
                    'QUERY_STRING': '',
                    'PATH_INFO': '/some_call',
                    'REQUEST_METHOD': 'GET',
                    'SERVER_NAME': 'localhost',
                }, start_response, "http://null"))

        elt = etree.fromstring(''.join(return_string))
        print etree.tostring(elt, pretty_print=True)

        return elt, app.interface.nsmap
Beispiel #16
0
 def __init__(self):
     info_app = Application([InfoServer],
                            tns=SOAP_NAMESPACE,
                            name='InfoService',
                            interface=Wsdl11(),
                            in_protocol=Soap11(),
                            out_protocol=Soap11())
     info_app.event_manager.add_listener('wsgi_close', shutdown_session)
     list_app = Application([ListServer],
                            tns=SOAP_NAMESPACE,
                            name='ListService',
                            interface=Wsdl11(),
                            in_protocol=Soap11(),
                            out_protocol=Soap11())
     list_app.event_manager.add_listener('wsgi_close', shutdown_session)
     schedule_app = Application([ScheduleServer],
                                tns=SOAP_NAMESPACE,
                                name='ScheduleService',
                                interface=Wsdl11(),
                                in_protocol=Soap11(),
                                out_protocol=Soap11())
     schedule_app.event_manager.add_listener('wsgi_close', shutdown_session)
     epgu_gate_app = Application([EPGUGateServer],
                                 tns='http://erGateService.er.atc.ru/ws',
                                 name='GateService',
                                 interface=Wsdl11(),
                                 in_protocol=Soap11(),
                                 out_protocol=Soap11())
     epgu_gate_app.event_manager.add_listener('wsgi_close',
                                              shutdown_session)
     self.applications = CustomWsgiMounter({
         'info': info_app,
         'list': list_app,
         'schedule': schedule_app,
         'gate': epgu_gate_app,
     })
Beispiel #17
0
    def __test_interface(self):
        import logging
        logging.basicConfig(level=logging.DEBUG)

        class KeyValuePair(ComplexModel):
            __namespace__ = "1"
            key = Unicode
            value = Unicode

        class Something(ComplexModel):
            __namespace__ = "2"
            d = DateTime
            i = Integer

        class SomethingElse(ComplexModel):
            __namespace__ = "3"
            a = AnyXml
            b = UnsignedLong
            se = Something

        class Service(ServiceBase):
            @rpc(SomethingElse, _returns=Array(KeyValuePair))
            def some_call(ctx, sth):
                pass

        application = Application([Service],
                                  in_protocol=HttpRpc(),
                                  out_protocol=Soap11(),
                                  name='Service',
                                  tns='target_namespace')

        imports = application.interface.imports
        smm = application.interface.service_method_map

        print(smm)

        raise NotImplementedError('test something!')
Beispiel #18
0
def main():
    file = open(
        'bench_result' +
        str(datetime.datetime.now().strftime("%Y-%m-%d-%H-%M")), 'w')
    gen = CubeGen(number_dimensions=3, rows_length=1000, columns_length=5)
    gen.generate_csv(gen.generate_cube(3, 1000))
    XmlaProviderService.discover_tools.change_catalogue(CUBE_NAME)
    mbench = MicBench()

    file.write("Benchmarks are made with cpu :\n")
    file.write(cpuinfo.get_cpu_info()['brand'] + "\n\n")

    application = Application([XmlaProviderService],
                              'urn:schemas-microsoft-com:xml-analysis',
                              in_protocol=Soap11(validator='soft'),
                              out_protocol=Soap11(validator='soft'))
    wsgi_application = WsgiApplication(application)
    server = WSGIServer(application=wsgi_application, host=HOST, port=PORT)
    server.start()

    provider = xmla.XMLAProvider()
    conn = provider.connect(location=server.url)

    t = PrettyTable(['Query', 'olapy execution time'])

    cmd = """
            SELECT
            FROM [""" + CUBE_NAME + """]
            WHERE ([Measures].[Amount])
            CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

    file.write(
        "Query 1 :\n" + cmd +
        "\n----------------------------------------------------------\n\n")

    t.add_row(['Query 1', mbench.bench(conn, cmd, CUBE_NAME)])

    cmd = """SELECT
        NON EMPTY Hierarchize(AddCalculatedMembers(DrilldownMember({{{
        [table0].[table0].[All table0A].Members}}}, {
        [table0].[table0].[table0A].[""" + str(
        XmlaProviderService.discover_tools.star_schema_dataframe.table0A[1]
    ) + """]})))
        DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
        ON COLUMNS
        FROM [""" + CUBE_NAME + """]
        WHERE ([Measures].[Amount])
        CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS
        """

    file.write(
        "Query 2 :\n" + cmd +
        "\n----------------------------------------------------------\n\n")
    t.add_row(['Query 2', mbench.bench(conn, cmd, CUBE_NAME)])

    tup = "[table0].[table0].[table0A].[" + str(
        XmlaProviderService.discover_tools.star_schema_dataframe.table0A[0]
    ) + "]"
    for d in range(REFINEMENT_LVL):
        tup += ",\n[table0].[table0].[table0A].[" + str(
            XmlaProviderService.discover_tools.star_schema_dataframe.table0A[
                d + 1]) + "]"

    cmd = """
        SELECT NON EMPTY Hierarchize(AddCalculatedMembers(DrilldownMember({{{
        [table0].[table0].[All table0A].Members}}}, {
        """ + tup + """
        })))
        DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
        ON COLUMNS
        FROM [""" + CUBE_NAME + """]
        WHERE ([Measures].[Amount])
        CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS
        """

    file.write(
        "Query 3 :\n" + cmd +
        "\n----------------------------------------------------------\n\n")
    t.add_row(['Query 3', mbench.bench(conn, cmd, CUBE_NAME)])
    file.write(str(t) + "\n\n")

    try:
        file.write(
            '******************************************************************************\n'
        )
        file.write(
            '* mondrian with "warehouse" Cube (note the same as olapy but resemble to it) *\n'
        )
        file.write(
            '* (olapy warehouse"s cube has more rows)                                     *\n'
        )
        file.write(
            '******************************************************************************\n\n'
        )

        t = PrettyTable(['Query', 'mondrian', 'olapy'])
        p2 = xmla.XMLAProvider()
        c2 = p2.connect(location="http://localhost:8080/xmondrian/xmla")

        cmd = """SELECT
               FROM [foodmart]
               WHERE ([Measures].[supply_time])
               CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        cmd2 = """SELECT
               NON EMPTY {[Measures].[Supply Time]}
               DIMENSION PROPERTIES PARENT_UNIQUE_NAME ON 0
               FROM
               [Warehouse]"""

        file.write(
            "Query 1 :\n" + cmd2 +
            "\n----------------------------------------------------------\n\n")
        t.add_row([
            'Query 1',
            mbench.bench(c2, cmd2, 'FoodMart'),
            mbench.bench(conn, cmd, 'foodmart')
        ])

        cmd = """SELECT NON EMPTY Hierarchize(AddCalculatedMembers(DrilldownMember({{{
          [Product].[Product].[All brand_name].Members}}}, {
          [Product].[Product].[brand_name].[Pearl]})))
          DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS
          FROM [foodmart]
          WHERE ([Measures].[supply_time])
          CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        cmd2 = """SELECT
            NON EMPTY CrossJoin(Hierarchize({
            [Product].[Brand Name].Members,
            [Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Wine].[Pearl].Children}), {
            [Measures].[Supply Time]})
            DIMENSION PROPERTIES PARENT_UNIQUE_NAME ON 0
            FROM [Warehouse]"""

        file.write(
            "Query 2 :\n" + cmd2 +
            "\n----------------------------------------------------------\n\n")
        t.add_row([
            'Query 2',
            mbench.bench(c2, cmd2, 'FoodMart'),
            mbench.bench(conn, cmd, 'foodmart')
        ])

        cmd = """SELECT NON EMPTY CrossJoin(Hierarchize(AddCalculatedMembers({
          [Product].[Product].[All brand_name].Members})), Hierarchize(AddCalculatedMembers({
          [Store].[Store].[All store_type].Members})))
          DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS
          FROM [foodmart]
          WHERE ([Measures].[supply_time])
          CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        cmd2 = """SELECT
            NON EMPTY CrossJoin(CrossJoin(Hierarchize({
            [Product].[Brand Name].Members}),Hierarchize({
            [Store Type].[All Store Types],
            [Store Type].[All Store Types].Children})),
            {[Measures].[Supply Time]})
            DIMENSION PROPERTIES PARENT_UNIQUE_NAME ON 0
            FROM [Warehouse]"""

        file.write(
            "Query 3 :\n" + cmd2 +
            "\n----------------------------------------------------------\n\n")
        t.add_row([
            'Query 3',
            mbench.bench(c2, cmd2, 'FoodMart'),
            mbench.bench(conn, cmd, 'foodmart')
        ])

        file.write(str(t) + "\n\n")

    except:
        print('Make sure mondrian is running and containing Warehouse cube')
        pass

    try:
        file.write('******************************************\n')
        file.write('* iCcube v4.8.2 with "sales Excel" Cube  *\n')
        file.write('******************************************\n\n')

        t = PrettyTable(['Query', 'olapy', 'icCube'])
        p2 = xmla.XMLAProvider()
        c2 = p2.connect(location="http://localhost:8282/icCube/xmla",
                        username="******",
                        password="******")

        cmd = """SELECT
          FROM [Sales]
          WHERE ([Measures].[Amount])
          CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        file.write(
            "Query 1 :\n" + cmd +
            "\n----------------------------------------------------------\n\n")
        t.add_row([
            'Query 1',
            mbench.bench(conn, cmd, 'sales'),
            mbench.bench(c2, cmd, 'Sales (Excel)')
        ])

        cmd = """SELECT
                NON EMPTY Hierarchize(AddCalculatedMembers({DrilldownLevel({
                [Geography].[Geo].[All Regions]})}))
                DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS
                FROM [Sales]
                WHERE ([Measures].[Amount])
                CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        cmd2 = """SELECT
                  NON EMPTY Hierarchize(AddCalculatedMembers({DrilldownLevel({
                  [Geography].[Geo].[All Continent]})}))
                  DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
                  ON COLUMNS
                  FROM [Sales]
                  WHERE ([Measures].[Amount])
                  CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""
        file.write(
            "Query 2 :\n" + cmd2 +
            "\n----------------------------------------------------------\n\n")
        t.add_row([
            'Query 2',
            mbench.bench(conn, cmd2, 'sales'),
            mbench.bench(c2, cmd, 'Sales (Excel)')
        ])

        cmd = """SELECT
                 NON EMPTY Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{DrilldownLevel({
                 [Geography].[Geo].[All Regions]})}}, {
                 [Geography].[Geo].[All Regions].&amp;[America],
                 [Geography].[Geo].[All Regions].&amp;[Europe]})}}, {
                 [Geography].[Geo].[All Regions].&amp;[America].&amp;[US],
                 [Geography].[Geo].[All Regions].&amp;[Europe].&amp;[FR],
                 [Geography].[Geo].[All Regions].&amp;[Europe].&amp;[ES]})))
                 DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
                 ON COLUMNS
                 FROM [Sales]
                 WHERE ([Measures].[Amount])
                 CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        cmd2 = """SELECT
                  NON EMPTY Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{{
                  [Geography].[Geography].[All Continent].Members}}}, {
                  [Geography].[Geography].[Continent].[America],
                  [Geography].[Geography].[Continent].[Europe]})}}, {
                  [Geography].[Geography].[Continent].[America].[United States],
                  [Geography].[Geography].[Continent].[Europe].[France],
                  [Geography].[Geography].[Continent].[Europe].[Spain]})))
                  DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
                  ON COLUMNS
                  FROM [sales]
                  WHERE ([Measures].[Amount])
                  CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""
        file.write(
            "Query 3 :\n" + cmd2 +
            "\n----------------------------------------------------------\n\n")
        t.add_row([
            'Query 3',
            mbench.bench(conn, cmd2, 'sales'),
            mbench.bench(c2, cmd, 'Sales (Excel)')
        ])

        cmd = """SELECT
                 NON EMPTY CrossJoin(Hierarchize(AddCalculatedMembers(DrilldownMember
                 ({{DrilldownMember({{DrilldownLevel({
                 [Geography].[Geo].[All Regions]})}}, {
                 [Geography].[Geo].[All Regions].&amp;[America],
                 [Geography].[Geo].[All Regions].&amp;[Europe]})}}, {
                 [Geography].[Geo].[All Regions].&amp;[America].&amp;[US],
                 [Geography].[Geo].[All Regions].&amp;[Europe].&amp;[FR],
                 [Geography].[Geo].[All Regions].&amp;[Europe].&amp;[ES]}))), Hierarchize(AddCalculatedMembers({
                 [Product].[Prod].[Company].Members}))) DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
                 ON COLUMNS
                 FROM [Sales]
                 WHERE ([Measures].[Amount])
                 CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        cmd2 = """SELECT
                  NON EMPTY CrossJoin(Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{{
                  [Geography].[Geography].[All Continent].Members}}}, {
                  [Geography].[Geography].[Continent].[America],
                  [Geography].[Geography].[Continent].[Europe]})}}, {
                  [Geography].[Geography].[Continent].[America].[United States],
                  [Geography].[Geography].[Continent].[Europe].[France],
                  [Geography].[Geography].[Continent].[Europe].[Spain]}))), Hierarchize(AddCalculatedMembers({
                  [Product].[Product].[Company].Members})))
                  DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
                  ON COLUMNS
                  FROM [sales]
                  WHERE ([Measures].[Amount])
                  CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        file.write(
            "Query 4 :\n" + cmd2 +
            "\n----------------------------------------------------------\n\n")
        t.add_row([
            'Query 4',
            mbench.bench(conn, cmd2, 'sales'),
            mbench.bench(c2, cmd, 'Sales (Excel)')
        ])

        cmd = """SELECT
                 NON EMPTY CrossJoin(CrossJoin(Hierarchize(AddCalculatedMembers
                 (DrilldownMember({{DrilldownMember({{DrilldownLevel({
                 [Geography].[Geo].[All Regions]})}}, {
                 [Geography].[Geo].[All Regions].&amp;[America],
                 [Geography].[Geo].[All Regions].&amp;[Europe]})}}, {
                 [Geography].[Geo].[All Regions].&amp;[America].&amp;[US],
                 [Geography].[Geo].[All Regions].&amp;[Europe].&amp;[FR],
                 [Geography].[Geo].[All Regions].&amp;[Europe].&amp;[ES]}))),
                 Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{
                 [Product].[Prod].[Company].Members}}, {
                 [Product].[Prod].[Company].&amp;[Crazy Development ]})}}, {
                 [Product].[Prod].[Company].&amp;[Crazy Development ].&amp;[icCube]})))),
                 Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{DrilldownMember({{
                 [Time].[Calendar].[Year].Members}}, {
                 [Time].[Calendar].[Year].&amp;[2010]})}}, {
                 [Time].[Calendar].[Year].&amp;[2010].&amp;[Q2 2010]})}}, {
                 [Time].[Calendar].[Year].&amp;[2010].&amp;[Q2 2010].&amp;[May 2010]}))))
                 DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
                 ON COLUMNS
                 FROM [Sales]
                 WHERE ([Measures].[Amount])
                 CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        cmd2 = """SELECT
                  NON EMPTY CrossJoin(CrossJoin(Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{{
                  [Geography].[Geography].[All Continent].Members}}}, {
                  [Geography].[Geography].[Continent].[America],
                  [Geography].[Geography].[Continent].[Europe]})}}, {
                  [Geography].[Geography].[Continent].[America].[United States],
                  [Geography].[Geography].[Continent].[Europe].[France],
                  [Geography].[Geography].[Continent].[Europe].[Spain]}))),
                  Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{
                  [Product].[Product].[Company].Members}}, {
                  [Product].[Product].[Company].[Crazy Development]})}}, {
                  [Product].[Product].[Company].[Crazy Development].[olapy]})))),
                  Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{DrilldownMember({{
                  [Time].[Time].[Year].Members}}, {
                  [Time].[Time].[Year].[2010]})}}, {
                  [Time].[Time].[Year].[2010].[Q2 2010]})}}, {
                  [Time].[Time].[Year].[2010].[Q2 2010].[May 2010]}))))
                  DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
                  ON COLUMNS
                  FROM [sales]
                  WHERE ([Measures].[Amount])
                  CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"""

        file.write(
            "Query 5 :\n" + cmd2 +
            "\n----------------------------------------------------------\n\n")
        t.add_row([
            'Query 5',
            mbench.bench(conn, cmd2, 'sales'),
            mbench.bench(c2, cmd, 'Sales (Excel)')
        ])

        file.write(str(t) + "\n\n")

    except:
        print('Make sure icCube is running and containing sales Excel cube')
        pass

    file.write(
        '---------------- Profiling olapy Query 5 ------------------ \n\n')
    cProfile.run(
        """cmd = '''
            SELECT
            NON EMPTY CrossJoin(CrossJoin(Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{{
            [Geography].[Geography].[All Continent].Members}}}, {
            [Geography].[Geography].[Continent].[America],
            [Geography].[Geography].[Continent].[Europe]})}}, {
            [Geography].[Geography].[Continent].[America].[United States],
            [Geography].[Geography].[Continent].[Europe].[France],
            [Geography].[Geography].[Continent].[Europe].[Spain]}))),
            Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{
            [Product].[Product].[Company].Members}}, {
            [Product].[Product].[Company].[Crazy Development]})}}, {
            [Product].[Product].[Company].[Crazy Development].[olapy]})))),
            Hierarchize(AddCalculatedMembers(DrilldownMember({{DrilldownMember({{DrilldownMember({{
            [Time].[Time].[Year].Members}}, {
            [Time].[Time].[Year].[2010]})}}, {
            [Time].[Time].[Year].[2010].[Q2 2010]})}}, {
            [Time].[Time].[Year].[2010].[Q2 2010].[May 2010]}))))
            DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME
            ON COLUMNS
            FROM [sales]
            WHERE ([Measures].[Amount])
            CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS'''

request = ExecuteRequest()
request.Command = Command(Statement = cmd)
request.Properties = Propertielist(PropertyList = Property(Catalog='sales'))

XmlaProviderService().Execute(XmlaProviderService(),request)""",
        "{}.profile".format(__file__))

    s = pstats.Stats("{}.profile".format(__file__), stream=file)
    s.strip_dirs()
    s.sort_stats("time").print_stats(PROFILING_LINES)

    try:
        os.system(
            'gprof2dot -f pstats main.py.profile | dot -Tpng -o profile.png')
    except:
        print('make sure gprof2dot and graphviz are installed')

    os.remove('main.py.profile ')
    gen.remove_temp_cube()
    file.close()
    server.stop()
Beispiel #19
0
        return retval


def _on_method_call(ctx):
    if ctx.in_object is None:
        raise ArgumentError("RequestHeader is null")
    if not (ctx.in_header.user_name, ctx.in_header.session_id) in session_db:
        raise AuthenticationError(ctx.in_object.user_name)


UserService.event_manager.add_listener('method_call', _on_method_call)

if __name__ == '__main__':
    from spyne.util.wsgi_wrapper import run_twisted

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
    logging.getLogger('twisted').setLevel(logging.DEBUG)

    application = Application([AuthenticationService, UserService],
        tns='spyne.examples.authentication',
        in_protocol=Soap11(validator='lxml'),
        out_protocol=Soap11()
    )

    twisted_apps = [
        (WsgiApplication(application), 'app'),
    ]

    sys.exit(run_twisted(twisted_apps, 8000))
Beispiel #20
0
        '''
        保存推送过来的地址信息接口
        :param request: 接收的请求
        :return: 地址保存结果
        '''
        logging.info('接收到请求:%s' % request)
        rq_decode = request_base64_decode(request)
        logging.info('请求参数:%s' % rq_decode)
        env_tree = XmlEnvelopeTree(rq_decode)
        dict_data = env_tree.xml_to_dict()
        logging.info('请求体字典数据:%s' % dict_data)
        result = saveaddr_to_db(dict_data)
        xml_tree = XmlEnvelopeTree(result)
        logging.info('响应数据:%s' % xml_tree.envelope_encode())
        return base64.b64encode(
            xml_tree.envelope_encode().encode('utf-8')).decode()


soap_app = Application(
    [OrderServices],
    tns='webservice_test.myservice.views',
    # in_protocol=HttpRpc(validator='soft'),
    # 'SampleServices',
    in_protocol=Soap11(validator="lxml"),
    out_protocol=Soap11())
django_app = DjangoApplication(soap_app)
sum_app = csrf_exempt(django_app)
es = get_session()
init_db(es[0])
logging.info("listening to http://127.0.0.1:8000")
logging.info("wsdl is at: http://localhost:8000/OrderServices?wsdl")
Beispiel #21
0
        if not (userid in user_database):
            raise ResourceNotFoundError(userid)

        del user_database[userid]

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

        return user_database.values()


if __name__ == '__main__':
    from wsgiref.simple_server import make_server

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)

    application = Application([UserManager],
                              'spyne.examples.complex',
                              interface=Wsdl11(),
                              in_protocol=Soap11(),
                              out_protocol=Soap11())

    server = make_server('127.0.0.1', 7789, WsgiApplication(application))

    logging.info("listening to http://127.0.0.1:7789")
    logging.info("wsdl is at: http://localhost:7789/?wsdl")

    server.serve_forever()
Beispiel #22
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
from spyne import Application
from spyne import rpc
from spyne import ServiceBase
from spyne import Iterable, Integer, Unicode
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

class Hello_world_service(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def hello_world(self, name, times):
        print name
        print times
        for i in range(times):
            yield u'Hello, %s' % name
            
soap_app = Application( [Hello_world_service], 'zyy_xxk', in_protocol = Soap11(validator='lxml'), out_protocol=Soap11() )

wsgi_app = WsgiApplication(soap_app)

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    server = make_server('192.168.209.136', 8000, wsgi_app)
    server.serve_forever()
Beispiel #23
0
class GetFlightService(spyne.Service):

    __service_url_path__ = '/test/get/flight'
    __in_protocol__ = Soap11(validator='lxml')
    __out_protocol__ = out_protocol = Soap11()

    @spyne.srpc(Auth, Flight, _returns=GetFlightsResponse)
    def get_flights(auth, flight):

        request_json = generate_json_request_get_flights(auth, flight)

        headers = {'Content-type': 'application/json'}
        response_json = requests.post('http://localhost:5000/temp/get/flight',
                                      data=request_json,
                                      headers=headers)
        response_json = json.loads(response_json.text)

        flights = []

        get_flights_response = GetFlightsResponse()
        get_flights_response.Error = response_json["error"]

        #  Por cada flight recibido, voy a recorrer tambien sus conexiones y fares y agregarlas a la respuesta
        for f in response_json["flights"]:
            new_flight = Flight()
            new_flight.from_ = f["from"]
            new_flight.to = f["to"]
            new_flight.airlineIATA = f["airlineIATA"]
            new_flight.airline = f["airline"]
            new_flight.flightNumber = f["flightNumber"]
            new_flight.range = f["range"]
            new_flight.arrivalDateTime = datetime.datetime.strptime(
                f["arrivalDateTime"], "%Y-%m-%dT%H:%M:%S")
            new_flight.departureDatetime = datetime.datetime.strptime(
                f["departureDatetime"], "%Y-%m-%dT%H:%M:%S")
            new_flight.nAdult = 1  # TODO completar
            new_flight.nChild = 1  # TODO completar
            new_flight.nInfant = 1  # TODO completar
            new_flight.Index = int(f["Index"])
            new_flight.type = f["type"]
            new_flight.schedule = f["schedule"]
            new_flight.info = f["info"]
            new_flight.return_ = f["return"]
            new_flight.LConnections = []
            new_flight.LFares = []

            for c in f["LConnections"]:

                new_connection = Connection()
                new_connection.airline = c["airline"]
                new_connection.airlineIATA = c["airlineIATA"]
                new_connection.from_ = c["from"]
                new_connection.fromAirport = c["fromAiport"]
                new_connection.fromAirportIATA = c["fromAirportIATA"]
                new_connection.to = c["to"]
                new_connection.toAirport = c["toAirport"]
                new_connection.toAirportIATA = c[
                    "toAirpottIATA"]  #TODO corregir SOAP
                new_connection.flightNumber = c["flightNumber"]
                new_connection.map = c["map"]

                new_connection.departureDatetime = datetime.datetime.strptime(
                    c["departureDatetime"], "%Y-%m-%dT%H:%M:%S")
                new_connection.arrivalDateTime = datetime.datetime.strptime(
                    c["arrivalDateTime"], "%Y-%m-%dT%H:%M:%S")
                # new_connection.AV = c["AV"] TODO agregar AV a estructuras

                new_flight.LConnections.append(new_connection)

            for flare in f["LFares"]:
                new_fare = Fare()
                new_fare.type = flare["type"]
                new_fare.fare_name = flare["fare_name"]
                new_fare.fare_price = flare["fare_price"]
                new_fare.currency = flare["currency"]
                new_fare.exchange_rate = flare["exchange_rate"]
                new_fare.fare_book = flare["fare_book"]
                new_fare.rules = flare["rules"]
                new_fare.return_ = flare["return_"]
                new_fare.connection = flare["connection"]

                new_flight.LFares.append(new_fare)

            flights.append(new_flight)

        get_flights_response.Flights = flights

        return get_flights_response
Beispiel #24
0
        except FieldContainer.DoesNotExist:
            raise ResourceNotFoundError('Container_submitseq')

    @rpc(Container_submitseq, _returns=Container_submitseq)
    def create_container(ctx, container):
        try:
            return FieldContainer.objects.create(**container.as_dict())
        except IntegrityError:
            raise ResourceAlreadyExistsError('Container_submitseq')

class ExceptionHandlingService_submitseq(DjangoServiceBase):
    """Service for testing exception handling."""

    @rpc(_returns=Container_submitseq)
    def raise_does_not_exist(ctx):
        return FieldContainer.objects.get(pk=-1)

    @rpc(_returns=Container_submitseq)
    def raise_validation_error(ctx):
        raise ValidationError('Is not valid.')


app_submitseq = Application([Service_submitseq, ContainerService_submitseq,
    ExceptionHandlingService_submitseq], 'pathopred.bioinfo.se',
    in_protocol=Soap11(validator='soft'), out_protocol=Soap11())
#wsgi_app_submitseq = WsgiApplication(app_submitseq)

submitseq_service = csrf_exempt(DjangoApplication(app_submitseq))

#}}}
Beispiel #25
0
import logging

logging.basicConfig(level=logging.DEBUG)
logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
logger = logging.getLogger('spyne.test.interop.server.soap_http_basic')

from spyne.test.interop.server import get_open_port
from spyne.server.wsgi import WsgiApplication
from spyne.test.interop.server._service import services
from spyne.application import Application
from spyne.protocol.soap import Soap11

soap11_application = Application(services,
                                 'spyne.test.interop.server',
                                 in_protocol=Soap11(validator='lxml',
                                                    cleanup_namespaces=True),
                                 out_protocol=Soap11())

host = '127.0.0.1'
port = [0]


def main():
    try:
        from wsgiref.simple_server import make_server
        from wsgiref.validate import validator
        if port[0] == 0:
            port[0] = get_open_port()

        wsgi_application = WsgiApplication(soap11_application)
        server = make_server(host, port[0], validator(wsgi_application))
Beispiel #26
0
    def test_method_exception(self):
        from spyne.protocol.xml import XmlDocument

        h = [0]

        def on_method_exception_object(ctx):
            assert ctx.out_error is not None
            from spyne.protocol.xml import SchemaValidationError
            assert isinstance(ctx.out_error, SchemaValidationError)
            logging.error("method_exception_object: %r", repr(ctx.out_error))
            h[0] += 1

        def on_method_exception_document(ctx):
            assert ctx.out_error is not None
            from spyne.protocol.xml import SchemaValidationError
            assert isinstance(ctx.out_error, SchemaValidationError)
            logging.error("method_exception_document: %r",
                          etree.tostring(ctx.out_document))
            h[0] += 1

        class SomeService(Service):
            @rpc(Unicode(5))
            def some_call(ctx, some_str):
                print(some_str)

        app = Application([SomeService],
                          "some_tns",
                          in_protocol=XmlDocument(validator='lxml'),
                          out_protocol=Soap11())

        app.event_manager.add_listener("method_exception_object",
                                       on_method_exception_object)

        app.event_manager.add_listener("method_exception_document",
                                       on_method_exception_document)

        # this shouldn't be called because:
        # 1. document isn't validated
        # 2. hence; document can't be parsed
        # 3. hence; document can't be mapped to a function
        # 4. hence; document can't be mapped to a service class
        # 5. hence; no handlers from the service class is invoked.
        # 6. hence; the h[0] == 2 check (instead of 3)
        SomeService.event_manager.add_listener("method_exception_object",
                                               on_method_exception_object)

        wsgi_app = WsgiApplication(app)

        xml_request = b"""
            <tns:some_call xmlns:tns="some_tns">
                <tns:some_str>123456</tns:some_str>
            </tns:some_call>
        """

        _ = b''.join(
            wsgi_app(
                {
                    'PATH_INFO': '/',
                    'SERVER_NAME': 'localhost',
                    'SERVER_PORT': '7000',
                    'REQUEST_METHOD': 'POST',
                    'wsgi.url_scheme': 'http',
                    'wsgi.input': BytesIO(xml_request),
                }, start_response))

        assert h[0] == 2
Beispiel #27
0
def build_app(service_list, tns, name):
    app = Application(service_list, tns, name=name,
                      in_protocol=Soap11(), out_protocol=Soap11())
    app.transport = 'http://schemas.xmlsoap.org/soap/http'
    return app
Beispiel #28
0
class QBWCService(spyne.Service):
    __target_namespace__ = 'http://developer.intuit.com/'
    __service_url_path__ = '/qwc'
    __in_protocol__ = Soap11(validator='lxml')
    __out_protocol__ = Soap11()

    @spyne.srpc(Unicode, Unicode, _returns=Array(Unicode))
    def authenticate(strUserName, strPassword):
        """Authenticate the web connector to access this service.
        @param strUserName user name to use for authentication
        @param strPassword password to use for authentication
        @return the completed array
        """
        returnArray = []
        # or maybe config should have a hash of usernames and salted hashed passwords
        if strUserName == config['qwc']['username'] and strPassword == config[
                'qwc']['password']:
            print "authenticated", time.ctime()
            session = session_manager.get_session()
            if 'ticket' in session:
                returnArray.append(session['ticket'])
                returnArray.append(
                    config['qwc']['qbwfilename']
                )  # returning the filename indicates there is a request in the queue
                returnArray.append(str(session['updatePauseSeconds']))
                returnArray.append(str(session['minimumUpdateSeconds']))
                returnArray.append(str(session['MinimumRunEveryNSeconds']))
            else:
                returnArray.append(
                    "none")  # don't return a ticket if there are no requests
                returnArray.append(
                    "none"
                )  #returning "none" indicates there are no requests at the moment
        else:
            returnArray.append(
                "no ticket"
            )  # don't return a ticket if username password does not authenticate
            returnArray.append('nvu')
        app.logger.debug('authenticate %s', returnArray)
        return returnArray

    @spyne.srpc(Unicode, _returns=Unicode)
    def clientVersion(strVersion):
        """ sends Web connector version to this service
        @param strVersion version of GB web connector
        @return what to do in case of Web connector updates itself
        """
        app.logger.debug('clientVersion %s', strVersion)
        return ""

    @spyne.srpc(Unicode, _returns=Unicode)
    def closeConnection(ticket):
        """ used by web connector to indicate it is finished with update session
        @param ticket session token sent from this service to web connector
        @return string displayed to user indicating status of web service
        """
        app.logger.debug('closeConnection %s', ticket)
        return "OK"

    @spyne.srpc(Unicode, Unicode, Unicode, _returns=Unicode)
    def connectionError(ticket, hresult, message):
        """ used by web connector to report errors connecting to Quickbooks
        @param ticket session token sent from this service to web connector
        @param hresult The HRESULT (in HEX) from the exception 
        @param message error message
        @return string done indicating web service is finished.
        """
        app.logger.debug('connectionError %s %s %s', ticket, hresult, message)
        return "done"

    @spyne.srpc(Unicode, _returns=Unicode)
    def getLastError(ticket):
        """ sends Web connector version to this service
        @param ticket session token sent from this service to web connector
        @return string displayed to user indicating status of web service
        """
        app.logger.debug('lasterror %s', ticket)
        return "Error message here!"

    @spyne.srpc(Unicode,
                Unicode,
                Unicode,
                Unicode,
                Integer,
                Integer,
                _returns=Unicode)
    def sendRequestXML(ticket, strHCPResponse, strCompanyFileName,
                       qbXMLCountry, qbXMLMajorVers, qbXMLMinorVers):
        """ send request via web connector to Quickbooks
        @param ticket session token sent from this service to web connector
        @param strHCPResponse qbXML response from QuickBooks
        @param strCompanyFileName The Quickbooks file to get the data from
        @param qbXMLCountry the country version of QuickBooks
        @param qbXMLMajorVers Major version number of the request processor qbXML 
        @param qbXMLMinorVers Minor version number of the request processor qbXML 
        @return string containing the request if there is one or a NoOp
        """
        reqXML = session_manager.send_request(ticket)
        app.logger.debug('sendRequestXML %s %s', strHCPResponse, reqXML)
        return reqXML

    @spyne.srpc(Unicode, Unicode, Unicode, Unicode, _returns=Integer)
    def receiveResponseXML(ticket, response, hresult, message):
        """ contains data requested from Quickbooks
        @param ticket session token sent from this service to web connector
        @param response qbXML response from QuickBooks
        @param hresult The HRESULT (in HEX) from any exception 
        @param message error message
        @return string done indicating web service is finished.
        """
        app.logger.debug('receiveResponseXML %s %s %s %s', ticket, response,
                         hresult, message)
        session_manager.return_response(ticket, response)
        return 10
Beispiel #29
0
class WaiterService(spyne.Service):
    """The actual waiter asynchronous service."""
    __service_url_path__ = '/Waiter'
    __in_protocol__ = Soap11(validator='soft')
    __out_protocol__ = Soap11()

    @spyne.srpc(Unicode,
                Unicode,
                Integer,
                _returns=(Unicode, Unicode),
                _out_variable_names=("status_base64", "result"))
    def startWaiter(serviceID, sessionToken, secondsToWait=300):
        """Starts a waiter script as a separate process and returns immediately.

        In a more realistic scenario, this is where a longer computation etc.
        would be started as a separate process. Here, we simply start a process
        which waits for a while while regularly updating a status file.
        """

        # Create a temporary folder to store the status files in.
        # Note that we use the service ID as a unique identifier. Since this
        # service is stateless, subsequent calls to getServiceStatus() need to
        # be able to read the correct status files. (The service can be started
        # several times in parallel.)
        # In a more realistic setting, one would set up log directories for a
        # computation here.
        waiterdir = os.path.join(WAITER_LOG_FOLDER, serviceID)
        if not os.path.exists(waiterdir):
            os.mkdir(waiterdir)
        statusfile = os.path.join(waiterdir, 'status.txt')
        resultfile = os.path.join(waiterdir, 'result.txt')

        # Spawn new process running the waiter script.
        # We pass the status and result file to the script to ensure that the
        # waiter logs to the correct place.
        command = [
            'python', 'wait_a_while.py',
            str(secondsToWait), statusfile, resultfile
        ]
        subprocess.Popen(command)

        # We now create a first status page to be displayed while the
        # workflow is executed. Since the waiter process was only just started,
        # we don't have a proper status yet. So we simply start with an empty
        # progress bar.
        # The status page needs to be base64 encoded.
        status = base64.b64encode(create_html_progressbar(0))
        result = "UNSET"

        return (status, result)

    @spyne.srpc(Unicode,
                Unicode,
                _returns=(Unicode, Unicode),
                _out_variable_names=("status_base64", "result"))
    def getServiceStatus(serviceID, sessionToken):
        """Status-query method which is called regularly by WFM.

        Here, a more realistic service would query the status of a calculation
        etc. and process its log files to create a status page. Here, the log
        contains only a single number, which we convert to an html progress
        bar.
        """
        # Create correct file paths from service ID. By using the unique
        # service ID, we can address the right waiter process in case this
        # service is called several times in parallel.
        waiterdir = os.path.join(WAITER_LOG_FOLDER, serviceID)
        statusfile = os.path.join(waiterdir, 'status.txt')
        resultfile = os.path.join(waiterdir, 'result.txt')

        # Read the current status from the waiter logs. Here, that is only a
        # single number between 0 and 100.
        with open(statusfile) as f:
            current_status = f.read().strip()

        if current_status == "100":
            status = "COMPLETED"
            # Read result page from waiter
            with open(resultfile) as f:
                result = f.read()
            return (status, result)

        # Note that the interface definition of getServiceStatus() specifies
        # "UNCHANGED" as another option for the return value of
        # 'status_base64'. In this case, the workflow manager will simply
        # continue to display the last status page transmitted. This can be
        # used when the status-page generation in itself is costly.

        # If not finished, create a status page from the current status
        # This could include more post-processing etc. in a more realistic
        # service
        result = "UNSET"
        status = base64.b64encode(create_html_progressbar(int(current_status)))
        return (status, result)

    @spyne.srpc(Unicode,
                Unicode,
                _returns=Boolean,
                _out_variable_name="success")
    def abortService(serviceID, sessionToken):
        """Aborts the currently running service (not implemented, returns false)
        """

        # This method offers the option to abort long-running asynchronous
        # services. In this example, we do not implement this functionality
        # and thus always return False.
        # In a more realistic scenario, this method would terminate the
        # background computation process gracefully.

        return False
Beispiel #30
0
def getSpyneApplications(wof_obj_1_0, wof_obj_1_1, templates=None):

    # wof_obj_1_0 = wof_1_0.WOF(dao, config_file)
    # wof_obj_1_1 = wof_1_1.WOF_1_1(dao,config_file)

    sensorNetwork = wof_obj_1_0.urlpath.replace('/', '').lower()

    soap_app_1_0 = Application(
        [wml10(wof_obj_1_0, Unicode, _SERVICE_PARAMS["s_type"])],
        tns=_SERVICE_PARAMS["wml10_tns"],
        name=sensorNetwork+'_svc_' + _SERVICE_PARAMS["wml10_soap_name"],
        in_protocol=wofSoap11(validator='lxml'),
        out_protocol=Soap11(),
    )

    rest_app_1_0 = Application(
        [wml10(wof_obj_1_0, AnyXml, _SERVICE_PARAMS["r_type"])],
        tns=_SERVICE_PARAMS["wml10_tns"],
        name=sensorNetwork+'_svc_' + _SERVICE_PARAMS["wml10_rest_name"],
        in_protocol=HttpRpc(validator='soft'),
        out_protocol=XmlDocument(),
    )

    soap_app_1_1 = Application(
        [wml11(wof_obj_1_1, Unicode, _SERVICE_PARAMS["s_type"])],
        tns=_SERVICE_PARAMS["wml11_tns"],
        name=sensorNetwork+'_svc_' + _SERVICE_PARAMS["wml11_soap_name"],
        in_protocol=wofSoap11(validator='lxml'),
        out_protocol=Soap11(),
    )

    rest_app_1_1 = Application(
        [wml11(wof_obj_1_1, AnyXml, _SERVICE_PARAMS["r_type"])],
        tns=_SERVICE_PARAMS["wml11_tns"],
        name=sensorNetwork + '_svc_' + _SERVICE_PARAMS["wml11_rest_name"],
        in_protocol=HttpRpc(validator='soft'),
        out_protocol=XmlDocument(),
    )
    # need to update template to 1_1 object.
    # <gml:Definition gml:id="methodCode-{{ method_result.MethodID  }}">
    #   File "\lib\site-packages\jinja2\environment.py", line 408, in getattr
    #     return getattr(obj, attribute)
    # UndefinedError: 'method_result' is undefined
    rest_app_2 = Application(
        [wml2(wof_obj_1_0, Unicode, _SERVICE_PARAMS["r_type"])],
        tns=_SERVICE_PARAMS["wml11_tns"],
        name=sensorNetwork + '_svc_' + _SERVICE_PARAMS["wml11_rest_name"],
        in_protocol=HttpRpc(validator='soft'),
        # out_protocol=XmlDocument(),
        out_protocol=HttpRpc(mime_type='text/xml'),

    )

    rest_wsgi_wrapper_1_0 = WsgiApplication(rest_app_1_0)
    soap_wsgi_wrapper_1_0 = WsgiApplication(soap_app_1_0)
    rest_wsgi_wrapper_1_1 = WsgiApplication(rest_app_1_1)
    soap_wsgi_wrapper_1_1 = WsgiApplication(soap_app_1_1)
    rest_wsgi_wrapper_2_0 = WsgiApplication(rest_app_2)

    spyneApps = {
        '/' + sensorNetwork+'/rest/1_0': rest_wsgi_wrapper_1_0,
        '/' + sensorNetwork+'/rest/1_1': rest_wsgi_wrapper_1_1,
        '/' + sensorNetwork+'/soap/cuahsi_1_0': soap_wsgi_wrapper_1_0,
        '/' + sensorNetwork+'/soap/cuahsi_1_1': soap_wsgi_wrapper_1_1,
        '/' + sensorNetwork+'/rest/2': rest_wsgi_wrapper_2_0,
    }

    templatesPath = None
    if templates is None:
        if wof_obj_1_1._config is not None:
            templatesPath = os.path.abspath(wof_obj_1_1._config.TEMPLATES)
    else:
        templatesPath = os.path.abspath(templates)

    if templatesPath:
        if not os.path.exists(templatesPath):
            logging.info('Templates path: {} NOT exists {}'.format(
                templatesPath,
                os.path.exists(templatesPath))
            )
            templatesPath = _TEMPLATES
            logging.info('default temnplate path: %s' % templatesPath)
        # needs to be service_baseURL. in config wof_obj_1_0.service_wsdl
        wsdl10 = WofWSDL_1_0(
            soap_wsgi_wrapper_1_0.doc.wsdl11.interface,
            templates=templatesPath,
            network=sensorNetwork,
            version=version
        )

        # soap_wsgi_wrapper_1_0._wsdl = wsdl10.build_interface_document('/'+ sensorNetwork+'/soap/wateroneflow',templatesPath) #.get_wsdl_1_0('/'+ sensorNetwork+'/soap/wateroneflow')  # noqa
        soap_wsgi_wrapper_1_0.event_manager.add_listener(
            'wsdl',
            wsdl10.on_get_wsdl_1_0_
        )
        # path: /{sensorNetwork}/soap/wateroneflow_1_1/.wsdl returns the WSDL.
        wsdl11 = WofWSDL_1_1(
            soap_wsgi_wrapper_1_1.doc.wsdl11.interface,
            templates=templatesPath,
            network=sensorNetwork,
            version=version
        )
        # soap_wsgi_wrapper_1_1._wsdl = wsdl11.build_interface_document('/'+ sensorNetwork+'/soap/wateroneflow_1_1',templatesPath) #.get_wsdl_1_0('/'+ sensorNetwork+'/soap/wateroneflow')  # noqa
        soap_wsgi_wrapper_1_1.event_manager.add_listener(
            'wsdl',
            wsdl11.on_get_wsdl_1_1_
        )

    return spyneApps