source: TI12-security/trunk/ndg_saml/ndg/soap/etree.py @ 7560

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/ndg_saml/ndg/soap/etree.py@7560
Revision 7560, 7.4 KB checked in by pjkersha, 9 years ago (diff)

Merged ndg.soap back into ndg_saml package - simpler to keep it together.

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