Revision 2bfd0fef

b/ncclient/glue.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
"TODO: docstring"
16

  
17
from cStringIO import StringIO
18
from Queue import Queue
19
from threading import Lock
20
from xml.etree import cElementTree as ET
21

  
22

  
23
def parse_root(raw):
24
    '''Parse the top-level element from a string representing an XML document.
25
    
26
    Returns a `(tag, attributes)` tuple, where `tag` is a string representing
27
    the qualified name of the root element and `attributes` is an
28
    `{attribute: value}` dictionary.
29
    '''
30
    fp = StringIO(raw)
31
    for event, element in ET.iterparse(fp, events=('start',)):
32
        return (element.tag, element.attrib)
33

  
34

  
35
class Subject:
36

  
37
    def __init__(self):
38
        "TODO: docstring"
39
        self._listeners = set([])
40
        self._outQ = Queue()
41
        self._lock = Lock()
42

  
43
    def _dispatch_received(self, raw):
44
        "TODO: docstring"
45
        root = parse_root(raw)
46
        with self._lock:
47
            listeners = list(self._listeners)
48
        for l in listeners:
49
            l.deliver(root, raw)
50
    
51
    def _dispatch_error(self, err):
52
        "TODO: docstring"
53
        with self._lock:
54
            listeners = list(self._listeners)
55
        for l in listeners:
56
            l.errback(err)
57
    
58
    def add_listener(self, listener):
59
        "TODO: docstring"
60
        with self._lock:
61
            self._listeners.add(listener)
62
    
63
    def remove_listener(self, listener):
64
        "TODO: docstring"
65
        with self._lock:
66
            self._listeners.discard(listener)
67
    
68
    def send(self, message):
69
        "TODO: docstring"
70
        logger.debug('queueing:%s' % message)
71
        self._outQ.put(message)
72

  
73

  
74
class Listener:
75
    
76
    def deliver(self, raw):
77
        raise NotImplementedError
78
    
79
    def errback(self, err):
80
        raise NotImplementedError

Also available in: Unified diff