Esempio n. 1
0
    def test_local_serialize_schema(self):
        from ZSI import SoapWriter
        from ZSI import _child_elements
        from xml.dom.ext.reader import PyExpat
        msg = self.client_module.DSQueryRegistrySoapOut()
        msg.DSQueryRegistryResult = msg.new_DSQueryRegistryResult()
        msg.DSQueryRegistryResult.Any = 'hi'

        input = open('wsdl/nvo-admin.wsdl').read()
        reader = PyExpat.Reader()
        dom = reader.fromString(input)

        dnode = _child_elements(dom)[0]
        tnode = _child_elements(dnode)[0]
        snode = _child_elements(tnode)[0]

        msg.DSQueryRegistryResult.Schema = snode

        sw = SoapWriter()
        sw.serialize(msg)
        soap = str(sw)
        print(soap)

        ps = ParsedSoap(soap)
        pyobj = ps.Parse(msg.typecode)
        self.assertEqual(pyobj.DSQueryRegistryResult.Any,
                         msg.DSQueryRegistryResult.Any)
        self.assertTrue(_is_element(pyobj.DSQueryRegistryResult.Schema))
        print(_get_element_nsuri_name(pyobj.DSQueryRegistryResult.Schema))
        self.assertEqual(
            _get_element_nsuri_name(pyobj.DSQueryRegistryResult.Schema),
            ('http://www.w3.org/2001/XMLSchema', 'schema'))
    def setBody(self, body, title='', is_error=0, bogus_str_search=None):
        if isinstance(body, Fault):
            # Convert Fault object to SOAP response.
            body = body.AsSOAP()
        else:
            # Marshall our body as an SOAP response. Strings will be sent
            # strings, integers as integers, etc. We do *not* convert
            # everything to a string first.
            try:
                target = self._method
                body = premarshal(body)
                result = body
                if hasattr(result, 'typecode'):
                    tc = result.typecode
                else:
                    tc = TC.Any(aslist=1, pname=target + 'Response')
                    result = [result]
                sw = SoapWriter(nsdict={}, header=True, outputclass=None,
                        encodingStyle=None)
                body = str(sw.serialize(result, tc))
                Node.unlink(sw.dom.node)
                Node.unlink(sw.body.node)
                del sw.dom.node
                del sw.body.node
                del sw.dom
                del sw.body
            except:
                self.exception()
                return

        # Set our body to the message, and fix our MIME type.
        self._real.setBody(body)
        self._setHeader()
        return self
Esempio n. 3
0
    def test_local_serialize_schema(self):
        from ZSI import SoapWriter
        from ZSI import _child_elements
        from xml.dom.ext.reader import PyExpat
        msg = self.client_module.DSQueryRegistrySoapOut()
        msg.DSQueryRegistryResult = msg.new_DSQueryRegistryResult()
        msg.DSQueryRegistryResult.Any = 'hi'

        input = open('wsdl/nvo-admin.wsdl').read()
        reader = PyExpat.Reader()
        dom = reader.fromString(input)

        dnode =  _child_elements(dom)[0]
        tnode =  _child_elements(dnode)[0]
        snode =  _child_elements(tnode)[0]

        msg.DSQueryRegistryResult.Schema = snode

        sw = SoapWriter()
        sw.serialize(msg)
        soap = str(sw)
        print soap

        ps = ParsedSoap(soap)
        pyobj = ps.Parse(msg.typecode)
        self.failUnlessEqual(pyobj.DSQueryRegistryResult.Any, msg.DSQueryRegistryResult.Any)
        self.failUnless(_is_element(pyobj.DSQueryRegistryResult.Schema))
        print _get_element_nsuri_name(pyobj.DSQueryRegistryResult.Schema)
        self.failUnlessEqual(_get_element_nsuri_name(pyobj.DSQueryRegistryResult.Schema), (u'http://www.w3.org/2001/XMLSchema', u'schema'))
Esempio n. 4
0
def serializeRequest(request):
    tc = getattr(request, 'typecode', None)
    sw = SoapWriter(nsdict={},
                    header=True,
                    outputclass=None,
                    encodingStyle=None)
    return str(sw.serialize(request, tc))
Esempio n. 5
0
    def test_local_anyType(self):
        """rpc/lit, testing if <any/> lax content handling
        should get back dicts and strings
        """
        ps = ParsedSoap(MSG)
        pyobj = ps.Parse(self.client_module.EventApproximatesSoapOut.typecode)

        any = {'PoolTotals': {'Pool': {'Total': u'4117.66', 'ENumbers': None, 'JackpotNet': None}}, 'Approximates': {'Pool': {'Win': u'3.90,0.00,10.40,11.80,4.70,29.50,29.90,2.40,19.80,0.00', 'Place': u'1.04,0.00,2.80,5.90,2.00,5.20,7.40,1.04,4.00,0.00'}}}

        self.failUnless(pyobj.EventApproximatesResult.Any == any, 'Failed match:\n %s\n\n%s' %(
            pyobj.EventApproximatesResult.Any, any))


        pyobj.EventApproximatesResult.Any = dict(pyobj.EventApproximatesResult.Any)
        sw = SoapWriter()
        sw.serialize(pyobj)
        print str(sw)
        ps2 = ParsedSoap(str(sw))
        pyobj2 = ps.Parse(self.client_module.EventApproximatesSoapOut.typecode)
        print "EAR: ", pyobj2.EventApproximatesResult
        print "Any: ", pyobj2.EventApproximatesResult.Any


        self.failUnless(pyobj.EventApproximatesResult.Any == pyobj2.EventApproximatesResult.Any,
            'Failed match:\n %s\n\n%s' %(pyobj.EventApproximatesResult.Any, pyobj2.EventApproximatesResult.Any))
Esempio n. 6
0
    def _cache_soap(self, name, res):
        from ZSI import SoapWriter
        sw = SoapWriter()
        xml = str(sw.serialize(res))
        self._soapcache[name] = xml

        # hack to get the cache to save
        self._soapcache = self._soapcache
Esempio n. 7
0
    def AsSOAP(self, **kw):

        header = self.DataForSOAPHeader() 
        sw = SoapWriter(**kw)
        self.serialize(sw)
        if header is not None:
            sw.serialize_header(header, header.typecode, typed=False)
        return str(sw)
Esempio n. 8
0
    def AsSOAP(self, **kw):

        header = self.DataForSOAPHeader()
        sw = SoapWriter(**kw)
        self.serialize(sw)
        if header is not None:
            sw.serialize_header(header, header.typecode, typed=False)
        return str(sw)
def deserialize(objectToDeserialize):
    sw = SoapWriter(nsdict={}, header=True, outputclass=None,
                    encodingStyle=None)
    tc = TC.Any(pname=None, aslist=False)
    deserializedObject = sw.serialize(objectToDeserialize, tc).body
    root = etree.XML(str(deserializedObject))
    body = root[0]
    return etree.tostring(body, encoding='utf-8', pretty_print=True)
Esempio n. 10
0
 def check_any_dict_list_rpcenc(self):
     sw = SoapWriter()
     testObj = [{"a":1,"b":2}, {"d":4,"e":5}, {"f":{"x":9}, "g":[6,7.0]}]
     typecode = TC.Any(aslist=True)
     sw.serialize(testObj, typecode=typecode)
     xml = str(sw)
     ps = ParsedSoap(xml)
     result = TC.Any().parse(ps.body_root, ps)
     self.assertTrue(result == testObj)
Esempio n. 11
0
 def check_any_dict_list_rpcenc(self):
     sw = SoapWriter()
     testObj = [{"a":1,"b":2}, {"d":4,"e":5}, {"f":{"x":9}, "g":[6,7.0]}]
     typecode = TC.Any(aslist=True)
     sw.serialize(testObj, typecode=typecode)
     xml = str(sw)
     ps = ParsedSoap(xml)
     result = TC.Any().parse(ps.body_root, ps)
     self.failUnless(result == testObj)
Esempio n. 12
0
    def _cache_soap(self, name, res):
        from ZSI import SoapWriter

        sw = SoapWriter()
        xml = str(sw.serialize(res))
        self._soapcache[name] = xml

        # hack to get the cache to save
        self._soapcache = self._soapcache
Esempio n. 13
0
 def check_parse_empty_string(self):
     # Empty String
     typecodes = list(TC.Any.parsemap.values())
     for tc in [c for c in list(TC.Any.parsemap.values()) if isinstance(c, TC.String)]:
         sw = SoapWriter()
         sw.serialize("", typecode=tc, typed=True)
         soap = str(sw)
         ps = ParsedSoap(soap)
         parsed = ps.Parse(TC.Any())
         self.assertEqual("", parsed)
Esempio n. 14
0
def lather(obj, tc=None):
    ''' Serial a python object into SOAP, return the SOAP.
      If tc is None, expect obj to have a .typecode attribute.
  '''
    if tc is None:
        tc = obj.typecode
    IO = StringIO()
    S = SoapWriter(IO)
    S.serialize(obj, tc)
    return str(S)
Esempio n. 15
0
 def check_parse_empty_string(self):
     # Empty String
     typecodes = list(TC.Any.parsemap.values())
     for tc in [c for c in list(TC.Any.parsemap.values()) if isinstance(c, TC.String)]:
         sw = SoapWriter()
         sw.serialize("", typecode=tc, typed=True)
         soap = str(sw)
         ps = ParsedSoap(soap)
         parsed = ps.Parse(TC.Any())
         self.assertEqual("", parsed)
Esempio n. 16
0
 def check_parse_empty_all(self):
     # None
     skip = [TC.FPEnumeration, TC.Enumeration, TC.IEnumeration, TC.List, TC.Integer]
     for typeclass in [c for c in list(TC.__dict__.values()) if type(c) in [type,type] and not issubclass(c, TC.String) and issubclass(c, TC.SimpleType)]:
         if typeclass in skip: continue
         tc = typeclass()
         sw = SoapWriter()
         sw.serialize(None, typecode=tc, typed=True)
         soap = str(sw)
         ps = ParsedSoap(soap)
         parsed = ps.Parse(TC.Any())
         self.assertEqual(None, parsed)
Esempio n. 17
0
 def check_parse_empty_all(self):
     # None
     skip = [TC.FPEnumeration, TC.Enumeration, TC.IEnumeration, TC.List, TC.Integer]
     for typeclass in [c for c in list(TC.__dict__.values()) if type(c) in [type,type] and not issubclass(c, TC.String) and issubclass(c, TC.SimpleType)]:
         if typeclass in skip: continue
         tc = typeclass()
         sw = SoapWriter()
         sw.serialize(None, typecode=tc, typed=True)
         soap = str(sw)
         ps = ParsedSoap(soap)
         parsed = ps.Parse(TC.Any())
         self.assertEqual(None, parsed)
Esempio n. 18
0
 def test_local_generateMessageAttachment(self):
     """doc/lit, generating a message using MIME attachment, 
     we don't have the server side implementation so we can 
     really do a full test yet
     """
     from TestService_server import uploadFileRequest
     #stubs were properly generated
     request = uploadFileRequest()
     request._name = "TestService_client.py"
     request._attachment = open("stubs/TestService_client.py", 'r')
     sw = SoapWriter({}, header=True, outputclass=None, encodingStyle=None)
     sw.serialize(request)
     print "the request message is: " + str(sw)
Esempio n. 19
0
 def test_local_generateMessageAttachment(self):
     """doc/lit, generating a message using MIME attachment, 
     we don't have the server side implementation so we can 
     really do a full test yet
     """
     from TestService_server import uploadFileRequest
     #stubs were properly generated
     request = uploadFileRequest()
     request._name = "TestService_client.py"
     request._attachment = open("stubs/TestService_client.py", 'r')
     sw = SoapWriter({}, header=True, outputclass=None, encodingStyle=None)
     sw.serialize(request)
     print "the request message is: " + str(sw)
Esempio n. 20
0
 def AsSOAP(self, output=None, **kw):
     if output is None:
         s = StringIO.StringIO()
         output = s
     else:
         s = None
     mykw = { 'header': self.DataForSOAPHeader() }
     if kw: mykw.update(kw)
     sw = SoapWriter(output, **mykw)
     self.serialize(sw)
     sw.close()
     if s: 
         return s.getvalue()
     else:
         return None
Esempio n. 21
0
 def newFunc(kw):
     try:
         log("%s(%s)\n" % (str(oldFunc.__name__), str(kw)))
         kw = trans.transArgs(oldFunc.__name__, kw)
         res = oldFunc(**kw)
         res = fixObject(res)
         log("%s(%s) -> %s\n" % (str(oldFunc.__name__), str(kw), str(res)))
         sw = SoapWriter()
         sw.serialize(res, res.typecode)
         res = trans.transResult(oldFunc.__name__,
                                 minidom.parseString(str(sw)))
         return res
     except:
         log("%s\n" % (traceback.format_exc(sys.exc_info())))
         raise
Esempio n. 22
0
 def check_empty_array(self):
     """Empty Array returned as list()
     """
     data = []
     s = str(SoapWriter().serialize(data, TC.Any(aslist=True)))
     p = ParsedSoap(s).Parse(TC.Any())
     self.assertTrue(data == p, 'expecting "%s", got "%s"' % (data, p))
Esempio n. 23
0
    def check_any_nill(self):
        result = ['23', {'a' : None, 'b': 5}]
        soap = str(SoapWriter().serialize(result, TC.Any(pname="NilRequest", nillable=True, aslist=True)))

        ps = ParsedSoap(soap)
        tc = TC.Any(nillable=True)
        pyobj = ps.Parse(tc)
Esempio n. 24
0
 def check_empty_struct(self):
     """Empty Struct is None, maybe dict() makes more sense, but this
     is fairly hard to determine if not typed (which is the norm).
     """
     data = {}
     s = str(SoapWriter().serialize(data, TC.Any()))
     p = ParsedSoap(s).Parse(TC.Any())
     self.assertTrue(p == None, 'expecting "%s", got "%s"' % (None, p))
Esempio n. 25
0
    def test_local_anyType(self):
        """rpc/lit, testing if <any/> lax content handling
        should get back dicts and strings 
        """
        ps = ParsedSoap(MSG)
        pyobj = ps.Parse(self.client_module.EventApproximatesSoapOut.typecode)

        any = {
            'PoolTotals': {
                'Pool': {
                    'Total': u'4117.66',
                    'ENumbers': None,
                    'JackpotNet': None
                }
            },
            'Approximates': {
                'Pool': {
                    'Win':
                    u'3.90,0.00,10.40,11.80,4.70,29.50,29.90,2.40,19.80,0.00',
                    'Place':
                    u'1.04,0.00,2.80,5.90,2.00,5.20,7.40,1.04,4.00,0.00'
                }
            }
        }

        self.failUnless(
            pyobj.EventApproximatesResult.Any == any,
            'Failed match:\n %s\n\n%s' %
            (pyobj.EventApproximatesResult.Any, any))

        pyobj.EventApproximatesResult.Any = dict(
            pyobj.EventApproximatesResult.Any)
        sw = SoapWriter()
        sw.serialize(pyobj)
        print str(sw)
        ps2 = ParsedSoap(str(sw))
        pyobj2 = ps.Parse(self.client_module.EventApproximatesSoapOut.typecode)
        print "EAR: ", pyobj2.EventApproximatesResult
        print "Any: ", pyobj2.EventApproximatesResult.Any

        self.failUnless(
            pyobj.EventApproximatesResult.Any ==
            pyobj2.EventApproximatesResult.Any,
            'Failed match:\n %s\n\n%s' % (pyobj.EventApproximatesResult.Any,
                                          pyobj2.EventApproximatesResult.Any))
Esempio n. 26
0
    def check_builtins(self):
        myInt,myLong,myStr,myDate,myFloat = 123,2147483648,\
            "hello", time.gmtime(), 1.0001
        orig = [myInt, myLong, myStr, myDate, myFloat]

        sw = SoapWriter()
        sw.serialize(orig, typecode=TC.Any(pname="builtins", aslist=True))

        ps = ParsedSoap(str(sw))
        parsed = ps.Parse(TC.Any())
        self.assertEqual(len(orig), len(parsed))

        self.assertEqual(myInt, parsed[0])
        self.assertEqual(myLong, parsed[1])
        self.assertEqual(myStr, parsed[2])
        self.assertEqual(myDate[0:6], parsed[3][0:6])
        self.assertEqual(myFloat, parsed[4])

        self.assertEqual(type(myInt), type(parsed[0]))
        self.assertEqual(type(myLong), type(parsed[1]))
        self.assertEqual(type(myStr), type(parsed[2]))
        self.assertEqual(tuple, type(parsed[3]))
        self.assertEqual(type(myFloat), type(parsed[4]))
Esempio n. 27
0
    def check_builtins(self):
        myInt,myLong,myStr,myDate,myFloat = 123,2147483648,\
            "hello", time.gmtime(), 1.0001
        orig = [myInt,myLong,myStr,myDate,myFloat]

        sw = SoapWriter()
        sw.serialize(orig, typecode=TC.Any(pname="builtins", aslist=True))
        
        ps = ParsedSoap(str(sw)) 
        parsed = ps.Parse(TC.Any())
        self.assertEqual(len(orig), len(parsed))

        self.assertEqual(myInt, parsed[0])
        self.assertEqual(myLong, parsed[1])
        self.assertEqual(myStr, parsed[2])
        self.assertEqual(myDate[0:6], parsed[3][0:6])
        self.assertEqual(myFloat, parsed[4])
        
        self.assertEqual(type(myInt), type(parsed[0]))
        self.assertEqual(type(myLong), type(parsed[1]))
        self.assertEqual(type(myStr), type(parsed[2]))
        self.assertEqual(tuple, type(parsed[3]))
        self.assertEqual(type(myFloat), type(parsed[4]))
Esempio n. 28
0
    def test_local_NoMessagePart(self):
        ## msg = self.client_module.HelloRequest()
        msg = None
        rsp = self.client_module.HelloResponse()

        # Core functionality required
        s = SoapWriter()
        xml = str(s)

        print xml

        # Core functionality required
        ps = ParsedSoap(xml)

        self.failUnless(ps.body.childNodes == 0, "Empty Body expected: " + ps.body.childNodes)
        self.failUnless(ps.body_root == None, "Body root should be None: " + ps.body_root)

        pyobj = ps.Parse(None)

        self.failUnless(pyobj == None, "pyobj should be None: " + pyobj)
Esempio n. 29
0
    def checkt7(self):
        ps = ParsedSoap(text)

        tcdict = TC.Apache.Map('c-gensym1')
        tclist = TC.Apache.Map('c-gensym1', aslist=1)

        d = tcdict.parse(ps.body_root, ps)
        self.assertEqual(d, {u'a': 123, '\x00\x01': 456})
        #print 'as dictionary\n', d

        l = tclist.parse(ps.body_root, ps)
        self.assertEqual(l, [('\x00\x01', 456), (u'a', 123)])
        #print '\n', '=' * 30
        #print 'as list\n', l

        #print '\n', '=' * 30
        sw = SoapWriter()
        sw.serialize(d, tcdict)
        #print >>sys.stdout, sw

        #print '\n', '=' * 30
        sw = SoapWriter()
        sw.serialize(l, tclist)
Esempio n. 30
0
    def check_uri_quoting(self):
        """ all reserved characters used for reserved purpose.
        """
        sw1 = SoapWriter(envelope=False)
        tc1 = TC.URI("sourceforge")
        orig = "https://sourceforge.net/tracker/index.php?func=detail&aid=1520092&group_id=26590&atid=387667"
        sw1.serialize(orig, typecode=tc1, typed=False)
        s1 = str(sw1)

        sw2 = SoapWriter(envelope=False)
        tc2 = TC.String("sourceforge")
        sw2.serialize(orig, typecode=tc2, typed=False)
        s2 = str(sw2)

        #        print s1
        #        print s2
        self.failUnless(s1 == s2, "reserved characters used for reserved purpose should not be escaped.")

        ps = ParsedSoap(s2, envelope=False)
        pyobj = ps.Parse(tc2)

        self.failUnless(pyobj == orig, "parsed object should be equivalent to original")
Esempio n. 31
0
    def checkt7(self):
        ps = ParsedSoap(text)

        tcdict = TC.Apache.Map('c-gensym1')
        tclist = TC.Apache.Map('c-gensym1', aslist=1)

        d = tcdict.parse(ps.body_root, ps)
        self.assertEqual(d, { u'a':123, '\x00\x01':456 })
        #print 'as dictionary\n', d

        l = tclist.parse(ps.body_root, ps)
        self.assertEqual(l, [('\x00\x01', 456), (u'a', 123)])
        #print '\n', '=' * 30
        #print 'as list\n', l

        #print '\n', '=' * 30
        sw = SoapWriter()
        sw.serialize(d, tcdict)
        #print >>sys.stdout, sw

        #print '\n', '=' * 30
        sw = SoapWriter()
        sw.serialize(l, tclist)
                    classname = operation[0].upper() + operation[1:] + "Request"
                    try:
                        objType = getattr(SRW.types, classname)
                        xreq = objType(operation + "Request", opts=opts,
                                       config=config, protocol="SRU")
                        xreq.calledAt = path
                        result = self.call(xreq)
			style = ""
                    except AttributeError, err:
                        result = self.processUnknownOperation(operation, err, config)


            reply = StringIO.StringIO()

            if (req.method == "GET"):
                sw = SoapWriter(reply, envelope=0)	    
            else:
                sw = SoapWriter(reply, nsdict=SRW.protocolNamespaces)
            try:
                sw.serialize(result, inline=1)
                sw.close()
                text = reply.getvalue()
            except Exception, err:
                self.send_fault(Fault(Fault.Client, 'Busted (%s)' % str(err)), req)
                return

            if (req.method == "GET"):
                if xreq and hasattr(xreq, 'stylesheet') and xreq.stylesheet:
                    headerText = u'<?xml version="1.0"?>\n<?xml-stylesheet type="text/xsl" href="%s"?>\n' % (xreq.stylesheet) 
                elif xreq and hasattr(xreq, 'defaultStylesheet') and xreq.defaultStylesheet:
                    headerText = u'<?xml version="1.0"?>\n<?xml-stylesheet type="text/xsl" href="%s"?>\n' % (xreq.defaultStylesheet) 
                        objType = getattr(SRW.types, classname)
                        xreq = objType(operation + "Request",
                                       opts=opts,
                                       config=config,
                                       protocol="SRU")
                        xreq.calledAt = path
                        result = self.call(xreq)
                        style = ""
                    except AttributeError, err:
                        result = self.processUnknownOperation(
                            operation, err, config)

            reply = StringIO.StringIO()

            if (req.method == "GET"):
                sw = SoapWriter(reply, envelope=0)
            else:
                sw = SoapWriter(reply, nsdict=SRW.protocolNamespaces)
            try:
                sw.serialize(result, inline=1)
                sw.close()
                text = reply.getvalue()
            except Exception, err:
                self.send_fault(Fault(Fault.Client, 'Busted (%s)' % str(err)),
                                req)
                return

            if (req.method == "GET"):
                if xreq and hasattr(xreq, 'stylesheet') and xreq.stylesheet:
                    headerText = u'<?xml version="1.0"?>\n<?xml-stylesheet type="text/xsl" href="%s"?>\n' % (
                        xreq.stylesheet)
Esempio n. 34
0
 def processResponse(cls, output, **kw):
     sw = SoapWriter(outputclass=cls.writerClass)
     sw.serialize(output)
     return sw
Esempio n. 35
0
    def Send(self, url, opname, obj, nsdict=None, soapaction=None, **kw):
        '''Send a message.  If url is None, use the value from the
        constructor (else error). obj is the object (data) to send.
        Data may be described with a requesttypecode keyword, or a
        requestclass keyword; default is the class's typecode (if
        there is one), else Any.
        '''
            
        # Get the TC for the obj.
        if kw.has_key('requesttypecode'):
            tc = kw['requesttypecode']
        elif kw.has_key('requestclass'):
            tc = kw['requestclass'].typecode
        elif type(obj) == types.InstanceType:
            tc = getattr(obj.__class__, 'typecode')
            if tc is None: tc = TC.Any(opname, aslist=1)
        else:
            tc = TC.Any(opname, aslist=1)


        if self.op_ns:
            opname = '%s:%s' % (self.op_ns, opname)
            tc.oname = opname 

        # Determine the SOAP auth element.
        if kw.has_key('auth_header'):
            auth_header = kw['auth_header']
        elif self.auth_style & AUTH.zsibasic:
            auth_header = _AuthHeader % (self.auth_user, self.auth_pass)
        else:
            auth_header = None

        # Serialize the object.
        s = StringIO.StringIO()
        d = self.nsdict or {}
        if self.ns: d[''] = self.ns
        d.update(nsdict or self.nsdict or {})
        sw = SoapWriter(s, nsdict=d, header=auth_header)
        if kw.has_key('_args'):
            sw.serialize(kw['_args'], tc)
        else:
            sw.serialize(obj, tc, typed=0)
        sw.close()
        soapdata = s.getvalue()

        # Tracing?
        if self.trace:
            print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
            print >>self.trace, soapdata

        # Send the request.
        # host and port may be parsed from a WSDL file.  if they are, they
        # are most likely unicode format, which httplib does not care for
        if isinstance(self.host, unicode):
            self.host = str(self.host)
        if not isinstance(self.port, int):
            self.port = int(self.port)
            
        if not self.ssl:
            self.h = httplib.HTTPConnection(self.host, self.port)
        else:
            self.h = httplib.HTTPSConnection(self.host, self.port,
                        **self.ssl_files)

        self.h.connect()
        self.h.putrequest("POST", url or self.url)
        self.h.putheader("Content-length", "%d" % len(soapdata))
        self.h.putheader("Content-type", 'text/xml; charset=utf-8')
        SOAPActionValue = '"%s"' % (soapaction or self.soapaction)
        self.h.putheader("SOAPAction", SOAPActionValue)
        if self.auth_style & AUTH.httpbasic:
            val = _b64_encode(self.auth_user + ':' + self.auth_pass) \
                        .replace("\012", "")
            self.h.putheader('Authorization', 'Basic ' + val)
        for header,value in self.user_headers:
            self.h.putheader(header, value)
        self.h.endheaders()
        self.h.send(soapdata)

        # Clear prior receive state.
        self.data, self.ps = None, None
Esempio n. 36
0
	def Send(self, url, opname, obj, nsdict={}, soapaction=None, wsaction=None, 
			 endPointReference=None, soapheaders=(), **kw):
		'''Send a message.	If url is None, use the value from the
		constructor (else error). obj is the object (data) to send.
		Data may be described with a requesttypecode keyword, the default 
		is the class's typecode (if there is one), else Any.

		Try to serialize as a Struct, if this is not possible serialize an Array.  If 
		data is a sequence of built-in python data types, it will be serialized as an
		Array, unless requesttypecode is specified.

		arguments:
			url -- 
			opname -- struct wrapper
			obj -- python instance

		key word arguments:
			nsdict -- 
			soapaction --
			wsaction -- WS-Address Action, goes in SOAP Header.
			endPointReference --  set by calling party, must be an 
				EndPointReference type instance.
			soapheaders -- list of pyobj, typically w/typecode attribute.
				serialized in the SOAP:Header.
			requesttypecode -- 

		'''
		url = url or self.url
		endPointReference = endPointReference or self.endPointReference

		# Serialize the object.
		d = {}
		d.update(self.nsdict)
		d.update(nsdict)

		sw = SoapWriter(nsdict=d, header=True, outputclass=self.writerclass, 
				 encodingStyle=kw.get('encodingStyle'),)
		
		requesttypecode = kw.get('requesttypecode')
		if kw.has_key('_args'): #NamedParamBinding
			tc = requesttypecode or TC.Any(pname=opname, aslist=False)
			sw.serialize(kw['_args'], tc)
		elif not requesttypecode:
			tc = getattr(obj, 'typecode', None) or TC.Any(pname=opname, aslist=False)
			try:
				if type(obj) in _seqtypes:
					obj = dict(map(lambda i: (i.typecode.pname,i), obj))
			except AttributeError:
				# can't do anything but serialize this in a SOAP:Array
				tc = TC.Any(pname=opname, aslist=True)
			else:
				tc = TC.Any(pname=opname, aslist=False)

			sw.serialize(obj, tc)
		else:
			sw.serialize(obj, requesttypecode)
			
		for i in soapheaders:
		   sw.serialize_header(i) 
			
		# 
		# Determine the SOAP auth element.	SOAP:Header element
		if self.auth_style & AUTH.zsibasic:
			sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass),
				_AuthHeader.typecode)

		# 
		# Serialize WS-Address
		if self.wsAddressURI is not None:
			if self.soapaction and wsaction.strip('\'"') != self.soapaction:
				raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match'\
					%(self.soapaction,wsaction)

			self.address = Address(url, self.wsAddressURI)
			self.address.setRequest(endPointReference, wsaction)
			self.address.serialize(sw)

		# 
		# WS-Security Signature Handler
		if self.sig_handler is not None:
			self.sig_handler.sign(sw)

		scheme,netloc,path,nil,nil,nil = urlparse.urlparse(url)
		transport = self.transport
		if transport is None and url is not None:
			if scheme == 'https':
				transport = self.defaultHttpsTransport
			elif scheme == 'http':
				transport = self.defaultHttpTransport
			else:
				raise RuntimeError, 'must specify transport or url startswith https/http'

		# Send the request.
		if issubclass(transport, httplib.HTTPConnection) is False:
			raise TypeError, 'transport must be a HTTPConnection'

		soapdata = str(sw)
		self.h = transport(netloc, None, **self.transdict)
		self.h.connect()
		self.SendSOAPData(soapdata, url, soapaction, **kw)
Esempio n. 37
0
    def test_local_substitute_SessionManager(self):
        # BUG [ 1755740 ] Multiple calls to the same method
        MSG = """<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
 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>
<RetrieveServiceContentResponse xmlns="urn:vim2">
  <returnval>
    <rootFolder type="Folder">group-d1</rootFolder>
    <propertyCollector type="PropertyCollector">propertyCollector</propertyCollector>
    <about>
      <name>VMware VirtualCenter</name>
      <fullName>VMware VirtualCenter 2.0.1 build-32042</fullName>
      <vendor>VMware, Inc.</vendor>
      <version>2.0.1</version>
      <build>32042</build>
      <localeVersion>INTL</localeVersion>
      <localeBuild>000</localeBuild>
      <osType>win32-x86</osType>
      <productLineId>vpx</productLineId>
      <apiType>VirtualCenter</apiType>
      <apiVersion>2.0.0</apiVersion>
    </about>
    <setting type="OptionManager">VpxSettings</setting>
    <userDirectory type="UserDirectory">UserDirectory</userDirectory>
    <sessionManager type="SessionManager">SessionManager</sessionManager>
    <authorizationManager type="AuthorizationManager">AuthorizationManager</authorizationManager>
    <perfManager type="PerformanceManager">PerfMgr</perfManager>
    <scheduledTaskManager type="ScheduledTaskManager">ScheduledTaskManager</scheduledTaskManager>
    <alarmManager type="AlarmManager">AlarmManager</alarmManager>
    <eventManager type="EventManager">EventManager</eventManager>
    <taskManager type="TaskManager">TaskManager</taskManager>
    <customizationSpecManager type="CustomizationSpecManager">CustomizationSpecManager</customizationSpecManager>
    <customFieldsManager type="CustomFieldsManager">CustomFieldsManager</customFieldsManager>
    <diagnosticManager type="DiagnosticManager">DiagMgr</diagnosticManager>
    <licenseManager type="LicenseManager">LicenseManager</licenseManager>
    <searchIndex type="SearchIndex">SearchIndex</searchIndex>
  </returnval>
</RetrieveServiceContentResponse>
</soapenv:Body>
</soapenv:Envelope>"""

        # Parse it out
        ps = ParsedSoap(MSG)
        pyobj = ps.Parse(
            self.client_module.RetrieveServiceContentResponseMsg.typecode)
        sessionMgr = pyobj.Returnval.SessionManager

        # Serialize SessionManager in different context
        msg = self.client_module.LogoutRequestMsg()
        msg._this = sessionMgr
        SoapWriter().serialize(msg)

        # Parse it out: was failing
        # ZSI.EvaluateException: Element "__this" missing from complexType
        # [Element trace: /soapenv:Envelope/soapenv:Body/RetrieveServiceContentResponse/returnval]
        ps = ParsedSoap(MSG)
        pyobj = ps.Parse(
            self.client_module.RetrieveServiceContentResponseMsg.typecode)
Esempio n. 38
0
def register_results(algsynonim, password, pocketid, results):
  """Posts results to the poligon server"""
  register_request = RegisterResultSoapIn()
  register_request.AlgSynonim = algsynonim
  register_request.Password = password
  register_request.PocketKey = int(pocketid)
  
  register_request.LearnResults = register_request.new_learnResults()
  register_request.TestResults = register_request.new_testResults()
  
  for i in range(len(results)):
    
    test_result = register_request.TestResults.new_TestResult()
    learn_result = register_request.LearnResults.new_TestResult()
    
    test_result.Index = i
    learn_result.Index = i
    
    test_result.Error = results[i].Error
    test_result.ErrorException = results[i].ErrorException
    learn_result.Error = results[i].Error
    learn_result.ErrorException = results[i].ErrorException
    
    if not results[i].Error:
      test_result.Error = results[i].Test.Error
      test_result.ErrorException = results[i].Test.ErrorException
      learn_result.Error = results[i].Test.Error
      learn_result.ErrorException = results[i].Test.ErrorException
   
    # Answers
    test_result.Answers = test_result.new_Answers()
    learn_result.Answers = learn_result.new_Answers()
    
    for j in range(len(results[i].Learn.Targets)):
      learn_result.Answers.Int.append(int(results[i].Learn.Targets[j]))
    
    for j in range(len(results[i].Test.Targets)):
      test_result.Answers.Int.append(int(results[i].Test.Targets[j]))
     
    # PropertiesWeights 
    #test_result.PropertiesWeights = test_result.new_PropertiesWeights()
    #learn_result.PropertiesWeights = learn_result.new_PropertiesWeights()
    
    #for j in range(len(results[i].LearnPropertiesWeights)):
    #  learn_result.PropertiesWeights.Double.append(results[i].LearnPropertiesWeights[j])
    
    #for j in range(len(results[i].TestPropertiesWeights)):
    #  test_result.PropertiesWeights.Double.append(results[i].TestPropertiesWeights[j])
    
    # Object weights
    #test_result.ObjectsWeights = test_result.new_ObjectsWeights()
    #learn_result.ObjectsWeights = learn_result.new_ObjectsWeights()
    
    #for j in range(len(results[i].LearnObjectsWeights)):
    #  learn_result.ObjectsWeights.Double.append(results[i].LearnObjectsWeights[j])
    
    #for j in range(len(results[i].TestObjectsWeights)):
    #  test_result.ObjectsWeights.Double.append(results[i].TestObjectsWeights[j])
    
    # ProbabilityMatrix
    test_result.ProbabilityMatrix = test_result.new_ProbabilityMatrix()
    learn_result.ProbabilityMatrix = learn_result.new_ProbabilityMatrix()
    
    for vector in results[i].Test.ProbabilityMatrix:
      array = test_result.ProbabilityMatrix.new_ArrayOfDouble()
      for item in vector:
        array.Double.append(item)
      test_result.ProbabilityMatrix.ArrayOfDouble.append(array)
    
    for vector in results[i].Learn.ProbabilityMatrix:
      array = learn_result.ProbabilityMatrix.new_ArrayOfDouble()
      for item in vector:
        array.Double.append(item)
      learn_result.ProbabilityMatrix.ArrayOfDouble.append(array)      
    
    register_request.TestResults.TestResult.append(test_result)   
    register_request.LearnResults.TestResult.append(learn_result)

  try:
    sw = SoapWriter()
    sw.serialize(register_request)
    
    file = open('RegisterResult.xml', 'w')
    file.write(str(sw))
    file.close()
  except:
    logger.error('Can\'t write file results file')
  
  if REGISTER_RESULTS:
    try:
      response = service.RegisterResult(register_request, **KW)
      if response.RegisterResultResult.Status == 'Ok':
        logger.info('Results are posted successfully')
      else:
        logger.error(
          'Error occured while posting results\n{0}'.format(response.RegisterResultResult.Message.encode('unicode', 'replace')))
      return response.RegisterResultResult 
    except:
      logger.error(
        'Error occured while posting results \'{0}\'\n{1}'.format(pocketid, sys.exc_info()[0]))
    
  return None
Esempio n. 39
0
        if len(mu):
            uri, localname = mu[0]
            print >> OUT, FaultFromNotUnderstood(uri, localname).AsSOAP()
            self.fail()

        try:
            player = ps.Parse(Player)
        except EvaluateException, e:
            print >> OUT, FaultFromZSIException(e).AsSOAP()
            self.fail()

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


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


class Player:
    '''Input class.'''
Esempio n. 40
0
def _Dispatch(ps, modules, SendResponse, SendFault, nsdict={}, typesmodule=None,
              gettypecode=gettypecode, rpc=False, docstyle=False, **kw):
    '''Find a handler for the SOAP request in ps; search modules.
    Call SendResponse or SendFault to send the reply back, appropriately.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                result = handler(**kwarg)

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

        sw = SoapWriter(nsdict=nsdict)
        sw.serialize(result, tc)
        return SendResponse(str(sw), **kw)
    except Fault as e:
        return SendFault(e, **kw)
    except Exception as e:
        # Something went wrong, send a fault.
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
Esempio n. 41
0
 def processResponse(cls, output, **kw):
     sw = SoapWriter(outputclass=cls.writerClass)
     sw.serialize(output)
     return sw
            else:
                length = int(self.headers['content-length'])
                ps = ParsedSoap(self.rfile.read(length))
        except ParseException, e:
            ConsumerServer.logger.error(str(e))
            self.send_fault(FaultFromZSIException(e))
            return
        except Exception, e:
            ConsumerServer.logger.error(str(e))
            self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
            return
        
        try:
            self.handleNotify(ps.body_root)
            #TODO: missing namespace cemon_consumer
            sw = SoapWriter(nsdict=NSTable)
            sw.serialize(Notify(), Notify.typecode)
            sw.close()
            self.send_xml(str(sw))
        except Exception, e:
            ConsumerServer.logger.error(str(e))
            import traceback
            traceback.print_tb(sys.exc_info()[2])
            self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
            
class ConnectionFixer(object):
    """ wraps a socket connection so it implements makefile """
    def __init__(self, conn):
        self.__conn = conn
    def makefile(self, mode, bufsize):
       return socket._fileobject(self.__conn, mode, bufsize)
    def Send(self, url, opname, obj, nsdict={}, soapaction=None, wsaction=None, 
             endPointReference=None, **kw):
        '''Send a message.  If url is None, use the value from the
        constructor (else error). obj is the object (data) to send.
        Data may be described with a requesttypecode keyword, or a
        requestclass keyword; default is the class's typecode (if
        there is one), else Any.

        Optional WS-Address Keywords
            wsaction -- WS-Address Action, goes in SOAP Header.
            endPointReference --  set by calling party, must be an 
                EndPointReference type instance.

        '''
        url = url or self.url
        # Get the TC for the obj.
        if kw.has_key('requesttypecode'):
            tc = kw['requesttypecode']
        elif kw.has_key('requestclass'):
            tc = kw['requestclass'].typecode
        elif type(obj) == types.InstanceType:
            tc = getattr(obj.__class__, 'typecode')
            if tc is None: tc = TC.Any(opname, aslist=1)
        else:
            tc = TC.Any(opname, aslist=1)

        endPointReference = endPointReference or self.endPointReference

        # Serialize the object.
        d = {}

        d.update(self.nsdict)
        d.update(nsdict)

        useWSAddress = self.wsAddressURI is not None
        sw = SoapWriter(nsdict=d, header=True, outputclass=self.writerclass, 
                 encodingStyle=kw.get('encodingStyle'),)
        if kw.has_key('_args'):
            sw.serialize(kw['_args'], tc)
        else:
            sw.serialize(obj, tc)

        # Determine the SOAP auth element.  SOAP:Header element
        if self.auth_style & AUTH.zsibasic:
            sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass),
                _AuthHeader.typecode)

        # Serialize WS-Address
        if useWSAddress is True:
            if self.soapaction and wsaction.strip('\'"') != self.soapaction:
                raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match'\
                    %(self.soapaction,wsaction)
            self.address = Address(url, self.wsAddressURI)
            self.address.setRequest(endPointReference, wsaction)
            self.address.serialize(sw)

        # WS-Security Signature Handler
        if self.sig_handler is not None:
            self.sig_handler.sign(sw)
        soapdata = str(sw)

        scheme,netloc,path,nil,nil,nil = urlparse.urlparse(url)

        # self.transport httplib.HTTPConnection derived class set-up removed
        # from HERE - this now handled by urllib2.urlopen()
        self.SendSOAPData(soapdata, url, soapaction, **kw)
Esempio n. 44
0
    def Send(self,
             url,
             opname,
             obj,
             nsdict={},
             soapaction=None,
             wsaction=None,
             endPointReference=None,
             soapheaders=(),
             **kw):
        '''Send a message.  If url is None, use the value from the
        constructor (else error). obj is the object (data) to send.
        Data may be described with a requesttypecode keyword, the default 
        is the class's typecode (if there is one), else Any.

        Try to serialize as a Struct, if this is not possible serialize an Array.  If 
        data is a sequence of built-in python data types, it will be serialized as an
        Array, unless requesttypecode is specified.

        arguments:
            url -- 
            opname -- struct wrapper
            obj -- python instance

        key word arguments:
            nsdict -- 
            soapaction --
            wsaction -- WS-Address Action, goes in SOAP Header.
            endPointReference --  set by calling party, must be an 
                EndPointReference type instance.
            soapheaders -- list of pyobj, typically w/typecode attribute.
                serialized in the SOAP:Header.
            requesttypecode -- 

        '''
        url = url or self.url
        endPointReference = endPointReference or self.endPointReference

        # Serialize the object.
        d = {}
        d.update(self.nsdict)
        d.update(nsdict)

        sw = SoapWriter(
            nsdict=d,
            header=True,
            outputclass=self.writerclass,
            encodingStyle=kw.get('encodingStyle'),
        )

        requesttypecode = kw.get('requesttypecode')
        if kw.has_key('_args'):  #NamedParamBinding
            tc = requesttypecode or TC.Any(pname=opname, aslist=False)
            sw.serialize(kw['_args'], tc)
        elif not requesttypecode:
            tc = getattr(obj, 'typecode', None) or TC.Any(pname=opname,
                                                          aslist=False)
            try:
                if type(obj) in _seqtypes:
                    obj = dict(map(lambda i: (i.typecode.pname, i), obj))
            except AttributeError:
                # can't do anything but serialize this in a SOAP:Array
                tc = TC.Any(pname=opname, aslist=True)
            else:
                tc = TC.Any(pname=opname, aslist=False)

            sw.serialize(obj, tc)
        else:
            sw.serialize(obj, requesttypecode)

        for i in soapheaders:
            sw.serialize_header(i)

        #
        # Determine the SOAP auth element.  SOAP:Header element
        if self.auth_style & AUTH.zsibasic:
            sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass),
                                _AuthHeader.typecode)

        #
        # Serialize WS-Address
        if self.wsAddressURI is not None:
            if self.soapaction and wsaction.strip('\'"') != self.soapaction:
                raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match'\
                    %(self.soapaction,wsaction)

            self.address = Address(url, self.wsAddressURI)
            self.address.setRequest(endPointReference, wsaction)
            self.address.serialize(sw)

        #
        # WS-Security Signature Handler
        if self.sig_handler is not None:
            self.sig_handler.sign(sw)

        scheme, netloc, path, nil, nil, nil = urlparse.urlparse(url)
        transport = self.transport
        if transport is None and url is not None:
            if scheme == 'https':
                transport = self.defaultHttpsTransport
            elif scheme == 'http':
                transport = self.defaultHttpTransport
            else:
                raise RuntimeError, 'must specify transport or url startswith https/http'

        # Send the request.
        if issubclass(transport, httplib.HTTPConnection) is False:
            raise TypeError, 'transport must be a HTTPConnection'

        soapdata = str(sw)
        self.h = transport(netloc, None, **self.transdict)
        self.h.connect()
        self.SendSOAPData(soapdata, url, soapaction, **kw)