root / src / listener.py @ 4a2351a5
History | View | Annotate | Download (1.8 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 |
class Subject: |
18 |
|
19 |
'Thread-safe abstact class for event-dispatching subjects'
|
20 |
|
21 |
def __init__(self, listeners=[]): |
22 |
self._listeners = listeners
|
23 |
self._lock = Lock()
|
24 |
|
25 |
def has_listener(self, listener): |
26 |
with self._lock: |
27 |
return (listener in self._listeners) |
28 |
|
29 |
def add_listener(self, listener): |
30 |
with self._lock: |
31 |
self._listeners.append(listener)
|
32 |
|
33 |
def remove_listener(self, listener): |
34 |
with self._lock: |
35 |
try:
|
36 |
self._listeners.remove(listener)
|
37 |
except ValueError: |
38 |
pass
|
39 |
|
40 |
def dispatch(self, event, *args, **kwds): |
41 |
try:
|
42 |
func = getattr(Listener, event)
|
43 |
with self._lock: |
44 |
for l in listeners: |
45 |
func(l, *args, **kwds) |
46 |
except AttributeError: |
47 |
pass
|
48 |
|
49 |
class Listener: |
50 |
|
51 |
"""Abstract class for NETCONF protocol message listeners, defining 2 events:
|
52 |
- reply
|
53 |
- error
|
54 |
"""
|
55 |
|
56 |
@override
|
57 |
def reply(self, *args, **kwds): |
58 |
raise NotImplementedError |
59 |
|
60 |
@override
|
61 |
def error(self, *args, **kwds): |
62 |
raise NotImplementedError |