1 # Copyright 2009 Shikhar Bhushan
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 "All to do with NETCONF <hello> messages"
17 from xml.etree import cElementTree as ET
19 from ncclient.glue import Listener
20 from ncclient.content import TreeBuilder, BASE_NS
21 from ncclient.content import qualify as _
22 from ncclient.content import unqualify as __
24 class HelloHandler(Listener):
26 def __init__(self, init_cb, error_cb):
27 self._init_cb, self._error_cb = init_cb, error_cb
30 return 'HelloListener'
32 def callback(self, root, raw):
33 if __(root[0]) == 'hello':
35 id, capabilities = HelloHandler.parse(raw)
36 except Exception as e:
39 self._init_cb(id, capabilities)
41 def errback(self, err):
45 def build(capabilities, encoding='utf-8'):
46 "Given a list of capability URI's returns encoded <hello> message"
48 'tag': _('hello', BASE_NS),
50 'tag': 'capabilities',
51 'children': # this is fun :-)
52 [{ 'tag': 'capability', 'text': uri} for uri in capabilities]
55 return TreeBuilder(spec).to_string(encoding)
59 "Returns tuple of ('session-id', ['capability_uri', ...])"
60 sid, capabilities = 0, []
61 root = ET.fromstring(raw)
62 for child in root.getchildren():
63 if __(child.tag) == 'session-id':
65 elif __(child.tag) == 'capabilities':
66 for cap in child.getiterator(_('capability', BASE_NS)):
67 capabilities.append(cap.text)
68 # cisco doesn't namespace hello message
69 for cap in child.getiterator('capability'):
70 capabilities.append(cap.text)
71 return sid, capabilities