# Path: hurricane/handlers/base.py
# class BaseHandler(object):
#     """Baseclass for all the handlers.  Each handler is guranteed to be
#     executed by one thread only so unless the header spawns threads, the
#     code does not have to be thread safe.
# 
#     Each handler class has one channel which is `HANDLER:import.name`
#     which is used by the default auto subscription process to subscribe
#     to the handler's channel.  As a matter of fact a handler is treaded
#     as a singleton when it comes to auto subscriptions.
#     """
# 
#     @classmethod
#     def channel(cls):
#         """The channel for a handler."""
#         return 'HANDLER:%s.%s' % (cls.__module__, cls.__name__)
# 
#     def __init__(self, settings, app_manager):
#         self.settings = settings
#         self.publisher = app_manager.publisher
#         self.subscription_manager = app_manager.get_subscription_manager(self)
#         self.auto_subscribe(app_manager)
# 
#     def auto_subscribe(self, app_manager):
#         """Called to subscribe the handlers on init."""
#         for handler in app_manager.handler_classes:
#             app_manager.subscribe(handler.channel(), self)
# 
#     def initialize(self):
#         """Called before the run to perform initialization."""
#         pass
# 
#     def run_base(self):
#         """Initializes and runs."""
#         self.initialize()
#         try:
#             self.run()
#         except KeyboardInterrupt:
#             pass
# 
#     def run(self):
#         """Runs the handler over the subscription manager."""
#         self.subscription_manager.run()
# 
#     def receive(self, msg):
#         """Called if the handler received data from any of the sources
#         it subscribed to.
#         """
#         pass
# 
#     def publish(self, msg):
#         """Helper method that publishes a message to its own channel."""
#         return self.publisher(self.channel(), msg)
# 
# Path: hurricane/base.py
# class Message(object):
#     def __init__(self, kind, timestamp, raw_data):
#         self.kind = kind
#         self.timestamp = timestamp
#         self.raw_data = raw_data
#         self.uuid = str(uuid.uuid4())
# 
#     def _asdict(self):
#         return {
#             'kind': self.kind,
#             'timestamp': self.timestamp,
#             'raw_data': self.raw_data,
#             'uuid': self.uuid,
#         }
#     
#     def __str__(self):
#         return str(self._asdict())
# 
#     def __repr__(self):
#         return '<%s %r>' % (type(self).__name__, str(self))
# 
# Path: hurricane/utils.py
# class RingBuffer(collections.deque):
#     """
#     inherits deque, pops the oldest data to make room for the newest data
#     when size is reached.
#  
#     http://www.daniweb.com/forums/post202523-3.html
#     """
#     def __init__(self, size):
#         collections.deque.__init__(self)
#         self.size = size
#  
#     def remove(self, item):
#         raise TypeError('you cannot remove an item from the ring buffer')
#  
#     def __delitem__(self, x):
#         raise TypeError('you cannot slice or delete from the ring buffer')
#  
#     def clear(self):
#         super(RingBuffer, self).clear()
#         self.append = type(self).append
#  
#     def _full_append(self, item):
#         collections.deque.append(self, item)
#         # full, pop the oldest item, left most item
#         self.popleft()
#  
#     def append(self, item):
#         collections.deque.append(self, item)
#         if len(self) == self.size:
#             self.append = self._full_append
#  
#     def after_match(self, func, full_fallback=False):
#         """Returns an iterator for all the elements after the first
#         match.  If `full_fallback` is `True`, it will return all the
#         messages if the function never matched.
#         """
#         iterator = iter(self)
#         for item in iterator:
#             if func(item):
#                 return iterator
#         if full_fallback:
#             iterator = iter(self)
#         return iterator
# 
# def json_timestamp(dt):
#     epoch = int(dt.strftime('%s'))
#     usec = dt.microsecond
#     timestamp = epoch + (usec / 1000000.0)
#     return timestamp


import datetime
from hurricane.handlers.base import BaseHandler
from hurricane.base import Message
from hurricane.utils import RingBuffer, json_timestamp

    def receive(self, msg):
        msg = msg._asdict()
        msg.update({
            'timestamp': json_timestamp(msg.pop('timestamp')),
        })
        if msg['kind'] == 'comet-GET':
            self.handle_GET(msg)
        elif msg['kind'] == 'comet-POST':
            self.handle_POST(msg)
        else:
            self.messages.append(msg)
    
    def handle_POST(self, msg):
        msg['raw_data'] = msg['raw_data']['body']
        self.messages.append(msg)
        message = Message(
            'comet-response',
            datetime.datetime.now(),
            {'messages': [msg]}
        )
        self.publish(message)
    
    def handle_GET(self, msg):
        cursor = msg['raw_data']['arguments'].get('cursor', ['null'])[0]
        messages = list(self.messages.after_match(lambda x: x['uuid'] == cursor,
                                                  full_fallback=True))
        if not messages:
            return


# Path: hurricane/handlers/base.py
# class BaseHandler(object):
#     """Baseclass for all the handlers.  Each handler is guranteed to be
#     executed by one thread only so unless the header spawns threads, the
#     code does not have to be thread safe.
# 
#     Each handler class has one channel which is `HANDLER:import.name`
#     which is used by the default auto subscription process to subscribe
#     to the handler's channel.  As a matter of fact a handler is treaded
#     as a singleton when it comes to auto subscriptions.
#     """
# 
#     @classmethod
#     def channel(cls):
#         """The channel for a handler."""
#         return 'HANDLER:%s.%s' % (cls.__module__, cls.__name__)
# 
#     def __init__(self, settings, app_manager):
#         self.settings = settings
#         self.publisher = app_manager.publisher
#         self.subscription_manager = app_manager.get_subscription_manager(self)
#         self.auto_subscribe(app_manager)
# 
#     def auto_subscribe(self, app_manager):
#         """Called to subscribe the handlers on init."""
#         for handler in app_manager.handler_classes:
#             app_manager.subscribe(handler.channel(), self)
# 
#     def initialize(self):
#         """Called before the run to perform initialization."""
#         pass
# 
#     def run_base(self):
#         """Initializes and runs."""
#         self.initialize()
#         try:
#             self.run()
#         except KeyboardInterrupt:
#             pass
# 
#     def run(self):
#         """Runs the handler over the subscription manager."""
#         self.subscription_manager.run()
# 
#     def receive(self, msg):
#         """Called if the handler received data from any of the sources
#         it subscribed to.
#         """
#         pass
# 
#     def publish(self, msg):
#         """Helper method that publishes a message to its own channel."""
#         return self.publisher(self.channel(), msg)
# 
# Path: hurricane/base.py
# class Message(object):
#     def __init__(self, kind, timestamp, raw_data):
#         self.kind = kind
#         self.timestamp = timestamp
#         self.raw_data = raw_data
#         self.uuid = str(uuid.uuid4())
# 
#     def _asdict(self):
#         return {
#             'kind': self.kind,
#             'timestamp': self.timestamp,
#             'raw_data': self.raw_data,
#             'uuid': self.uuid,
#         }
#     
#     def __str__(self):
#         return str(self._asdict())
# 
#     def __repr__(self):
#         return '<%s %r>' % (type(self).__name__, str(self))
# 
# Path: hurricane/utils.py
# class RingBuffer(collections.deque):
#     """
#     inherits deque, pops the oldest data to make room for the newest data
#     when size is reached.
#  
#     http://www.daniweb.com/forums/post202523-3.html
#     """
#     def __init__(self, size):
#         collections.deque.__init__(self)
#         self.size = size
#  
#     def remove(self, item):
#         raise TypeError('you cannot remove an item from the ring buffer')
#  
#     def __delitem__(self, x):
#         raise TypeError('you cannot slice or delete from the ring buffer')
#  
#     def clear(self):
#         super(RingBuffer, self).clear()
#         self.append = type(self).append
#  
#     def _full_append(self, item):
#         collections.deque.append(self, item)
#         # full, pop the oldest item, left most item
#         self.popleft()
#  
#     def append(self, item):
#         collections.deque.append(self, item)
#         if len(self) == self.size:
#             self.append = self._full_append
#  
#     def after_match(self, func, full_fallback=False):
#         """Returns an iterator for all the elements after the first
#         match.  If `full_fallback` is `True`, it will return all the
#         messages if the function never matched.
#         """
#         iterator = iter(self)
#         for item in iterator:
#             if func(item):
#                 return iterator
#         if full_fallback:
#             iterator = iter(self)
#         return iterator
# 
# def json_timestamp(dt):
#     epoch = int(dt.strftime('%s'))
#     usec = dt.microsecond
#     timestamp = epoch + (usec / 1000000.0)
#     return timestamp


# Path: demos/chat/handlers/chat.py
import datetime
from hurricane.handlers.base import BaseHandler
from hurricane.base import Message
from hurricane.utils import RingBuffer, json_timestamp


    def receive(self, msg):
        msg = msg._asdict()
        msg.update({
            'timestamp': json_timestamp(msg.pop('timestamp')),
        })
        if msg['kind'] == 'comet-GET':
            self.handle_GET(msg)
        elif msg['kind'] == 'comet-POST':
            self.handle_POST(msg)
        else:
            self.messages.append(msg)
    
    def handle_POST(self, msg):
        msg['raw_data'] = msg['raw_data']['body']
        self.messages.append(msg)
        message = Message(
            'comet-response',
            datetime.datetime.now(),
            {'messages': [msg]}
        )
        self.publish(message)
    
    def handle_GET(self, msg):
        cursor = msg['raw_data']['arguments'].get('cursor', ['null'])[0]
        messages = list(self.messages.after_match(lambda x: x['uuid'] == cursor,
                                                  full_fallback=True))
        if not messages:
            return


        message = Message(