summaryrefslogtreecommitdiff
path: root/suds/mx/literal.py
blob: 937ad8ecc7b0bf2d55040dfb42318fd780375fd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the 
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( jortel@redhat.com )

"""
Provides literal I{marshaller} classes.
"""

from logging import getLogger
from suds import *
from suds.mx import *
from suds.mx.core import Core
from suds.mx.typer import Typer
from suds.resolver import GraphResolver, Frame
from suds.sax.element import Element
from suds.sudsobject import Factory

log = getLogger(__name__)


#
# Add typed extensions
# type = The expected xsd type
# real = The 'true' XSD type
# ancestry = The 'type' ancestry
#
Content.extensions.append('type')
Content.extensions.append('real')
Content.extensions.append('ancestry')



class Typed(Core):
    """
    A I{typed} marshaller.
    This marshaller is semi-typed as needed to support both
    I{document/literal} and I{rpc/literal} soap message styles.
    @ivar schema: An xsd schema.
    @type schema: L{xsd.schema.Schema}
    @ivar resolver: A schema type resolver.
    @type resolver: L{GraphResolver}
    """

    def __init__(self, schema, xstq=True):
        """
        @param schema: A schema object
        @type schema: L{xsd.schema.Schema}
        @param xstq: The B{x}ml B{s}chema B{t}ype B{q}ualified flag indicates
            that the I{xsi:type} attribute values should be qualified by namespace.
        @type xstq: bool
        """
        Core.__init__(self)
        self.schema = schema
        self.xstq = xstq
        self.resolver = GraphResolver(self.schema)
    
    def reset(self):
        self.resolver.reset()
            
    def start(self, content):
        #
        # Start marshalling the 'content' by ensuring that both the
        # 'content' _and_ the resolver are primed with the XSD type
        # information.  The 'content' value is both translated and
        # sorted based on the XSD type.  Only values that are objects
        # have their attributes sorted.
        #
        log.debug('starting content:\n%s', content)
        if content.type is None:
            name = content.tag
            if name.startswith('_'):
                name = '@'+name[1:]
            content.type = self.resolver.find(name, content.value)
            if content.type is None:
                raise TypeNotFound(content.tag)
        else:
            known = None
            if isinstance(content.value, Object):
                known = self.resolver.known(content.value)
                if known is None:
                    log.debug('object has no type information', content.value)
                    known = content.type
            frame = Frame(content.type, resolved=known)
            self.resolver.push(frame)
        frame = self.resolver.top()
        content.real = frame.resolved
        content.ancestry = frame.ancestry
        self.translate(content)
        self.sort(content)
        if self.skip(content):
            log.debug('skipping (optional) content:\n%s', content)
            self.resolver.pop()
            return False
        else:
            return True
        
    def suspend(self, content):
        #
        # Suspend to process a list content.  Primarily, this
        # involves popping the 'list' content off the resolver's
        # stack so the list items can be marshalled.
        #
        self.resolver.pop()
    
    def resume(self, content):
        #
        # Resume processing a list content.  To do this, we
        # really need to simply push the 'list' content
        # back onto the resolver stack.
        #
        self.resolver.push(Frame(content.type))
        
    def end(self, parent, content):
        #
        # End processing the content.  Make sure the content
        # ending matches the top of the resolver stack since for
        # list processing we play games with the resolver stack.
        #
        log.debug('ending content:\n%s', content)
        current = self.resolver.top().type
        if current == content.type:
            self.resolver.pop()
        else:
            raise Exception, \
                'content (end) mismatch: top=(%s) cont=(%s)' % \
                (current, content)
    
    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
    
    def setnil(self, node, content):
        #
        # Set the 'node' nil only if the XSD type
        # specifies that it is permitted.
        #
        if content.type.nillable:
            node.setnil()
            
    def setdefault(self, node, content):
        #
        # Set the node to the default value specified
        # by the XSD type.
        #
        default = content.type.default
        if default is None:
            pass
        else:
            node.setText(default)
        return default
    
    def optional(self, content):
        if content.type.optional():
            return True
        for a in content.ancestry:
            if a.optional():
                return True
        return False
    
    def encode(self, node, content):
        # Add (soap) encoding information only if the resolved
        # type is derived by extension.  Further, the xsi:type values
        # is qualified by namespace only if the content (tag) and
        # referenced type are in different namespaces.
        if content.type.any():
            return
        if not content.real.extension():
            return
        if content.type.resolve() == content.real:
            return
        ns = None
        name = content.real.name
        if self.xstq:
            ns = content.real.namespace('ns1')
        Typer.manual(node, name, ns)
    
    def skip(self, content):
        """
        Get whether to skip this I{content}.
        Should be skipped when the content is optional
        and either the value=None or the value is an empty list.
        @param content: The content to skip.
        @type content: L{Object}
        @return: True if content is to be skipped.
        @rtype: bool
        """
        if self.optional(content):
            v = content.value
            if v is None:
                return True
            if isinstance(v, (list,tuple)) and len(v) == 0:
                return True
        return False
    
    def optional(self, content):
        if content.type.optional():
            return True
        for a in content.ancestry:
            if a.optional():
                return True
        return False
    
    def translate(self, content):
        """
        Translate using the XSD type information.
        Python I{dict} is translated to a suds object.  Most
        importantly, primative values are translated from python
        types to XML types using the XSD type.
        @param content: The content to translate.
        @type content: L{Object}
        @return: self
        @rtype: L{Typed}
        """
        v = content.value
        if v is None:
            return
        if isinstance(v, dict):
            cls = content.real.name
            content.value = Factory.object(cls, v)
            md = content.value.__metadata__
            md.sxtype = content.type
            return
        v = content.real.translate(v, False)
        content.value = v
        return self
        
    def sort(self, content):
        """
        Sort suds object attributes based on ordering defined
        in the XSD type information.
        @param content: The content to sort.
        @type content: L{Object}
        @return: self
        @rtype: L{Typed}
        """
        v = content.value
        if isinstance(v, Object):
            md = v.__metadata__
            md.ordering = self.ordering(content.real)
        return self

    def ordering(self, type):
        """
        Get the attribute ordering defined in the specified
        XSD type information.
        @param type: An XSD type object.
        @type type: SchemaObject
        @return: An ordered list of attribute names.
        @rtype: list
        """
        result = []
        for child, ancestry in type.resolve():
            name = child.name
            if child.name is None:
                continue
            if child.isattr():
                name = '_%s' % child.name
            result.append(name)
        return result


class Literal(Typed):
    """
    A I{literal} marshaller.
    This marshaller is semi-typed as needed to support both
    I{document/literal} and I{rpc/literal} soap message styles.
    """
    pass