commitdump
[ncclient] / ncclient / content.py
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 import logging
16 from xml.etree import cElementTree as ElementTree
17
18 logger = logging.getLogger('ncclient.content')
19
20 BASE_NS = 'urn:ietf:params:xml:ns:netconf:base:1.0'
21 NOTIFICATION_NS = 'urn:ietf:params:xml:ns:netconf:notification:1.0'
22
23 def qualify(tag, ns=BASE_NS):
24     return '{%s}%s' % (ns, tag)
25
26 _ = qualify
27
28 def make_hello(capabilities):
29     return '<hello xmlns="%s">%s</hello>' % (BASE_NS, capabilities)
30
31 def make_rpc(id, op):
32     return '<rpc message-id="%s" xmlns="%s">%s</rpc>' % (id, BASE_NS, op)
33
34 def parse_hello(raw):
35     from capabilities import Capabilities
36     id, capabilities = 0, Capabilities()
37     root = ElementTree.fromstring(raw)
38     if root.tag == _('hello'):
39         for child in root.getchildren():
40             if child.tag == _('session-id'):
41                 id = int(child.text)
42             elif child.tag == _('capabilities'):
43                 for cap in child.getiterator(_('capability')):
44                     capabilities.add(cap.text)
45     return id, capabilities
46
47 def parse_message_root(raw):
48     from cStringIO import StringIO
49     fp = StringIO(raw)
50     for event, element in ElementTree.iterparse(fp, events=('start',)):
51         if element.tag == _('rpc'):
52             return element.attrib['message-id']
53         elif element.tag == _('notification', NOTIFICATION_NS):
54             return 'notification'
55         else:
56             return None