restructured and better
[ncclient] / ncclient / subject.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 from threading import Lock
16
17 import logging
18
19 logger = logging.getLogger('ncclient.subject')
20
21 class Subject:
22         
23     def __init__(self, listeners=[]):
24         self._listeners = listeners
25         self._lock = Lock()
26     
27     def has_listener(self, listener):
28         with self._lock:
29             return (listener in self._listeners)
30     
31     def add_listener(self, listener):
32         with self._lock:
33             self._listeners.append(listener)
34     
35     def remove_listener(self, listener):
36         with self._lock:
37             try:
38                 self._listeners.remove(listener)
39             except ValueError:
40                 pass
41     
42     def dispatch(self, event, *args, **kwds):
43         with self._lock:
44             listeners = list(self._listeners)
45         for l in listeners:
46             logger.debug('dispatching [%s] to [%s]' % (event, l.__class__))
47             try:
48                 getattr(l, event)(*args, **kwds)
49             except Exception as e:
50                 logger.warning(e)
51
52
53 class SessionListener:
54
55     def __init__(self):
56         self._id2rpc = {}
57         self._subscription = None
58
59     def reply(self, raw):
60         reply = RPCReply(msg)
61         id2rpc[reply.id]._deliver(reply)
62     
63     def error(self, buf):
64         pass