class XMLNS:
    BASE        = "http://www.w3.org/2000/xmlns/"
    XML         = "http://www.w3.org/XML/1998/namespace"
    HTML        = "http://www.w3.org/TR/REC-html40" WSA = WSA200408 WSA_LIST = (WSA200508, WSA200408, WSA200403, WSA200303) WSAW_LIST = (WSAW200605,) class WSRF_V1_2:
    '''OASIS WSRF Specifications Version 1.2
    '''
    class LIFETIME:
        XSD_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceLifetime-1.2-draft-01.xsd"
        XSD_DRAFT4 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceLifetime-1.2-draft-04.xsd"

        WSDL_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceLifetime-1.2-draft-01.wsdl"
        WSDL_DRAFT4 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceLifetime-1.2-draft-04.wsdl"
        LATEST = WSDL_DRAFT4
        WSDL_LIST = (WSDL_DRAFT1, WSDL_DRAFT4)
        XSD_LIST = (XSD_DRAFT1, XSD_DRAFT4)

    class PROPERTIES:
        XSD_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.xsd"
        XSD_DRAFT5 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceProperties-1.2-draft-05.xsd"

        WSDL_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.wsdl"
        WSDL_DRAFT5 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceProperties-1.2-draft-05.wsdl"
        LATEST = WSDL_DRAFT5
        WSDL_LIST = (WSDL_DRAFT1, WSDL_DRAFT5)
        XSD_LIST = (XSD_DRAFT1, XSD_DRAFT5)

    class BASENOTIFICATION:
        XSD_DRAFT1 = "http://docs.oasis-open.org/wsn/2004/06/wsn-WS-BaseNotification-1.2-draft-01.xsd"

        WSDL_DRAFT1 = "http://docs.oasis-open.org/wsn/2004/06/wsn-WS-BaseNotification-1.2-draft-01.wsdl"
        LATEST = WSDL_DRAFT1
        WSDL_LIST = (WSDL_DRAFT1,)
        XSD_LIST = (XSD_DRAFT1,)

    class BASEFAULTS:
        XSD_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-BaseFaults-1.2-draft-01.xsd"
        XSD_DRAFT3 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-BaseFaults-1.2-draft-03.xsd"
        #LATEST = DRAFT3
        #WSDL_LIST = (WSDL_DRAFT1, WSDL_DRAFT3)
        XSD_LIST = (XSD_DRAFT1, XSD_DRAFT3) WSRF = WSRF_V1_2 class Collection(UserDict):
    """Helper class for maintaining ordered named collections."""
    default = lambda self,k: k.name
    def __init__(self, parent, key=None):
        UserDict.__init__(self)
        self.parent = weakref.ref(parent)
        self.list = []
        self._func = key or self.default

    def __getitem__(self, key):
        if isinstance(key, int):
            return self.list[key]
        return self.data[key]

    def __setitem__(self, key, item):
        item.parent = weakref.ref(self)
        self.list.append(item)
        self.data[key] = item

    def iterkeys(self):
        for i in self.list:
            yield self._func(i)
    
    def iteritems(self):
        for i in self.list:
            yield (self._func(i), i)

    def itervalues(self):
        for l in self.list:
            yield l

    def keys(self):
        return [self._func(i) for i in self.list]

    def items(self):
        return [(self._func(i), i) for i in self.list]

    def values(self):
        return self.list class CollectionNS(UserDict):
    """Helper class for maintaining ordered named collections."""
    default = lambda self,k: k.name
    def __init__(self, parent, key=None):
        UserDict.__init__(self)
        self.parent = weakref.ref(parent)
        self.targetNamespace = None
        self.list = []
        self._func = key or self.default

    def __getitem__(self, key):
        self.targetNamespace = self.parent().targetNamespace
        if isinstance(key, int):
            return self.list[key]
        elif self.__isSequence(key):
            nsuri,name = key
            return self.data[nsuri][name]
        return self.data[self.parent().targetNamespace][key]

    def __setitem__(self, key, item):
        item.parent = weakref.ref(self)
        self.list.append(item)
        targetNamespace = getattr(item, 'targetNamespace', self.parent().targetNamespace)
        if targetNamespace not in self.data:
            self.data[targetNamespace] = {}
        self.data[targetNamespace][key] = item

    def __isSequence(self, key):
        return (isinstance(key, (tuple, list)) and len(key) == 2)

    def keys(self):
        keys = []
        for tns in self.data.iterkeys():
            keys.append([(tns,self._func(i)) for i in self.data[tns].itervalues()])
        return keys

    def items(self):
        return [(self._func(i), i) for i in self.list]

    def values(self):
        return self.list class DOM:
    """The DOM singleton defines a number of XML related constants and
       provides a number of utility methods for DOM related tasks. It
       also provides some basic abstractions so that the rest of the
       package need not care about actual DOM implementation in use."""

    # Namespace stuff related to the SOAP specification.

    NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
    NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'

    NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
    NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'

    NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
    NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)

    NS_SOAP_ENV = NS_SOAP_ENV_1_1
    NS_SOAP_ENC = NS_SOAP_ENC_1_1

    _soap_uri_mapping = {
        NS_SOAP_ENV_1_1 : '1.1',
        NS_SOAP_ENV_1_2 : '1.2',
    }

    SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
    SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
    SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
    
    def SOAPUriToVersion(self, uri):
        """Return the SOAP version related to an envelope uri."""
        value = self._soap_uri_mapping.get(uri)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported SOAP envelope uri: %s' % uri
            )

    def GetSOAPEnvUri(self, version):
        """Return the appropriate SOAP envelope uri for a given
           human-friendly SOAP version string (e.g. '1.1')."""
           
        attrname = 'NS_SOAP_ENV_%s' % version.replace('.', '_')
        value = getattr(self, attrname, None)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported SOAP version: %s' % version
            )

    def GetSOAPEncUri(self, version):
        """Return the appropriate SOAP encoding uri for a given
           human-friendly SOAP version string (e.g. '1.1')."""
        attrname = 'NS_SOAP_ENC_%s' % version.replace('.', '_')
        value = getattr(self, attrname, None)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported SOAP version: %s' % version
            )

    def GetSOAPActorNextUri(self, version):
        """Return the right special next-actor uri for a given
           human-friendly SOAP version string (e.g. '1.1')."""
        attrname = 'SOAP_ACTOR_NEXT_%s' % version.replace('.', '_')
        value = getattr(self, attrname, None)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported SOAP version: %s' % version
            )


    # Namespace stuff related to XML Schema.

    NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
    NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'    

    NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
    NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'    

    NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
    NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'

    NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
    NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)

    NS_XSD = NS_XSD_01
    NS_XSI = NS_XSI_01

    _xsd_uri_mapping = {
        NS_XSI_99 : NS_XSD_99,
        NS_XSI_00 : NS_XSD_00,
        NS_XSI_01 : NS_XSD_01,
    }


    def InstanceUriForSchemaUri(self, uri):
        """Return the appropriate matching XML Schema instance uri for
           the given XML Schema namespace uri."""
        return self._xsd_uri_mapping.get(uri)

    def SchemaUriForInstanceUri(self, uri):
        """Return the appropriate matching XML Schema namespace uri for
           the given XML Schema instance namespace uri."""
        return self._xsd_uri_mapping.get(uri)


    # Namespace stuff related to WSDL.

    NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
    NS_WSDL_ALL = (NS_WSDL_1_1,)
    NS_WSDL = NS_WSDL_1_1

    NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
    NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
    NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'

    NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
    NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
    NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)

    NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
    NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
    NS_MIME_BINDING = NS_MIME_BINDING_1_1

    NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
    NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
    NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
    

    _wsdl_uri_mapping = {
        NS_WSDL_1_1 : '1.1',
    }
    
    def WSDLUriToVersion(self, uri):
        """Return the WSDL version related to a WSDL namespace uri."""
        value = self._wsdl_uri_mapping.get(uri)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported SOAP envelope uri: %s' % uri
            )

    def GetWSDLUri(self, version):
        attr = 'NS_WSDL_%s' % version.replace('.', '_')
        value = getattr(self, attr, None)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported WSDL version: %s' % version
            )

    def GetWSDLSoapBindingUri(self, version):
        attr = 'NS_SOAP_BINDING_%s' % version.replace('.', '_')
        value = getattr(self, attr, None)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported WSDL version: %s' % version
            )

    def GetWSDLHttpBindingUri(self, version):
        attr = 'NS_HTTP_BINDING_%s' % version.replace('.', '_')
        value = getattr(self, attr, None)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported WSDL version: %s' % version
            )

    def GetWSDLMimeBindingUri(self, version):
        attr = 'NS_MIME_BINDING_%s' % version.replace('.', '_')
        value = getattr(self, attr, None)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported WSDL version: %s' % version
            )

    def GetWSDLHttpTransportUri(self, version):
        attr = 'NS_SOAP_HTTP_%s' % version.replace('.', '_')
        value = getattr(self, attr, None)
        if value is not None:
            return value
        raise ValueError(
            'Unsupported WSDL version: %s' % version
            )


    # Other xml namespace constants.
    NS_XMLNS     = 'http://www.w3.org/2000/xmlns/'



    def isElement(self, node, name, nsuri=None):
        """Return true if the given node is an element with the given
           name and optional namespace uri."""
        if node.nodeType != node.ELEMENT_NODE:
            return 0
        return node.localName == name and \
               (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))

    def getElement(self, node, name, nsuri=None, default=old_join):
        """Return the first child of node with a matching name and
           namespace uri, or the default if one is provided."""
        nsmatch = self.nsUriMatch
        ELEMENT_NODE = node.ELEMENT_NODE
        for child in node.childNodes:
            if child.nodeType == ELEMENT_NODE:
                if ((child.localName == name or name is None) and
                    (nsuri is None or nsmatch(child.namespaceURI, nsuri))
                    ):
                    return child
        if default is not old_join:
            return default
        raise KeyError(name)

    def getElementById(self, node, _id, default=old_join):
        """Return the first child of node matching an id reference."""
        attrget = self.getAttr
        ELEMENT_NODE = node.ELEMENT_NODE
        for child in node.childNodes:
            if child.nodeType == ELEMENT_NODE:
                if attrget(child, 'id') == _id:
                    return child
        if default is not old_join:
            return default
        raise KeyError

    def getMappingById(self, document, depth=None, element=None,
                       mapping=None, level=1):
        """Create an id -> element mapping of those elements within a
           document that define an id attribute. The depth of the search
           may be controlled by using the (1-based) depth argument."""
        if document is not None:
            element = document.documentElement
            mapping = {}
        attr = element._attrs.get('id', None)
        if attr is not None:
            mapping[attr.value] = element
        if depth is None or depth > level:
            level = level + 1
            ELEMENT_NODE = element.ELEMENT_NODE
            for child in element.childNodes:
                if child.nodeType == ELEMENT_NODE:
                    self.getMappingById(None, depth, child, mapping, level)
        return mapping        

    def getElements(self, node, name, nsuri=None):
        """Return a sequence of the child elements of the given node that
           match the given name and optional namespace uri."""
        nsmatch = self.nsUriMatch
        result = []
        ELEMENT_NODE = node.ELEMENT_NODE
        for child in node.childNodes:
            if child.nodeType == ELEMENT_NODE:
                if ((child.localName == name or name is None) and (
                    (nsuri is None) or nsmatch(child.namespaceURI, nsuri))):
                    result.append(child)
        return result

    def hasAttr(self, node, name, nsuri=None):
        """Return true if element has attribute with the given name and
           optional nsuri. If nsuri is not specified, returns true if an
           attribute exists with the given name with any namespace."""
        if nsuri is None:
            if node.hasAttribute(name):
                return True
            return False
        return node.hasAttributeNS(nsuri, name)

    def getAttr(self, node, name, nsuri=None, default=old_join):
        """Return the value of the attribute named 'name' with the
           optional nsuri, or the default if one is specified. If
           nsuri is not specified, an attribute that matches the
           given name will be returned regardless of namespace."""
        if nsuri is None:
            result = node._attrs.get(name, None)
            if result is None:
                for item in node._attrsNS.iterkeys():
                    if item[1] == name:
                        result = node._attrsNS[item]
                        break
        else:
            result = node._attrsNS.get((nsuri, name), None)
        if result is not None:
            return result.value
        if default is not old_join:
            return default
        return ''

    def getAttrs(self, node):
        """Return a Collection of all attributes 
        """
        attrs = {}
        for k,v in node._attrs.iteritems():
            attrs[k] = v.value
        return attrs

    def getElementText(self, node, preserve_ws=None):
        """Return the text value of an xml element node. Leading and trailing
           whitespace is stripped from the value unless the preserve_ws flag
           is passed with a true value."""
        result = []
        for child in node.childNodes:
            nodetype = child.nodeType
            if nodetype == child.TEXT_NODE or \
               nodetype == child.CDATA_SECTION_NODE:
                result.append(child.nodeValue)
        value = ''.join(result)
        if preserve_ws is None:
            value = value.strip()
        return value

    def findNamespaceURI(self, prefix, node):
        """Find a namespace uri given a prefix and a context node."""
        attrkey = (self.NS_XMLNS, prefix)
        DOCUMENT_NODE = node.DOCUMENT_NODE
        ELEMENT_NODE = node.ELEMENT_NODE
        while 1:
            if node is None:
                raise DOMException('Value for prefix %s not found.' % prefix)
            if node.nodeType != ELEMENT_NODE:
                node = node.parentNode
                continue
            result = node._attrsNS.get(attrkey, None)
            if result is not None:
                return result.value
            if hasattr(node, '__imported__'):
                raise DOMException('Value for prefix %s not found.' % prefix)
            node = node.parentNode
            if node.nodeType == DOCUMENT_NODE:
                raise DOMException('Value for prefix %s not found.' % prefix)

    def findDefaultNS(self, node):
        """Return the current default namespace uri for the given node."""
        attrkey = (self.NS_XMLNS, 'xmlns')
        DOCUMENT_NODE = node.DOCUMENT_NODE
        ELEMENT_NODE = node.ELEMENT_NODE
        while 1:
            if node.nodeType != ELEMENT_NODE:
                node = node.parentNode
                continue
            result = node._attrsNS.get(attrkey, None)
            if result is not None:
                return result.value
            if hasattr(node, '__imported__'):
                raise DOMException('Cannot determine default namespace.')
            node = node.parentNode
            if node.nodeType == DOCUMENT_NODE:
                raise DOMException('Cannot determine default namespace.')

    def findTargetNS(self, node):
        """Return the defined target namespace uri for the given node."""
        attrget = self.getAttr
        DOCUMENT_NODE = node.DOCUMENT_NODE
        ELEMENT_NODE = node.ELEMENT_NODE
        while 1:
            if node.nodeType != ELEMENT_NODE:
                node = node.parentNode
                continue
            result = attrget(node, 'targetNamespace', default=None)
            if result is not None:
                return result
            node = node.parentNode
            if node.nodeType == DOCUMENT_NODE:
                raise DOMException('Cannot determine target namespace.')

    def getTypeRef(self, element):
        """Return (namespaceURI, name) for a type attribue of the given
           element, or None if the element does not have a type attribute."""
        typeattr = self.getAttr(element, 'type', default=None)
        if typeattr is None:
            return None
        parts = typeattr.split(':', 1)
        if len(parts) == 2:
            nsuri = self.findNamespaceURI(parts[0], element)
        else:
            nsuri = self.findDefaultNS(element)
        return (nsuri, parts[1])

    def importNode(self, document, node, deep=0):
        """Implements (well enough for our purposes) DOM node import."""
        nodetype = node.nodeType
        if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
            raise DOMException('Illegal node type for importNode')
        if nodetype == node.ENTITY_REFERENCE_NODE:
            deep = 0
        clone = node.cloneNode(deep)
        self._setOwnerDoc(document, clone)
        clone.__imported__ = 1
        return clone

    def _setOwnerDoc(self, document, node):
        node.ownerDocument = document
        for child in node.childNodes:
            self._setOwnerDoc(document, child)

    def nsUriMatch(self, value, wanted, strict=0, tt=tuple):
        """Return a true value if two namespace uri values match."""
        if value == wanted or isinstance(wanted, tt) and value in wanted:
            return 1
        if not strict and value is not None:
            wanted = isinstance(wanted, tt) and wanted or (wanted,)
            value = value[-1:] != '/' and value or value[:-1]
            for item in wanted:
                if item == value or item[:-1] == value:
                    return 1
        return 0

    def createDocument(self, nsuri, qname, doctype=None):
        """Create a new writable DOM document object."""
        impl = xml.dom.minidom.getDOMImplementation()
        return impl.createDocument(nsuri, qname, doctype)

    def loadDocument(self, data):
        """Load an xml file from a file-like object and return a DOM
           document instance."""
        return xml.dom.minidom.parse(data)

    def loadFromURL(self, url):
        """Load an xml file from a URL and return a DOM document."""
        if isfile(url) is True:
            f = open(url, 'r')
        else:
            f = urlopen(url)

        try:     
            result = self.loadDocument(f)
        except Exception, ex:
            f.close()
            raise ParseError(('Failed to load document %s' %url,) + ex.args)
        else:
            f.close()
        return result DOM = DOM() class ElementProxy(Base, MessageInterface):
    '''
    '''
    _soap_env_prefix = 'SOAP-ENV'
    _soap_enc_prefix = 'SOAP-ENC'
    _zsi_prefix = 'ZSI'
    _xsd_prefix = 'xsd'
    _xsi_prefix = 'xsi'
    _xml_prefix = 'xml'
    _xmlns_prefix = 'xmlns'

    _soap_env_nsuri = SOAP.ENV
    _soap_enc_nsuri = SOAP.ENC
    _zsi_nsuri = ZSI_SCHEMA_URI
    _xsd_nsuri =  SCHEMA.XSD3
    _xsi_nsuri = SCHEMA.XSI3
    _xml_nsuri = XMLNS.XML
    _xmlns_nsuri = XMLNS.BASE

    standard_ns = {\
        _xml_prefix:_xml_nsuri,
        _xmlns_prefix:_xmlns_nsuri
    }
    reserved_ns = {\
        _soap_env_prefix:_soap_env_nsuri,
        _soap_enc_prefix:_soap_enc_nsuri,
        _zsi_prefix:_zsi_nsuri,
        _xsd_prefix:_xsd_nsuri,
        _xsi_prefix:_xsi_nsuri,
    }
    name = None
    namespaceURI = None

    def __init__(self, sw, message=None):
        '''Initialize. 
           sw -- SoapWriter
        '''
        self._indx = 0
        MessageInterface.__init__(self, sw)
        Base.__init__(self)
        self._dom = DOM
        self.node = None
        if isinstance(message, (str,unicode)):
            self.loadFromString(message)
        elif isinstance(message, ElementProxy):
            self.node = message._getNode()
        else:
            self.node = message
        self.processorNss = self.standard_ns.copy()
        self.processorNss.update(self.reserved_ns)

    def __str__(self):
        return self.toString()

    #############################################
    # Methods for checking/setting the
    # classes (namespaceURI,name) node. 
    #############################################
    def checkNode(self, namespaceURI=None, localName=None):
        '''
            namespaceURI -- namespace of element
            localName -- local name of element
        '''
        namespaceURI = namespaceURI or self.namespaceURI
        localName = localName or self.name
        check = False
        if localName and self.node:
            check = self._dom.isElement(self.node, localName, namespaceURI)
        if not check:
            raise NamespaceError('unexpected node type %s, expecting %s' %(self.node, localName))

    def setNode(self, node=None):
        if node:
            if isinstance(node, ElementProxy):
                self.node = node._getNode()
            else:
                self.node = node
        elif self.node:
            node = self._dom.getElement(self.node, self.name, self.namespaceURI, default=None)
            if not node:
                raise NamespaceError('cant find element (%s,%s)' %(self.namespaceURI,self.name))
            self.node = node
        else:
            #self.node = self._dom.create(self.node, self.name, self.namespaceURI, default=None)
            self.createDocument(self.namespaceURI, localName=self.name, doctype=None)
        
        self.checkNode()

    #############################################
    # Wrapper Methods for direct DOM Element Node access
    #############################################
    def _getNode(self):
        return self.node

    def _getElements(self):
        return self._dom.getElements(self.node, name=None)

    def _getOwnerDocument(self):
        return self.node.ownerDocument or self.node

    def _getUniquePrefix(self):
        '''I guess we need to resolve all potential prefixes
        because when the current node is attached it copies the 
        namespaces into the parent node.
        '''
        while 1:
            self._indx += 1
            prefix = 'ns%d' %self._indx
            try:
                self._dom.findNamespaceURI(prefix, self._getNode())
            except DOMException:
                break
        return prefix

    def _getPrefix(self, node, nsuri):
        '''
        Keyword arguments:
            node -- DOM Element Node
            nsuri -- namespace of attribute value
        '''
        try:
            if node and (node.nodeType == node.ELEMENT_NODE) and \
                (nsuri == self._dom.findDefaultNS(node)):
                return None
        except DOMException:
            pass
        if nsuri == XMLNS.XML:
            return self._xml_prefix
        if node.nodeType == Node.ELEMENT_NODE:
            for attr in node.attributes.values():
                if attr.namespaceURI == XMLNS.BASE \
                   and nsuri == attr.value:
                        return attr.localName
            else:
                if node.parentNode:
                    return self._getPrefix(node.parentNode, nsuri)
        raise NamespaceError('namespaceURI "%s" is not defined' % nsuri)

    def _appendChild(self, node):
        '''
        Keyword arguments:
            node -- DOM Element Node
        '''
        if node is None:
            raise TypeError('node is None')
        self.node.appendChild(node)

    def _insertBefore(self, newChild, refChild):
        '''
        Keyword arguments:
            child -- DOM Element Node to insert
            refChild -- DOM Element Node 
        '''
        self.node.insertBefore(newChild, refChild)

    def _setAttributeNS(self, namespaceURI, qualifiedName, value):
        '''
        Keyword arguments:
            namespaceURI -- namespace of attribute
            qualifiedName -- qualified name of new attribute value
            value -- value of attribute
        '''
        self.node.setAttributeNS(namespaceURI, qualifiedName, value)

    #############################################
    #General Methods
    #############################################
    def isFault(self):
        '''check to see if this is a soap:fault message.
        '''
        return False

    def getPrefix(self, namespaceURI):
        try:
            prefix = self._getPrefix(node=self.node, nsuri=namespaceURI)
        except NamespaceError:
            prefix = self._getUniquePrefix() 
            self.setNamespaceAttribute(prefix, namespaceURI)
        return prefix

    def getDocument(self):
        return self._getOwnerDocument()

    def setDocument(self, document):
        self.node = document

    def importFromString(self, xmlString):
        doc = self._dom.loadDocument(StringIO(xmlString))
        node = self._dom.getElement(doc, name=None)
        clone = self.importNode(node)
        self._appendChild(clone)

    def importNode(self, node):
        if isinstance(node, ElementProxy):
            node = node._getNode()
        return self._dom.importNode(self._getOwnerDocument(), node, deep=1)

    def loadFromString(self, data):
        self.node = self._dom.loadDocument(StringIO(data))

    def canonicalize(self):
        return Canonicalize(self.node)

    def toString(self):
        return self.canonicalize()

    def createDocument(self, namespaceURI, localName, doctype=None):
        '''If specified must be a SOAP envelope, else may contruct an empty document.
        '''
        prefix = self._soap_env_prefix

        if namespaceURI == self.reserved_ns[prefix]:
            qualifiedName = '%s:%s' %(prefix,localName)
        elif namespaceURI is localName is None:
            self.node = self._dom.createDocument(None,None,None)
            return
        else:
            raise KeyError('only support creation of document in %s' %self.reserved_ns[prefix])

        document = self._dom.createDocument(nsuri=namespaceURI, qname=qualifiedName, doctype=doctype)
        self.node = document.childNodes[0]

        #set up reserved namespace attributes
        for prefix,nsuri in self.reserved_ns.iteritems():
            self._setAttributeNS(namespaceURI=self._xmlns_nsuri, 
                qualifiedName='%s:%s' %(self._xmlns_prefix,prefix), 
                value=nsuri)

    #############################################
    #Methods for attributes
    #############################################
    def hasAttribute(self, namespaceURI, localName):
        return self._dom.hasAttr(self._getNode(), name=localName, nsuri=namespaceURI)

    def setAttributeType(self, namespaceURI, localName):
        '''set xsi:type
        Keyword arguments:
            namespaceURI -- namespace of attribute value
            localName -- name of new attribute value

        '''
        self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName)
        value = localName
        if namespaceURI:
            value = '%s:%s' %(self.getPrefix(namespaceURI),localName)

        xsi_prefix = self.getPrefix(self._xsi_nsuri)
        self._setAttributeNS(self._xsi_nsuri, '%s:type' %xsi_prefix, value)

    def createAttributeNS(self, namespace, name, value):
        document = self._getOwnerDocument()
        ##this function doesn't exist!! it has only two arguments
        document.createAttributeNS(namespace, name, value)

    def setAttributeNS(self, namespaceURI, localName, value):
        '''
        Keyword arguments:
            namespaceURI -- namespace of attribute to create, None is for
                attributes in no namespace.
            localName -- local name of new attribute
            value -- value of new attribute
        ''' 
        prefix = None
        if namespaceURI:
            try:
                prefix = self.getPrefix(namespaceURI)
            except KeyError:
                prefix = 'ns2'
                self.setNamespaceAttribute(prefix, namespaceURI)
        qualifiedName = localName
        if prefix:
            qualifiedName = '%s:%s' %(prefix, localName)
        self._setAttributeNS(namespaceURI, qualifiedName, value)

    def setNamespaceAttribute(self, prefix, namespaceURI):
        '''
        Keyword arguments:
            prefix -- xmlns prefix
            namespaceURI -- value of prefix
        '''
        self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)

    #############################################
    #Methods for elements
    #############################################
    def createElementNS(self, namespace, qname):
        '''
        Keyword arguments:
            namespace -- namespace of element to create
            qname -- qualified name of new element
        '''
        document = self._getOwnerDocument()
        node = document.createElementNS(namespace, qname)
        return ElementProxy(self.sw, node)

    def createAppendSetElement(self, namespaceURI, localName, prefix=None):
        '''Create a new element (namespaceURI,name), append it
           to current node, then set it to be the current node.
        Keyword arguments:
            namespaceURI -- namespace of element to create
            localName -- local name of new element
            prefix -- if namespaceURI is not defined, declare prefix.  defaults
                to 'ns1' if left unspecified.
        '''
        node = self.createAppendElement(namespaceURI, localName, prefix=None)
        node=node._getNode()
        self._setNode(node._getNode())

    def createAppendElement(self, namespaceURI, localName, prefix=None):
        '''Create a new element (namespaceURI,name), append it
           to current node, and return the newly created node.
        Keyword arguments:
            namespaceURI -- namespace of element to create
            localName -- local name of new element
            prefix -- if namespaceURI is not defined, declare prefix.  defaults
                to 'ns1' if left unspecified.
        '''
        declare = False
        qualifiedName = localName
        if namespaceURI:
            try:
                prefix = self.getPrefix(namespaceURI)
            except:
                declare = True
                prefix = prefix or self._getUniquePrefix()
            if prefix: 
                qualifiedName = '%s:%s' %(prefix, localName)
        node = self.createElementNS(namespaceURI, qualifiedName)
        if declare:
            node._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
        self._appendChild(node=node._getNode())
        return node

    def createInsertBefore(self, namespaceURI, localName, refChild):
        qualifiedName = localName
        prefix = self.getPrefix(namespaceURI)
        if prefix: 
            qualifiedName = '%s:%s' %(prefix, localName)
        node = self.createElementNS(namespaceURI, qualifiedName)
        self._insertBefore(newChild=node._getNode(), refChild=refChild._getNode())
        return node

    def getElement(self, namespaceURI, localName):
        '''
        Keyword arguments:
            namespaceURI -- namespace of element
            localName -- local name of element
        '''
        node = self._dom.getElement(self.node, localName, namespaceURI, default=None)
        if node:
            return ElementProxy(self.sw, node)
        return None

    def getAttributeValue(self, namespaceURI, localName):
        '''
        Keyword arguments:
            namespaceURI -- namespace of attribute
            localName -- local name of attribute
        '''
        if self.hasAttribute(namespaceURI, localName):
            attr = self.node.getAttributeNodeNS(namespaceURI,localName)
            return attr.value
        return None

    def getValue(self):
        return self._dom.getElementText(self.node, preserve_ws=True)    

    #############################################
    #Methods for text nodes
    #############################################
    def createAppendTextNode(self, pyobj):
        node = self.createTextNode(pyobj)
        self._appendChild(node=node._getNode())
        return node

    def createTextNode(self, pyobj):
        document = self._getOwnerDocument()
        node = document.createTextNode(pyobj)
        return ElementProxy(self.sw, node)

    #############################################
    #Methods for retrieving namespaceURI's
    #############################################
    def findNamespaceURI(self, qualifiedName):
        parts = SplitQName(qualifiedName)
        element = self._getNode()

        return self._dom.findNamespaceURI(parts[0], element)

    def resolvePrefix(self, prefix):
        element = self._getNode()
        return self._dom.findNamespaceURI(prefix, element)

    def getSOAPEnvURI(self):
        return self._soap_env_nsuri

    def isEmpty(self):
        return not self.node class SchemaReader:
    """A SchemaReader creates XMLSchema objects from urls and xml data.
    """
    
    namespaceToSchema = {}
    
    def __init__(self, domReader=None, base_url=None):
        """domReader -- class must implement DOMAdapterInterface
           base_url -- base url string
        """
        self.__base_url = base_url
        self.__readerClass = domReader
        if not self.__readerClass:
            self.__readerClass = DOMAdapter
        self._includes = {}
        self._imports = {}

    def __setImports(self, schema):
        """Add dictionary of imports to schema instance.
           schema -- XMLSchema instance
        """
        for ns in schema.imports.iterkeys(): 
            if ns in self._imports:
                schema.addImportSchema(self._imports[ns])

    def __setIncludes(self, schema):
        """Add dictionary of includes to schema instance.
           schema -- XMLSchema instance
        """
        for schemaLocation in schema.includes.iterkeys(): 
            if schemaLocation in self._includes:
                schema.addIncludeSchema(schemaLocation, self._imports[schemaLocation])

    def addSchemaByLocation(self, location, schema):
        """provide reader with schema document for a location.
        """
        self._includes[location] = schema

    def addSchemaByNamespace(self, schema):
        """provide reader with schema document for a targetNamespace.
        """
        self._imports[schema.targetNamespace] = schema

    def loadFromNode(self, parent, element):
        """element -- DOM node or document
           parent -- WSDLAdapter instance
        """
        reader = self.__readerClass(element)
        schema = XMLSchema(parent)
        #HACK to keep a reference
        schema.wsdl = parent
        schema.setBaseUrl(self.__base_url)
        schema.load(reader)
        return schema
        
    def loadFromStream(self, _file, url=None):
        """Return an XMLSchema instance loaded from a file object.
           _file -- file object
           url -- base location for resolving imports/includes.
        """
        reader = self.__readerClass()
        reader.loadDocument(_file)
        schema = XMLSchema()
        if url is not None:
            schema.setBaseUrl(url)
        schema.load(reader)
        self.__setIncludes(schema)
        self.__setImports(schema)
        return schema

    def loadFromString(self, data):
        """Return an XMLSchema instance loaded from an XML string.
           data -- XML string
        """
        return self.loadFromStream(StringIO(data))

    def loadFromURL(self, url, schema=None):
        """Return an XMLSchema instance loaded from the given url.
           url -- URL to dereference
           schema -- Optional XMLSchema instance.
        """
        reader = self.__readerClass()
        if self.__base_url:
            url = basejoin(self.__base_url,url)

        reader.loadFromURL(url)
        schema = schema or XMLSchema()
        schema.setBaseUrl(url)
        schema.load(reader)
        self.__setIncludes(schema)
        self.__setImports(schema)
        return schema

    def loadFromFile(self, filename):
        """Return an XMLSchema instance loaded from the given file.
           filename -- name of file to open
        """
        if self.__base_url:
            filename = basejoin(self.__base_url,filename)
        f = open(filename, 'rb')
        try:
            schema = self.loadFromStream(f, filename)
        finally:
            f.close()

        return schema class WSDLToolsAdapter(XMLSchemaComponent):
    """WSDL Adapter to grab the attributes from the wsdl document node.
    """
    attributes = {'name':None, 'targetNamespace':None}
    tag = 'definitions'

    def __init__(self, wsdl):
        XMLSchemaComponent.__init__(self, parent=wsdl)
        self.setAttributes(DOMAdapter(wsdl.document))

    def getImportSchemas(self):
        """returns WSDLTools.WSDL types Collection
        """
        return self._parent().types
import weakref
from cStringIO import StringIO
from pysphere.ZSI.wstools.Namespaces import XMLNS, WSA, WSA_LIST, WSAW_LIST, WSRF_V1_2, WSRF
from pysphere.ZSI.wstools.Utility import Collection, CollectionNS, DOM, ElementProxy, basejoin
from pysphere.ZSI.wstools.XMLSchema import SchemaReader, WSDLToolsAdapter
            self.parts[name] = part
            elemref = DOM.getAttr(element, 'element', default=None)
            typeref = DOM.getAttr(element, 'type', default=None)
            if typeref is None and elemref is None:
                raise WSDLError(
                    'No type or element attribute for part: %s' % name
                    )
            if typeref is not None:
                part.type = ParseTypeRef(typeref, element)
            if elemref is not None:
                part.element = ParseTypeRef(elemref, element)

    def toDom(self):
        wsdl = self.getWSDL()
        ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
        epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'message')
        epc.setAttributeNS(None, 'name', self.name)

        for part in self.parts:
            part.toDom(epc._getNode())


class MessagePart(Element):
    def __init__(self, name):
        Element.__init__(self, name, '')
        self.element = None
        self.type = None

#    def getWSDL(self):
#        """Return the WSDL object that contains this Message Part."""
#        return self.parent().parent().parent().parent()

    def getTypeDefinition(self):
        wsdl = self.getWSDL()
        nsuri,name = self.type
        schema = wsdl.types.get(nsuri, {})
        return schema.get(name)

    def getElementDeclaration(self):
        wsdl = self.getWSDL()
        nsuri,name = self.element
        schema = wsdl.types.get(nsuri, {})
        return schema.get(name)

    def toDom(self, node):
        """node -- node representing message"""
        wsdl = self.getWSDL()
        ep = ElementProxy(None, node)
        epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'part')
        epc.setAttributeNS(None, 'name', self.name)

        if self.element is not None:
            ns,name = self.element
            prefix = epc.getPrefix(ns)
            epc.setAttributeNS(None, 'element', '%s:%s'%(prefix,name))
        elif self.type is not None:
            ns,name = self.type
            prefix = epc.getPrefix(ns)
            epc.setAttributeNS(None, 'type', '%s:%s'%(prefix,name))


class PortType(Element):
    '''PortType has a anyAttribute, thus must provide for an extensible
       mechanism for supporting such attributes.  ResourceProperties is
       specified in WS-ResourceProperties.   wsa:Action is specified in
       WS-Address.

       Instance Data:
           name -- name attribute
           resourceProperties -- optional. wsr:ResourceProperties attribute,
              value is a QName this is Parsed into a (namespaceURI, name)
              that represents a Global Element Declaration.
           operations
    '''

    def __init__(self, name, documentation=''):
        Element.__init__(self, name, documentation)
        self.operations = Collection(self)
        self.resourceProperties = None

#    def getWSDL(self):
#        return self.parent().parent()

    def getTargetNamespace(self):
        return self.targetNamespace or self.getWSDL().targetNamespace

    def getResourceProperties(self):
        return self.resourceProperties

    def addOperation(self, name, documentation='', parameterOrder=None):
        item = Operation(name, documentation, parameterOrder)
        self.operations[name] = item
        return item

    def load(self, element):
        self.name = DOM.getAttr(element, 'name')
        self.documentation = GetDocumentation(element)
        self.targetNamespace = DOM.getAttr(element, 'targetNamespace')

        for nsuri in WSRF_V1_2.PROPERTIES.XSD_LIST:
            if DOM.hasAttr(element, 'ResourceProperties', nsuri):
                rpref = DOM.getAttr(element, 'ResourceProperties', nsuri)
                self.resourceProperties = ParseQName(rpref, element)

        NS_WSDL = DOM.GetWSDLUri(self.getWSDL().version)
        elements = DOM.getElements(element, 'operation', NS_WSDL)
        for element in elements:
            name = DOM.getAttr(element, 'name')
            docs = GetDocumentation(element)
            param_order = DOM.getAttr(element, 'parameterOrder', default=None)
            if param_order is not None:
                param_order = param_order.split(' ')
            operation = self.addOperation(name, docs, param_order)

            item = DOM.getElement(element, 'input', None, None)
            if item is not None:
                name = DOM.getAttr(item, 'name')
                docs = GetDocumentation(item)
                msgref = DOM.getAttr(item, 'message')
                message = ParseQName(msgref, item)

                for WSA in WSA_LIST + WSAW_LIST: