Statistics
| Branch: | Tag: | Revision:

root / ncclient / content / builders.py @ f5c75f88

History | View | Annotate | Download (2.9 kB)

1
# Copyright 2009 Shikhar Bhushan
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#    http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

    
15
from xml.etree import cElementTree as ET
16

    
17
from common import BASE_NS
18
from common import qualify as _
19

    
20
class TreeBuilder:
21
    '''Build an ElementTree.Element instance from an XML tree specification
22
    based on nested dictionaries.
23
    '''
24
    
25
    def __init__(self, spec):
26
        self._root = TreeBuilder.build(spec)
27
        
28
    def to_string(self, encoding='utf-8'):
29
        return ET.tostring(self._root, encoding)
30
    
31
    @property
32
    def tree(self):
33
        return self._root
34
    
35
    @staticmethod
36
    def build(spec):
37
        'Returns constructed ElementTree.Element'
38
        if spec.has_key('tag'):
39
            ele = ET.Element(spec.get('tag'), spec.get('attributes', {}))
40
            ele.text = spec.get('text', '')
41
            for child in spec.get('children', []):
42
                ele.append(TreeBuilder.build(child))
43
            return ele
44
        elif spec.has_key('comment'):
45
            return ET.Comment(spec.get('comment'))
46
        else:
47
            raise ValueError('Invalid tree spec')
48

    
49

    
50
class HelloBuilder:
51
        
52
    @staticmethod
53
    def build(capabilities, encoding='utf-8'):
54
        children = [{'tag': 'capability', 'text': uri } for uri in capabilities]
55
        spec = {
56
            'tag': _('hello', BASE_NS),
57
            'children': [{
58
                        'tag': 'capabilities',
59
                        'children': children
60
                        }]
61
            }
62
        return TreeBuilder(spec).to_string(encoding)
63

    
64

    
65
class RPCBuilder:
66
    
67
    @staticmethod
68
    def build(msgid, op, encoding='utf-8'):
69
        if isinstance(op, basestring):
70
            return RPCBuilder.build_from_string(msgid, op, encoding)
71
        else:
72
            return RPCBuilder.build_from_spec(msgid, op, encoding)
73
    
74
    @staticmethod
75
    def build_from_spec(msgid, opspec, encoding='utf-8'):
76
        if isinstance(opspec, dict):
77
            opspec = [opspec]
78
        spec = {
79
            'tag': _('rpc', BASE_NS),
80
            'attributes': {'message-id': msgid},
81
            'children': opspec
82
            }
83
        return TreeBuilder(spec).to_string(encoding)
84
    
85
    @staticmethod
86
    def build_from_string(msgid, opstr, encoding='utf-8'):
87
        decl = '<?xml version="1.0" encoding="%s"?>' % encoding
88
        doc = (u'''<rpc message-id="%s" xmlns="%s">%s</rpc>''' %
89
               (msgid, BASE_NS, opstr)).encode(encoding)
90
        return (decl + doc)