source: TI12-security/trunk/python/ndg.security.common/ndg/security/common/soap/etree.py @ 5601

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg-security/TI12-security/trunk/python/ndg.security.common/ndg/security/common/soap/etree.py@5601
Revision 5601, 7.3 KB checked in by pjkersha, 12 years ago (diff)

Adding Assertion parsing functionality - not finished!

Line 
1"""SOAP client package - XML representation using ElementTree
2
3NERC DataGrid Project
4"""
5__author__ = "P J Kershaw"
6__date__ = "27/07/09"
7__copyright__ = ""
8__license__ = "BSD - see LICENSE file in top-level directory"
9__contact__ = "Philip.Kershaw@stfc.ac.uk"
10__revision__ = '$Id:$'
11import logging
12log = logging.getLogger(__name__)
13   
14try: # python 2.5
15    from xml.etree import cElementTree, ElementTree
16except ImportError:
17    # if you've installed it yourself it comes this way
18    import cElementTree, ElementTree
19
20# ElementTree helper functions
21from ndg.security.common.utils.etree import QName
22
23from ndg.security.common.soap import SOAPObject, SOAPEnvelopeBase, \
24    SOAPHeaderBase, SOAPBodyBase, SOAPFault
25
26class ETreeSOAPExtensions(object): 
27    """Utility to enable addition of core ElementTree specific attributes and
28    methods for ElementTree SOAP implementation
29    """
30    def __init__(self):
31        self.__qname = None
32        self.__elem = None
33
34    def _getQname(self):
35        return self.__qname
36
37    def _setQname(self, value):
38        if not isinstance(value, QName):
39            raise TypeError('Expecting %r for "qname" attribute; got %r' %
40                            (QName, type(value)))
41        self.__qname = value
42
43    def _getElem(self):
44        return self.__elem
45
46    def _setElem(self, value):
47        if not ElementTree.iselement(value):
48            raise TypeError('Expecting %r for "elem" attribute; got %r' %
49                            (ElementTree.Element, type(value)))
50        self.__elem = value
51       
52    qname = property(_getQname, _setQname, None, "Qualified name object")
53    elem = property(_getElem, _setElem, None, "Root element")
54
55    @staticmethod
56    def _serialize(elem):
57         """Serialise element tree into string"""
58         return cElementTree.tostring(elem)
59       
60    @classmethod
61    def _prettyPrint(cls, elem):
62        """Basic pretty printing separating each element on to a new line"""
63        xml = cls._serialize(elem)
64        xml = ">\n".join(xml.split(">"))
65        xml = "\n<".join(xml.split("<"))
66        xml = '\n'.join(xml.split('\n\n'))
67        return xml
68
69    def _parse(self, source):
70        """Read in the XML from source
71        @type source: basestring/file
72        @param source: file path to XML file or file object
73        """
74        tree = ElementTree.parse(source)
75        elem = tree.getroot()
76       
77        return elem       
78
79
80class SOAPHeader(SOAPHeaderBase, ETreeSOAPExtensions):
81    """ElementTree implementation of SOAP Header object"""
82   
83    DEFAULT_ELEMENT_NAME = QName(SOAPHeaderBase.DEFAULT_ELEMENT_NS,
84                               tag=SOAPHeaderBase.DEFAULT_ELEMENT_LOCAL_NAME,
85                               prefix=SOAPHeaderBase.DEFAULT_ELEMENT_NS_PREFIX)
86   
87    def __init__(self):
88        SOAPHeaderBase.__init__(self)
89        ETreeSOAPExtensions.__init__(self)
90       
91        self.qname = QName(SOAPHeaderBase.DEFAULT_ELEMENT_NS, 
92                           tag=SOAPHeaderBase.DEFAULT_ELEMENT_LOCAL_NAME, 
93                           prefix=SOAPHeaderBase.DEFAULT_ELEMENT_NS_PREFIX)
94
95    def create(self):
96        """Create header ElementTree element"""
97       
98        self.elem = ElementTree.Element(str(self.qname))
99        ElementTree._namespace_map[SOAPHeaderBase.DEFAULT_ELEMENT_NS
100                                   ] = SOAPHeaderBase.DEFAULT_ELEMENT_NS_PREFIX
101   
102    def serialize(self):
103        """Serialise element tree into string"""
104        return ETreeSOAPExtensions._serialize(self.elem)
105   
106    def prettyPrint(self):
107        """Basic pretty printing separating each element on to a new line"""
108        return ETreeSOAPExtensions._prettyPrint(self.elem)
109
110
111class SOAPBody(SOAPBodyBase, ETreeSOAPExtensions):
112    """ElementTree based implementation for SOAP Body object"""
113   
114    DEFAULT_ELEMENT_NAME = QName(SOAPBodyBase.DEFAULT_ELEMENT_NS,
115                                 tag=SOAPBodyBase.DEFAULT_ELEMENT_LOCAL_NAME,
116                                 prefix=SOAPBodyBase.DEFAULT_ELEMENT_NS_PREFIX)
117   
118    def __init__(self):
119        SOAPBodyBase.__init__(self)
120        ETreeSOAPExtensions.__init__(self)
121       
122        self.qname = QName(SOAPBodyBase.DEFAULT_ELEMENT_NS, 
123                           tag=SOAPBodyBase.DEFAULT_ELEMENT_LOCAL_NAME, 
124                           prefix=SOAPBodyBase.DEFAULT_ELEMENT_NS_PREFIX)
125       
126    def create(self):
127        """Create header ElementTree element"""
128        self.elem = ElementTree.Element(str(self.qname))
129   
130    def serialize(self):
131        """Serialise element tree into string"""
132        return ETreeSOAPExtensions._serialize(self.elem)
133   
134    def prettyPrint(self):
135        """Basic pretty printing separating each element on to a new line"""
136        return ETreeSOAPExtensions._prettyPrint(self.elem)
137   
138
139class SOAPEnvelope(SOAPEnvelopeBase, ETreeSOAPExtensions):
140    """ElementTree based SOAP implementation"""
141    DEFAULT_ELEMENT_NAME = QName(SOAPEnvelopeBase.DEFAULT_ELEMENT_NS,
142                             tag=SOAPEnvelopeBase.DEFAULT_ELEMENT_LOCAL_NAME,
143                             prefix=SOAPEnvelopeBase.DEFAULT_ELEMENT_NS_PREFIX)
144
145    def __init__(self):
146        SOAPEnvelopeBase.__init__(self)
147        ETreeSOAPExtensions.__init__(self)
148       
149        self.qname = QName(SOAPEnvelopeBase.DEFAULT_ELEMENT_NS, 
150                             tag=SOAPEnvelopeBase.DEFAULT_ELEMENT_LOCAL_NAME, 
151                             prefix=SOAPEnvelopeBase.DEFAULT_ELEMENT_NS_PREFIX)
152        self.__header = SOAPHeader()
153        self.__body = SOAPBody()
154
155    def _getHeader(self):
156        return self.__header
157
158    def _setHeader(self, value):
159        if not isinstance(value, SOAPHeader):
160            raise TypeError('Expecting %r for "header" attribute; got %r' %
161                            (SOAPHeader, type(value)))
162        self.__header = value
163
164    def _getBody(self):
165        return self.__body
166
167    def _setBody(self, value):
168        if not isinstance(value, SOAPBody):
169            raise TypeError('Expecting %r for "header" attribute; got %r' %
170                            (SOAPBody, type(value)))
171        self.__body = value
172
173    header = property(_getHeader, _setHeader, None, "SOAP header object")
174    body = property(_getBody, _setBody, None, "SOAP body object")
175
176    def create(self):
177        """Create SOAP Envelope with header and body"""
178       
179        self.elem = ElementTree.Element(str(self.qname))
180           
181        self.header.create()
182        self.elem.append(self.header.elem)
183       
184        self.body.create()
185        self.elem.append(self.body.elem)
186   
187    def serialize(self):
188        """Serialise element tree into string"""
189        return ETreeSOAPExtensions._serialize(self.elem)
190   
191    def prettyPrint(self):
192        """Basic pretty printing separating each element onto a new line"""
193        return ETreeSOAPExtensions._prettyPrint(self.elem)
194   
195    def parse(self, source):
196        self.elem = ETreeSOAPExtensions._parse(self, source) 
197       
198        for elem in self.elem:
199            localName = QName.getLocalPart(elem.tag)
200            if localName == SOAPHeader.DEFAULT_ELEMENT_LOCAL_NAME:
201                self.header.elem = elem
202               
203            elif localName == SOAPBody.DEFAULT_ELEMENT_LOCAL_NAME:
204                self.body.elem = elem
205               
206            else:
207                raise SOAPFault('Invalid child element in SOAP Envelope "%s" '
208                                'for stream %r' % (localName, source))
Note: See TracBrowser for help on using the repository browser.