コード例 #1
0
ファイル: __init__.py プロジェクト: evandeaubl/suds
    def encryptMessage(self, env, use_encrypted_header=False, second_pass=False):
        encrypted_parts = second_pass and self.second_pass_encrypted_parts or self.encrypted_parts
        elements_to_encrypt = []
        encrypted_headers = []

        for elements_to_encrypt_func in encrypted_parts:
            addl_elements = elements_to_encrypt_func(env)
            if addl_elements[0] is None:
                continue
            if not isinstance(addl_elements[0], list):
                addl_elements = ([addl_elements[0]], addl_elements[1])
            for element in addl_elements[0]:
                if element not in elements_to_encrypt:
                    if element[0].parent.match("Header") and use_encrypted_header:
                        enc_hdr = Element("EncryptedHeader", ns=wsse11ns)
                        element[0].parent.replaceChild(element[0], enc_hdr)
                        enc_hdr.append(element[0])
                        elements_to_encrypt.append((enc_hdr, "Content"))
                        encrypted_headers.append(enc_hdr)
                    else:
                        elements_to_encrypt.append((element, addl_elements[1]))

        ref_list = xmlsec.encryptMessage(
            self.cert, self.symmetricKey, elements_to_encrypt, "#" + self.keyId, self.keyReference, self.keyTransport
        )

        for enc_hdr in encrypted_headers:
            enc_hdr.set("wsu:Id", enc_hdr[0].get("Id"))
            enc_hdr[0].unset("Id")
        if self.includeRefList:
            self.encryptedKey.append(ref_list)
            return self.encryptedKey
        else:
            return (self.encryptedKey, ref_list)
コード例 #2
0
ファイル: delete-items.py プロジェクト: kinghuang/itsm
	def main(self):
		items = self.adsm_lists.service.GetListItems(self.args.list, self.args.view).listitems.data.row

		method_idx = 1
		batch = Element('Batch')\
		       .append(Attribute('OnError', 'Continue'))\
		       .append(Attribute('ListVersion', 1))

		def update(b):
			if not self.args.d:
				updates = Element('ns1:updates').append(b)
				print self.adsm_lists.service.UpdateListItems(listName=self.args.list, updates=updates)

		for item in items:
			method = Element('Method')\
			        .append(Attribute('ID', method_idx))\
			        .append(Attribute('Cmd', 'Delete'))\
			        .append(Element('Field')\
			          .append(Attribute('Name', 'ID'))\
			          .setText(item['_ows_ID']))
			batch.append(method)
			print method
			method_idx += 1

			if len(batch) > 20:
				update(batch)
				batch.detachChildren()

		if len(batch) > 0:
			update(batch)
コード例 #3
0
def init_client(faults=True):
    ENTREPRISE_WSDL = getattr(settings,     'SALESFORCE_ENTERPRISE_WSDL')
    DJANGO_WSDL = getattr(settings,         'SALESFORCE_DJANGO_WSDL')
    SALESFORCE_ENDPOINT = getattr(settings, 'SALESFORCE_ENDPOINT')
    
    SALESFORCE_USER = getattr(settings,     'SALESFORCE_USER')
    SALESFORCE_PASS = getattr(settings,     'SALESFORCE_PASS')
    SALESFORCE_TOKEN = getattr(settings,    'SALESFORCE_TOKEN')
    
    # Use the entreprise login to get a session id
    entreprise_client = Client(ENTREPRISE_WSDL)
    #entreprise_client.wsdl.url = SALESFORCE_ENDPOINT
    
    login_result = entreprise_client.service.login(SALESFORCE_USER, 
                                                   SALESFORCE_PASS+SALESFORCE_TOKEN)
    

    # our client specific methods are in this specific       
   
    # NOTE we have to create the endpoint url using values from the serverUrl in the loginResponse plus 
    # the djangoAdapter schema
    
    options = urlparse(login_result.serverUrl)
    
    #DJANGO_SF_ENDPOINT = '%s://%s/services/Soap/class/dJangoAdapter' % (options.scheme, options.netloc)
    
    django_client = Client(DJANGO_WSDL, location = SALESFORCE_ENDPOINT, faults=faults)
         
    session_name_space = ('djan', 'http://soap.sforce.com/schemas/class/dJangoAdapter')
    session = Element('sessionId').setText(login_result.sessionId)
    wrapper = Element('SessionHeader')
    wrapper.append(session)
    
    django_client.set_options(soapheaders=wrapper)
    return django_client
コード例 #4
0
ファイル: slsoap.py プロジェクト: enygma/slsoap
 def set_auth_header(self):
     """Set up the authorization header"""
     auth_user = Element("username").setText(self.api_user)
     auth_key = Element("apiKey").setText(self.api_key)
     auth_header = Element("authenticate", ns=self.ims_ns)
     auth_header.children = [auth_user, auth_key]
     return auth_header
コード例 #5
0
ファイル: WSA_spoof.py プロジェクト: zsmahi/WS-Amplification
def testWSDL(wsdlURL):
  replyURL = 'http://wsamplification.appspot.com/?webservice=' + wsdlURL
  try:
    client = Client(wsdlURL)    
    wsans = ('wsa', 'http://schemas.xmlsoap.org/ws/2004/08/addressing')
    wsaReply = Element('ReplyTo', ns=wsans)
    wsaAddress = Element('Address', ns=wsans).setText(replyURL)
    wsaReply.insert(wsaAddress)
  except:
    print 'Moving on...'
    return
  try:
    client.set_options(soapheaders=wsaReply) 
    #impl = getattr(client.service, 'submitOrderNoAck')
    #print impl()
    for method in client.wsdl.services[0].ports[0].methods.values():
      print method.name
      result = getattr(client.service, method.name)()
      #print result()
  except suds.WebFault as detail:
    print 'Invoking method failed'
    print client
  except:
    print 'Derping...'
    print client
コード例 #6
0
ファイル: client.py プロジェクト: sirsgriffin/pymarketo
    def marshalled(self, context):
        userid = self.userid
        timestamp = rfc3339(datetime.datetime.now())
        secret = self.secret
        signature = sign(secret, timestamp+userid)
        auth = self.authfragment % locals()
        envelope = context.envelope

        #Set the right ns prefixes
        envelope.nsprefixes[ 'ns1' ] = envelope.nsprefixes[ 'ns0' ]
        envelope.clearPrefix( 'ns0' )

        #Add our auth to the header element
        header = envelope.getChild('Header')
        authns = Element( 'ns1:AuthenticationHeader' )
        authns.append( Element( 'mktowsUserId' ).setText(self.userid) )
        authns.append( Element( 'requestSignature' ).setText(signature) )
        authns.append( Element( 'requestTimestamp' ).setText(timestamp) )
        header.append( authns )

        #Set the proper body prefixes
        body = envelope.getChild( 'Body' )
        body.prefix = 'SOAP-ENV'
        body.children[0].prefix = 'ns1'

        if self.debug:
            with open("/tmp/envelope.txt","w") as f: f.write(envelope.str())
コード例 #7
0
ファイル: slsoap.py プロジェクト: enygma/slsoap
 def set_object_mask(self, data):
     """Create an object mask to tell the API what we want"""
     print "%sObjectMask" % self.object_type
     el = Element("%sObjectMask" % self.object_type, ns=self.ims_ns)
     mask = Element("mask")
     mask = self.build_soap_header(mask, data)
     el.children = [mask]
     return el
コード例 #8
0
    def to_xml(self, factory):
        # Needs to be an xsd:int with an attribute
        # Can't do that with factory.create('ns0:quantity')
        #metadata = factory.resolver.find('ns0:quantity')
        #ns = metadata.namespace()

        element = Element('ns0:quantity')
        element.setText(str(self.value))
        element.set('unitOfMeasure', self.unit)
        return element
コード例 #9
0
ファイル: literal.py プロジェクト: bigbang4u2/mywork
 def node(self, content):
     ns = content.type.namespace()
     if content.type.form_qualified:
         node = Element(content.tag, ns=ns)
         node.addPrefix(ns[0], ns[1])
     else:
         node = Element(content.tag)
     self.encode(node, content)
     log.debug('created - node:\n%s', node)
     return node
コード例 #10
0
ファイル: wsse.py プロジェクト: BhallaLab/moose-gui
 def xml(self):
     """
     Get xml representation of the object.
     @return: The root node.
     @rtype: L{Element}
     """
     root = Element('Security', ns=wssens)
     root.set('mustUnderstand', str(self.mustUnderstand).lower())
     for t in self.tokens:
         root.append(t.xml())
     return root
コード例 #11
0
ファイル: binding.py プロジェクト: propars/python-suds
 def header(self, content):
     """
     Build the B{<Body/>} for an soap outbound message.
     @param content: The header content.
     @type content: L{Element}
     @return: the soap body fragment.
     @rtype: L{Element}
     """
     header = Element('Header', ns=envns)
     header.append(content)
     return header
コード例 #12
0
ファイル: binding.py プロジェクト: propars/python-suds
 def body(self, content):
     """
     Build the B{<Body/>} for an soap outbound message.
     @param content: The body content.
     @type content: L{Element}
     @return: the soap body fragment.
     @rtype: L{Element}
     """
     body = Element('Body', ns=envns)
     body.append(content)
     return body
コード例 #13
0
ファイル: client.py プロジェクト: a1ph4g33k/zuora-client
 def set_session(self, session_id):
     """
     Record the session info.
     """
     self.session = session_id
     self.session_expiration = datetime.now() + timedelta(
         seconds=self.session_duration)
     session_namespace = ('ns1', 'http://api.zuora.com/')
     session = Element('session', ns=session_namespace).setText(session_id)
     header = Element('SessionHeader', ns=session_namespace)
     header.append(session)
     self.client.set_options(soapheaders=[header])
コード例 #14
0
ファイル: core.py プロジェクト: Infinidat/pyvisdk
 def connect(self):
     from .client import SmsClient
     from suds.sax.element import Element
     self.client = SmsClient(self._vim.server_fqdn)
     session = eval(list(self._vim.client.client.options.transport.cookiejar)[0].value)
     cookie = Element("vcSessionCookie")
     cookie.setText(session)
     self.client.wsdl.options.__pts__.set("soapheaders", cookie)
     ref = Property('ServiceInstance')
     ref._type = 'ServiceInstance'
     self.service_instance = SmsServiceInstance(self, name='ServiceInstance', ref=ref)
     self.connected = True
コード例 #15
0
ファイル: doctor.py プロジェクト: chalkchisel/suds
 def add(self, root):
     """
     Add an <xs:import/> to the specified schema root.
     @param root: A schema root.
     @type root: L{Element}
     """
     node = Element('import', ns=self.xsdns)
     node.set('namespace', self.ns)
     if self.location is not None:
         node.set('schemaLocation', self.location)
     log.debug('%s inserted', node)
     root.insert(node) 
コード例 #16
0
ファイル: parser.py プロジェクト: tic-ull/defensatfc-proto
 def startElement(self, name, attrs):
     top = self.top()
     node = Element(unicode(name), parent=top)
     for a in attrs.getNames():
         n = unicode(a)
         v = unicode(attrs.getValue(a))
         attribute = Attribute(n,v)
         if self.mapPrefix(node, attribute):
             continue
         node.append(attribute)
     top.append(node)
     self.push(node)
コード例 #17
0
ファイル: wsse.py プロジェクト: BhallaLab/moose-gui
 def xml(self):
     root = Element("Timestamp", ns=wsuns)
     created = Element('Created', ns=wsuns)
     created.setText(str(DateTime(self.created)))
     expires = Element('Expires', ns=wsuns)
     expires.setText(str(DateTime(self.expires)))
     root.append(created)
     root.append(expires)
     return root
コード例 #18
0
ファイル: binding.py プロジェクト: EASYMARKETING/suds-jurko
    def body(self, content):
        """
        Build the B{<Body/>} for a SOAP outbound message.

        @param content: The body content.
        @type content: L{Element}
        @return: The SOAP body fragment.
        @rtype: L{Element}

        """
        body = Element("Body", ns=envns)
        body.append(content)
        return body
コード例 #19
0
ファイル: parser.py プロジェクト: USGM/suds
 def startElement(self, name, attrs):
     top = self.top()
     node = Element(str(name))
     for a in attrs.getNames():
         n = str(a)
         v = str(attrs.getValue(a))
         attribute = Attribute(n,v)
         if self.mapPrefix(node, attribute):
             continue
         node.append(attribute)
     node.charbuffer = []
     top.append(node)
     self.push(node)
コード例 #20
0
ファイル: __init__.py プロジェクト: evandeaubl/suds
 def xml(self):
     root = Element("Timestamp", ns=wsuns)
     # xsd:datetime format does not have fractional seconds
     created = Element("Created", ns=wsuns)
     created.setText(str(UTC(self.created - timedelta(microseconds=self.created.microsecond))))
     expires = Element("Expires", ns=wsuns)
     expires.setText(str(UTC(self.expires - timedelta(microseconds=self.expires.microsecond))))
     root.append(created)
     root.append(expires)
     return root
コード例 #21
0
ファイル: literal.py プロジェクト: dvska/suds-htj
 def node(self, content):
     #
     # Create an XML node and namespace qualify as defined
     # by the schema (elementFormDefault).
     #
     ns = content.type.namespace()
     if content.type.form_qualified:
         node = Element(content.tag, ns=ns)
         node.addPrefix(ns[0], ns[1])
     else:
         node = Element(content.tag)
     self.encode(node, content)
     log.debug('created - node:\n%s', node)
     return node
コード例 #22
0
ファイル: mouser.py プロジェクト: chintal/tendril
 def _build_mouser_header(self):
     header_partnerid = Element('PartnerID').setText(self._api_key)
     header_accountinfo = Element('AccountInfo')
     header_accountinfo.insert(header_partnerid)
     header = Element('MouserHeader')
     header.insert(header_accountinfo)
     header.set('xmlns', 'http://api.mouser.com/service')
     return header
コード例 #23
0
ファイル: slsoap.py プロジェクト: enygma/slsoap
    def build_soap_header(self, el, data):
        """Set up a SOAP object for our headers"""
        ## make our first element
        for name in data:
            if type(data[name]) is dict:
                ## append to the current element
                nel = Element(name)
                el.children.append(nel)
                self.build_soap_header(nel, data[name])
            else:
                opt = Element(name)
                opt.setText(data[name])
                el.children.append(opt)
                # print "{name} - {data}".format(name=name,data=data[name])

        return el
コード例 #24
0
def describe_vehicle_failure2(vin):
    """This fails because there is a bug related when prettyxml is False
    https://fedorahosted.org/suds/ticket/432
    """
    client = Client(CHROME_URL)

    account_info = client.factory.create('AccountInfo')
    account_info._number = CHROME_ACCOUNT_NUMBER
    account_info._secret = CHROME_ACCOUNT_SECRET
    account_info._country = 'US'
    account_info._language = 'en'

    vin_element = Element('vin', ns=('ns1', 'urn:description7a.services.chrome.com'))
    vin_element.setText(vin)

    result = client.service.describeVehicle(account_info, vin_element)
    print result
コード例 #25
0
ファイル: doctor.py プロジェクト: chalkchisel/suds
 def apply(self, root):
     """
     Apply the import (rule) to the specified schema.
     If the schema does not already contain an import for the
     I{namespace} specified here, it is added.
     @param root: A schema root.
     @type root: L{Element}
     """
     if not self.filter.match(root, self.ns):
         return
     if self.exists(root):
         return
     node = Element('import', ns=self.xsdns)
     node.set('namespace', self.ns)
     if self.location is not None:
         node.set('schemaLocation', self.location)
     log.debug('inserting: %s', node)
     root.insert(node)
コード例 #26
0
ファイル: literal.py プロジェクト: JieNanMAXIV/edna-mx
    def node(self, content):
        """
        Create an XML node.

        The XML node is namespace qualified as defined by the corresponding
        schema element.

        """
        ns = content.type.namespace()
        if content.type.form_qualified:
            node = Element(content.tag, ns=ns)
            if ns[0]:
                node.addPrefix(ns[0], ns[1])
        else:
            node = Element(content.tag)
        self.encode(node, content)
        log.debug("created - node:\n%s", node)
        return node
コード例 #27
0
ファイル: __init__.py プロジェクト: evandeaubl/suds
 def xml(self, wsse):
     """
     Get xml representation of the object.
     @return: The root node.
     @rtype: L{Element}
     """
     root = Element("Security", ns=wssens)
     root.set("mustUnderstand", "true")
     if wsse.includeTimestamp and wsse.headerLayout != HEADER_LAYOUT_LAX_TIMESTAMP_LAST:
         root.append(Timestamp().xml())
     for t in wsse.tokens:
         root.append(UsernameToken(t.username, t.password, t.includenonce).xml())
     if wsse.includeTimestamp and wsse.headerLayout == HEADER_LAYOUT_LAX_TIMESTAMP_LAST:
         root.append(Timestamp().xml())
     return root
コード例 #28
0
 def to_xml(self, factory):
     # make sure the namespace is set to the correct one
     metadata = factory.resolver.find('ns0:totalVatAmount')
     element = Element("totalVatAmount", ns=metadata.namespace())
     element.setText(str(int(self.value * 100)))
     element.set('rate', self.rate)
     element.set('currency', self.currency)
     return element
コード例 #29
0
 def to_xml(self, factory):
     # Dear Docdata: apparently, reusing Vat was not possible..?
     #node = factory.create('ns0:totalVatAmount') does not support setting text.
     element = Element('ns0:totalVatAmount')
     element.setText(str(int(self.value * 100)))
     element.set('rate', self.rate)
     element.set('currency', self.currency)
     return element
コード例 #30
0
ファイル: client.py プロジェクト: zhaisw/FuelSDK-Python
    def build_soap_client(self):
        if self.soap_endpoint is None or not self.soap_endpoint:
            self.soap_endpoint = self.get_soap_endpoint()

        self.soap_client = suds.client.Client(self.wsdl_file_url, faults=False, cachingpolicy=1)
        self.soap_client.set_options(location=self.soap_endpoint)
        self.soap_client.set_options(headers={'user-agent' : 'FuelSDK-Python-v1.3.0'})

        if self.use_oAuth2_authentication == 'True':
            element_oAuth = Element('fueloauth', ns=('etns', 'http://exacttarget.com'))
            element_oAuth.setText(self.authToken);
            self.soap_client.set_options(soapheaders=(element_oAuth))
        else:
            element_oAuth = Element('oAuth', ns=('etns', 'http://exacttarget.com'))
            element_oAuthToken = Element('oAuthToken').setText(self.internalAuthToken)
            element_oAuth.append(element_oAuthToken)
            self.soap_client.set_options(soapheaders=(element_oAuth))

            security = suds.wsse.Security()
            token = suds.wsse.UsernameToken('*', '*')
            security.tokens.append(token)
            self.soap_client.set_options(wsse=security)
コード例 #31
0
ファイル: wsse.py プロジェクト: pitcons/suds-ng
 def xml(self):
     """
     Get xml representation of the object.
     @return: The root node.
     @rtype: L{Element}
     """
     root = Element('Security', ns=wssens)
     root.set('mustUnderstand', str(self.mustUnderstand).lower())
     for t in self.tokens:
         root.append(t.xml())
     return root
コード例 #32
0
ファイル: sapi.py プロジェクト: atamanje/SPENVIS_NG_py
    def login(self):

        url = "/".join([
            self.globalconfig["baseURL"], self.globalconfig["webservice"],
            self.globalconfig["webservicefile"]
        ])
        clientlogin = Client(url)
        token = clientlogin.service.authenticate(
            username=self.globalconfig["username"],
            password=self.globalconfig["password"])

        ssnns = (self.globalconfig["ns"], self.globalconfig["mainurl"])
        ssn = Element('SecureToken', ns=ssnns).setText(token)

        self.ssn = ssn

        return ssn
コード例 #33
0
    def setUp(self):
	url = 'http://localhost:8080/tmis-ws-laboratory/tmis-laboratory-integration?wsdl'
        self.client = Client(url, username='', password='', cache=None)
        
        medipadWsUrl = 'http://localhost:8080/tmis-ws-medipad/tmis-medipad?wsdl'
        self.medipadClient = Client(medipadWsUrl, username='', password='', cache=None)
        
        # Authenticate
        authenticator = Authenticator()
        authData = authenticator.asAdmin()

        # Add auth headers
        tmisAuthNS = ('ta', 'http://korus.ru/tmis/auth')
        authHeader = Element('tmisAuthToken', ns=tmisAuthNS).setText(authData.authToken.id)
        self.medipadClient.set_options(soapheaders=authHeader)
        
        db.initialize()
コード例 #34
0
    def augment_metadata(self, entities, board='departures', **kwargs):
        station_entities = []
        for entity in entities:
            if not entity.identifiers.get('crs'):
                continue
            station_entities.append(entity)

        station_entities = station_entities[:self._max_results]
        if not station_entities:
            return
        
        try:
            ldb = suds.client.Client(self._WSDL_URL, soapheaders=Element('AccessToken').insert(Element('TokenValue').setText(self._token)))
        except Exception, e:
            logger.warning("Could not instantiate suds client for live departure board.", exc_info=True, extra={'wsdl_url': self._WSDL_URL})
            self._add_error(station_entities)
            return
コード例 #35
0
ファイル: doctor.py プロジェクト: 571451370/devstack_mitaka
 def add(self, root):
     """
     Add an <xs:import/> to the specified schema root.
     @param root: A schema root.
     @type root: L{Element}
     """
     node = Element('import', ns=self.xsdns)
     node.set('namespace', self.ns)
     if self.location is not None:
         node.set('schemaLocation', self.location)
     log.debug('%s inserted', node)
     root.insert(node)
コード例 #36
0
 def get_suds_element(suds_obj, element_name):
     "Build a suds Element based on a suds-encoded response variable"
     el = Element(element_name)
     for node in suds_obj:
         left = node[0]
         right = node[1]
         # Attributes start with _
         if left[:1] == '_':
             el.set(left[1:], str(right))
         # Otherwise it's a subelement
         else:
             if type(right) is list:
                 for item in right:
                     sub = get_suds_element(item, str(left))
                     el.append(sub)
             else:
                 sub = get_suds_element(right, str(left))
                 el.append(sub)
     return el
コード例 #37
0
    def __init__(self, wsdl=None, api_key=None, timeout=5):
        """
        Constructor

        Keyword arguments:
        wsdl -- the URL of the Darwin LDB WSDL document. Will fall back to using the DARWIN_WEBSERVICE_WSDL environment variable if not supplied
        api_key -- a valid API key for the Darwin LDB webservice. Will fall back to the DARWIN_WEBSERVICE_API_KEY if not supplied
        timeout -- a timeout in seconds for calls to the LDB Webservice (default 5)
        """
        if not wsdl:
            wsdl = os.environ['DARWIN_WEBSERVICE_WSDL']
        if not api_key:
            api_key = os.environ['DARWIN_WEBSERVICE_API_KEY']
        self._soap_client = Client(wsdl)
        self._soap_client.set_options(timeout=timeout)
        #build soap headers
        token3 = Element('AccessToken', ns=DARWIN_WEBSERVICE_NAMESPACE)
        token_value = Element('TokenValue', ns=DARWIN_WEBSERVICE_NAMESPACE)
        token_value.setText(api_key)
        token3.append(token_value)
        self._soap_client.set_options(soapheaders=(token3))
コード例 #38
0
 def node(self, content):
     #
     # Create an XML node and namespace qualify as defined
     # by the schema (elementFormDefault).
     #
     ns = content.type.namespace()
     if content.type.form_qualified:
         node = Element(content.tag, ns=ns)
         node.addPrefix(ns[0], ns[1])
     else:
         node = Element(content.tag)
     self.encode(node, content)
     log.debug('created - node:\n%s', node)
     return node
コード例 #39
0
ファイル: wsdl.py プロジェクト: ziaa/suds-jurko
 def build_schema(self):
     """Process L{Types} objects and create the schema collection."""
     loaded_schemata = {}
     container = SchemaCollection(self)
     for t in (t for t in self.types if t.local()):
         for root in t.contents():
             schema = Schema(root, self.url, self.options, loaded_schemata, container)
             container.add(schema)
     if not container:
         root = Element.buildPath(self.root, "types/schema")
         schema = Schema(root, self.url, self.options, loaded_schemata, container)
         container.add(schema)
     self.schema = container.load(self.options, loaded_schemata)
     #TODO: Recheck this XSD schema merging. XSD schema imports are not
     # supposed to be transitive. They only allow the importing schema to
     # reference entities from the imported schema, but do not include them
     # as their own content.
     for s in (t.schema() for t in self.types if t.imported()):
         self.schema.merge(s)
     return self.schema
コード例 #40
0
ファイル: gateway.py プロジェクト: tahaghazy/django-oscar-2.0
    def to_xml(self, factory):
        # Needs to be an xsd:int with an attribute. Suds is not
        # responding nicely with basic types combined with attributes, so
        # we can't do that with factory.create('ns0:quantity')
        #
        # See also:
        # https://stackoverflow.com/questions/13103023/how-can-i-assign-a-value-to-a-factory-created-simpletype-object-with-python-suds

        # make sure the namespace is set to the correct one
        metadata = factory.resolver.find('ns0:quantity')
        element = Element("quantity", ns=metadata.namespace())

        element.setText(str(self.value))
        element.set('unitOfMeasure', self.unit)
        return element
コード例 #41
0
 def __init__(self, key):
     """
     input - 'key' - your unique access token.
     """
     self.key = key
     self.url = 'https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2017-10-01'
     self.namespace = ('ns2',
                       'http://thalesgroup.com/RTTI/2013-11-28/Token/types')
     self.header = Element('AccessToken', ns=self.namespace)
     header_val = Element('TokenValue',
                          ns=self.namespace,
                          parent=self.header)
     header_val.setText(key)
     self.header.append(header_val)
     self.__client = Client(self.url)
     self.__client.set_options(soapheaders=self.header)
コード例 #42
0
ファイル: Polarion.py プロジェクト: akashagarwal/qPaaS
    def __init__(self, url, username, password, query):
        self.url = url
        self.username = username
        self.password = password
        self.query = query  #project.id:ProjectPeriod AND type:defect
        self.connected = True

        self.session = Client(
            self.url +
            '/ws/services/SessionWebService?wsdl')  #http://10.0.0.1/polarion
        try:
            self.session.service.logIn(self.username, self.password)
            header_regex = re.compile('<ns1:sessionID.+>(.*)</ns1:sessionID')
            m = header_regex.search(self.session.last_received().str())
            sessionId = m.group(1)
            session_ns = ('ns1', 'http://ws.polarion.com/session')
            self.sessionId = Element('sessionID',
                                     ns=session_ns).setText(sessionId)
        except:
            logger.error('Can not get the issues from ' + self.url +
                         ' with the username ' + self.username)
            self.connected = False
コード例 #43
0
ファイル: doctor.py プロジェクト: 571451370/devstack_mitaka
 def apply(self, root):
     """
     Apply the import (rule) to the specified schema.
     If the schema does not already contain an import for the
     I{namespace} specified here, it is added.
     @param root: A schema root.
     @type root: L{Element}
     """
     if not self.filter.match(root, self.ns):
         return
     if self.exists(root):
         return
     node = Element('import', ns=self.xsdns)
     node.set('namespace', self.ns)
     if self.location is not None:
         node.set('schemaLocation', self.location)
     log.debug('inserting: %s', node)
     root.insert(node)
コード例 #44
0
    def node(self, content):
        """
        Create an XML node.

        The XML node is namespace qualified as defined by the corresponding
        schema element.

        """
        ns = content.type.namespace()
        if content.type.form_qualified:
            node = Element(content.tag, ns=ns)
            if ns[0]:
                node.addPrefix(ns[0], ns[1])
        else:
            node = Element(content.tag)
        self.encode(node, content)
        log.debug("created - node:\n%s", node)
        return node
コード例 #45
0
 def node(self, content):
     """
     Create and return an XML node that is qualified
     using the I{type}.  Also, make sure all referenced namespace
     prefixes are declared.
     @param content: The content for which proccessing has ended.
     @type content: L{Object}
     @return: A new node.
     @rtype: L{Element}
     """
     ns = content.type.namespace()
     if content.type.form_qualified:
         node = Element(content.tag, ns=ns)
         node.addPrefix(ns[0], ns[1])
     else:
         node = Element(content.tag)
     self.encode(node, content)
     log.debug('created - node:\n%s', node)
     return node
コード例 #46
0
ファイル: glasses_guide.py プロジェクト: socotra/public
def get_gg_details(nvic, username, password):

    url = "http://eurotaxglasswebservices.com.au/GeneralGGWebService.asmx?WSDL"

    imp = Import('http://www.w3.org/2001/XMLSchema',
                 location='http://www.w3.org/2001/XMLSchema.xsd')
    imp.filter.add('http://microsoft.com/webservices/')

    client = Client(url, doctor=ImportDoctor(imp))

    code = Element('Username').setText(username)
    pwd = Element('Password').setText(password)

    reqsoapheader = Element('AuthHeader').insert(code)
    reqsoapheader = reqsoapheader.append(pwd)
    reqsoap_attribute = Attribute('xmlns', "http://microsoft.com/webservices/")
    reqsoapheader.append(reqsoap_attribute)
    client.set_options(soapheaders=reqsoapheader)
    # print client   # shows the details of this service

    result = client.service.GetDetailsSpecificationAll('A', nvic)
    details = result.diffgram.NewDataSet.DataSepcDetails
    # print details
    return details
コード例 #47
0
ファイル: __init__.py プロジェクト: analytehealth/suds
    def encryptMessage(self,
                       env,
                       use_encrypted_header=False,
                       second_pass=False):
        encrypted_parts = second_pass and self.second_pass_encrypted_parts or self.encrypted_parts
        elements_to_encrypt = []
        encrypted_headers = []

        for elements_to_encrypt_func in encrypted_parts:
            addl_elements = elements_to_encrypt_func(env)
            if addl_elements[0] is None:
                continue
            if not isinstance(addl_elements[0], list):
                addl_elements = ([addl_elements[0]], addl_elements[1])
            for element in addl_elements[0]:
                if element not in elements_to_encrypt:
                    if element[0].parent.match(
                            'Header') and use_encrypted_header:
                        enc_hdr = Element('EncryptedHeader', ns=wsse11ns)
                        element[0].parent.replaceChild(element[0], enc_hdr)
                        enc_hdr.append(element[0])
                        elements_to_encrypt.append((enc_hdr, 'Content'))
                        encrypted_headers.append(enc_hdr)
                    else:
                        elements_to_encrypt.append((element, addl_elements[1]))

        ref_list = xmlsec.encryptMessage(self.cert, self.symmetricKey,
                                         elements_to_encrypt, '#' + self.keyId,
                                         self.keyReference, self.keyTransport)

        for enc_hdr in encrypted_headers:
            enc_hdr.set('wsu:Id', enc_hdr[0].get('Id'))
            enc_hdr[0].unset('Id')
        if self.includeRefList:
            self.encryptedKey.append(ref_list)
            return self.encryptedKey
        else:
            return (self.encryptedKey, ref_list)
コード例 #48
0
ファイル: wsse.py プロジェクト: XdasKrall/TestingWebServices
 def xml(self):
     if self.digest and self.password is None:
         raise RuntimeError("Cannot generate password digest without the password.")
     if self.autosetnonce:
         self.setnonce()
     if self.autosetcreated:
         self.setcreated()
     root = Element('UsernameToken', ns=WSSENS)
     u = Element('Username', ns=WSSENS)
     u.setText(self.username)
     root.append(u)
     if self.password is not None:
         password = self.password
         if self.digest:
             password = self.get_digest()
         p = Element('Password', ns=WSSENS)
         p.setText(password)
         p.set('Type', DIGEST_TYPE if self.digest else TEXT_TYPE)
         root.append(p)
     if self.nonce is not None:
         n = Element('Nonce', ns=WSSENS)
         n.setText(base64.encodestring(self.nonce)[:-1])
         n.set('EncodingType', BASE64_ENC_TYPE)
         root.append(n)
     if self.created:
         c = Element('Created', ns=WSUNS)
         c.setText(iso_utc(self.created))
         root.append(c)
     return root
コード例 #49
0
class Document:
    """ An XML Document """

    DECL = '<?xml version="1.0" encoding="UTF-8"?>'

    def __init__(self, root=None):
        """
        @param root: A root L{Element} or name used to build
            the document root element.
        @type root: (L{Element}|str|None)
        """
        self.__root = None
        self.append(root)

    def root(self):
        """
        Get the document root element (can be None)
        @return: The document root.
        @rtype: L{Element}
        """
        return self.__root

    def append(self, node):
        """
        Append (set) the document root.
        @param node: A root L{Element} or name used to build
            the document root element.
        @type node: (L{Element}|str|None)
        """
        if isinstance(node, basestring):
            self.__root = Element(node)
            return
        if isinstance(node, Element):
            self.__root = node
            return

    def getChild(self, name, ns=None, default=None):
        """
        Get a child by (optional) name and/or (optional) namespace.
        @param name: The name of a child element (may contain prefix).
        @type name: basestring
        @param ns: An optional namespace used to match the child.
        @type ns: (I{prefix}, I{name})
        @param default: Returned when child not-found.
        @type default: L{Element}
        @return: The requested child, or I{default} when not-found.
        @rtype: L{Element}
        """
        if self.__root is None:
            return default
        if ns is None:
            prefix, name = splitPrefix(name)
            if prefix is None:
                ns = None
            else:
                ns = self.__root.resolvePrefix(prefix)
        if self.__root.match(name, ns):
            return self.__root
        else:
            return default

    def childAtPath(self, path):
        """
        Get a child at I{path} where I{path} is a (/) separated
        list of element names that are expected to be children.
        @param path: A (/) separated list of element names.
        @type path: basestring
        @return: The leaf node at the end of I{path}
        @rtype: L{Element}
        """
        if self.__root is None:
            return None
        if path[0] == '/':
            path = path[1:]
        path = path.split('/',1)
        if self.getChild(path[0]) is None:
            return None
        if len(path) > 1:
            return self.__root.childAtPath(path[1])
        else:
            return self.__root

    def childrenAtPath(self, path):
        """
        Get a list of children at I{path} where I{path} is a (/) separated
        list of element names that are expected to be children.
        @param path: A (/) separated list of element names.
        @type path: basestring
        @return: The collection leaf nodes at the end of I{path}
        @rtype: [L{Element},...]
        """
        if self.__root is None:
            return []
        if path[0] == '/':
            path = path[1:]
        path = path.split('/',1)
        if self.getChild(path[0]) is None:
            return []
        if len(path) > 1:
            return self.__root.childrenAtPath(path[1])
        else:
            return [self.__root,]

    def getChildren(self, name=None, ns=None):
        """
        Get a list of children by (optional) name and/or (optional) namespace.
        @param name: The name of a child element (may contain prefix).
        @type name: basestring
        @param ns: An optional namespace used to match the child.
        @type ns: (I{prefix}, I{name})
        @return: The list of matching children.
        @rtype: [L{Element},...]
        """
        if name is None:
            matched = self.__root
        else:
            matched = self.getChild(name, ns)
        if matched is None:
            return []
        else:
            return [matched,]

    def str(self):
        """
        Get a string representation of this XML document.
        @return: A I{pretty} string.
        @rtype: basestring
        """
        s = []
        s.append(self.DECL)
        root = self.root()
        if root is not None:
            s.append('\n')
            s.append(root.str())
        return ''.join(s)

    def plain(self):
        """
        Get a string representation of this XML document.
        @return: A I{plain} string.
        @rtype: basestring
        """
        s = []
        s.append(self.DECL)
        root = self.root()
        if root is not None:
            s.append(root.plain())
        return ''.join(s)

    def __unicode__(self):
        return self.str()
コード例 #50
0
 def create(cls, definitions):
     root = Element('types', ns=wsdlns)
     definitions.root.insert(root)
     return Types(root, definitions)
コード例 #51
0
 def xml(self):
     """
     Get xml representation of the object.
     @return: The root node.
     @rtype: L{Element}
     """
     root = Element('UsernameToken', ns=wssens)
     u = Element('Username', ns=wssens)
     u.setText(self.username)
     root.append(u)
     p = Element('Password', ns=wssens)
     p.setText(self.password)
     root.append(p)
     if self.nonce is not None:
         n = Element('Nonce', ns=wssens)
         n.setText(self.nonce)
         root.append(n)
     if self.created is not None:
         n = Element('Created', ns=wsuns)
         n.setText(self.created.isoformat())
         root.append(n)
     return root
コード例 #52
0
ファイル: wsse.py プロジェクト: XdasKrall/TestingWebServices
 def xml(self):
     self.created = datetime.utcnow()
     root = Element("Timestamp", ns=WSUNS)
     created = Element('Created', ns=WSUNS)
     created.setText(iso_utc(self.created))
     root.append(created)
     if self.validity is not None:
         self.expires = self.created + timedelta(seconds=self.validity)
         expires = Element('Expires', ns=WSUNS)
         expires.setText(iso_utc(self.expires))
         root.append(expires)
     return root
コード例 #53
0
ファイル: appender.py プロジェクト: EnetModa/suds-philpem
 def __init__(self, content):
     Element.__init__(self, content.name, content.parent)
     self.__content = content
コード例 #54
0
ファイル: token.py プロジェクト: robsonschmidt/homeassistant
    def xml(self):
        """
		Get xml representation of the object.
		@return: The root node.
		@rtype: L{Element}
		"""
        root = Element('UsernameToken', ns=wssens)

        u = Element('Username', ns=wssens)
        u.setText(self.username)
        root.append(u)

        p = Element('Password', ns=wssens)
        p.setText(self.generate_digest())
        p.set(wspassd[0], wspassd[1])
        root.append(p)

        n = Element('Nonce', ns=wssens)
        nonce_bytes = self.nonce
        if not isinstance(self.nonce, bytes):
            nonce_bytes = self.nonce.encode('utf-8')

        n.setText(base64.encodebytes(nonce_bytes)[:-1])
        n.set(wsenctype[0], wsenctype[1])
        root.append(n)

        n = Element('Created', ns=wsuns)
        n.setText(self.created)
        root.append(n)

        self.reset()
        return root
コード例 #55
0
        exit(8)
    print 'Found', num_layers, 'layers'
    if not_found_layer1:
        print 'Layer 1 not found!'
        exit(9)
    if not_found_layer2:
        print 'Layer 2 not found!'
        exit(10)

    print 'GetLayers: OK'

    layers = [layer1, layer2]

    #####  CREATE MODEL
    ###################################
    mod_params = Element('ModelParameters')
    mod_params.applyns((None, 'http://openmodeller.cria.org.br/xml/1.0'))
    sampler = Element('Sampler')
    env = Element('Environment')
    # Layers
    for ref_layer in layers:
        map_element = Element('Map')
        map_element.set('Id', ref_layer)
        env.append(map_element)
    # Mask
    mask_element = Element('Mask')
    mask_element.set('Id', layer1)
    env.append(mask_element)
    sampler.append(env)
    # Points
    presence = Element('Presence')
コード例 #56
0
def test_init_name(name, expected_prefix, expected_name):
    e = Element(name)
    assert e.prefix == expected_prefix
    assert e.name == expected_name
コード例 #57
0
    def _marshallSObjects(self, sObjects, tag='sObjects'):
        '''
    Marshall generic sObjects into a list of SAX elements
  
    This code is going away ASAP

    tag param is for nested objects (e.g. MergeRequest) where 
    key: object must be in <key/>, not <sObjects/>
    '''
        if not isinstance(sObjects, (tuple, list)):
            sObjects = (sObjects, )
        if sObjects[0].type in [
                'LeadConvert', 'SingleEmailMessage', 'MassEmailMessage'
        ]:
            nsPrefix = 'tns:'
        else:
            nsPrefix = 'ens:'

        li = []
        for obj in sObjects:
            el = Element(tag)
            el.set('xsi:type', nsPrefix + obj.type)
            for k, v in obj:
                if k == 'type':
                    continue

                # This is here to avoid 'duplicate values' error when setting a field in fieldsToNull
                # Even a tag like <FieldName/> will trigger it
                if v == None:
                    # not going to win any awards for variable-naming scheme here
                    tmp = Element(k)
                    tmp.set('xsi:nil', 'true')
                    el.append(tmp)
                elif isinstance(v, (list, tuple)):
                    for value in v:
                        el.append(Element(k).setText(value))
                elif isinstance(v, suds.sudsobject.Object):
                    el.append(self._marshallSObjects(v, k))
                else:
                    el.append(Element(k).setText(v))

            li.append(el)
        return li
コード例 #58
0
 def test_missing(self):
     root = Element("root")
     result = root.childAtPath("an invalid path")
     assert result is None
コード例 #59
0
 def test_backslash_in_name(self):
     root, a, _, _ = self.__create_single_branch("root", "a", "b", "c")
     b_c = Element("b\\c")
     a.append(b_c)
     result = root.childAtPath("a/b\\c")
     assert result is b_c