Statistics
| Branch: | Tag: | Revision:

root / src / listener.py @ 14b13ebe

History | View | Annotate | Download (1.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 threading import Lock
16

    
17
import logging
18

    
19
logger = logging.getLogger('ncclient.listener')
20

    
21
class Subject:
22
    
23
    'Thread-safe abstact class for event-dispatching subjects'
24
    
25
    def __init__(self, listeners=[]):
26
        self._listeners = listeners
27
        self._lock = Lock()
28
    
29
    def has_listener(self, listener):
30
        with self._lock:
31
            return (listener in self._listeners)
32
    
33
    def add_listener(self, listener):
34
        with self._lock:
35
            self._listeners.append(listener)
36
    
37
    def remove_listener(self, listener):
38
        with self._lock:
39
            try:
40
                self._listeners.remove(listener)
41
            except ValueError:
42
                pass
43
    
44
    def dispatch(self, event, *args, **kwds):
45
        with self._lock:
46
            for l in self._listeners:
47
                try:
48
                    getattr(l, event)(*args, **kwds)
49
                except Exception as e:
50
                    logger.warning(e)
51

    
52
if __name__=="__main__":
53
    
54
    logging.basicConfig(level=logging.DEBUG)
55
    
56
    class Listener:
57
        def reply(self, data):
58
            print data
59
        def error(self, err_info):
60
            print err_info
61
    
62
    subject = Subject()        
63
    subject.add_listener(Listener())
64
    
65
    subject.dispatch('reply', 'hello world')
66
    subject.dispatch('error', 'bye world')
67
    subject.dispatch('undefined', 'happy deliverin')