def mapChannel(self, channel):
        """Overridden so that channel is added as an attribute."""
        if hasattr(self, channel.name):
            raise ChannelError("Reserved attribute name '%s' cannot be used as a channel name." % channel.name)

        ChannelSet.mapChannel(self, channel)

        setattr(self, channel.name, channel.__call__)
    def mapChannel(self, channel):
        """Overridden so that channel is added as an attribute."""
        if hasattr(self, channel.name):
            raise ChannelError(
                "Reserved attribute name '%s' cannot be used as a channel name."
                % channel.name)

        ChannelSet.mapChannel(self, channel)

        setattr(self, channel.name, channel.__call__)
Exemple #3
0
class App(object):
    def __init__(self):
        self.channel_set = ChannelSet()
        rpc_channel = WsgiChannel('amf-channel')
        self.channel_set.mapChannel(rpc_channel)
        utils.setup_channel_set(self.channel_set)

    def __call__(self, environ, start_response):
        path = environ['PATH_INFO'].replace('/', '')

        if path == 'amf':
            channel = self.channel_set.getChannel('amf-channel')
            return channel(environ, start_response)
        else:
            channel = self.channel_set.getChannel('amf-channel')
            return channel.badPage(start_response, 'Page does not exist.')
Exemple #4
0
class App(object):
    def __init__(self):
        self.channel_set = ChannelSet()
        rpc_channel = WsgiChannel('amf-channel', endpoint=PyAmfEndpoint())
        self.channel_set.mapChannel(rpc_channel)
        utils.setup_channel_set(self.channel_set)

    def __call__(self, environ, start_response):
        path = environ['PATH_INFO'].replace('/', '')

        if path == 'amf':
            channel = self.channel_set.getChannel('amf-channel')
            return channel(environ, start_response)
        else:
            channel = self.channel_set.getChannel('amf-channel')
            return channel.badPage(start_response, 'Page does not exist.')
 def __init__(self, name, channel_name=None, *args, **kwargs):
     
     super(SimpleService, self).__init__(name, *args, **kwargs)
     self.channel = DjangoChannel(channel_name or name)
     self.channel_set = ChannelSet()
     self.channel_set.mapChannel(self.channel)
     self.channel_set.service_mapper.mapService(self)
Exemple #6
0
    def setUp(self):
        self.service_mapper = ServiceMapper()

        # Map example function to target
        self.target_name = 'Credentials'
        target = remoting.CallableTarget(self.login, self.target_name)

        # Map header targets
        self.service_mapper.packet_header_service.mapTarget(target)

        # Map message targets
        self.service_name = 'login'
        service = remoting.Service(self.service_name)
        service.mapTarget(target)
        self.service_mapper.mapService(service)

        # Valid values for the target
        self.arg = {'userid': 'userid', 'password': '******'}

        # Setup Encoder and Decoder
        self.channel_set = ChannelSet(service_mapper=self.service_mapper)
        self.channel = Channel('amf_rpc')
        self.channel_set.mapChannel(self.channel)
Exemple #7
0
    def setUp(self):
        self.service_mapper = ServiceMapper()

        # Map example function to target
        self.target_name = 'Credentials'
        target = remoting.CallableTarget(self.login, self.target_name)

        # Map header targets
        self.service_mapper.packet_header_service.mapTarget(target)

        # Map message targets
        self.service_name = 'login'
        service = remoting.Service(self.service_name)
        service.mapTarget(target)
        self.service_mapper.mapService(service)

        # Valid values for the target
        self.arg = {'userid': 'userid', 'password': '******'}

        # Setup Encoder and Decoder
        self.channel_set = ChannelSet(service_mapper=self.service_mapper)
        self.channel = Channel('amf_rpc')
        self.channel_set.mapChannel(self.channel)
Exemple #8
0
 def __init__(self):
     self.channel_set = ChannelSet()
     rpc_channel = WsgiChannel('amf-channel', endpoint=PyAmfEndpoint())
     self.channel_set.mapChannel(rpc_channel)
     utils.setup_channel_set(self.channel_set)
Exemple #9
0
import sys
import os

from amfast.remoting.channel import ChannelSet
from amfast.remoting.django_channel import DjangoChannel

import utils

channel_set = ChannelSet()
rpc_channel = DjangoChannel('amf')
channel_set.mapChannel(rpc_channel)
utils.setup_channel_set(channel_set)
Exemple #10
0
class RemotingTestCase(unittest.TestCase):

    def setUp(self):
        self.service_mapper = ServiceMapper()

        # Map example function to target
        self.target_name = 'Credentials'
        target = remoting.CallableTarget(self.login, self.target_name)

        # Map header targets
        self.service_mapper.packet_header_service.mapTarget(target)

        # Map message targets
        self.service_name = 'login'
        service = remoting.Service(self.service_name)
        service.mapTarget(target)
        self.service_mapper.mapService(service)

        # Valid values for the target
        self.arg = {'userid': 'userid', 'password': '******'}

        # Setup Encoder and Decoder
        self.channel_set = ChannelSet(service_mapper=self.service_mapper)
        self.channel = Channel('amf_rpc')
        self.channel_set.mapChannel(self.channel)

    def tearDown(self):
        pass

    def login(self, credentials):
        self.assertEquals(self.arg['userid'], credentials['userid'])
        self.assertEquals(self.arg['password'], credentials['password'])
        return True

    def testMapObjectExcludesAttr(self):
        test_service = remoting.Service('test')
        remoting.CallableTarget.mapObject(test_service, _mappingObj())
        self.assertEquals(None, test_service.getTarget('foo'))

    def testMapObjectExcludesPrivate(self):
        test_service = remoting.Service('test')
        remoting.CallableTarget.mapObject(test_service, _mappingObj())
        self.assertEquals(None, test_service.getTarget('_private'))

    def testMapObjectExcludesSpecial(self):
        test_service = remoting.Service('test')
        remoting.CallableTarget.mapObject(test_service, _mappingObj())
        self.assertEquals(None, test_service.getTarget('__init__'))

    def testMapObjectIncludesMethods(self):
        test_service = remoting.Service('test')
        remoting.CallableTarget.mapObject(test_service, _mappingObj(), map_private=True)
        self.assertTrue(isinstance(test_service.getTarget('_private'), remoting.Target))
        self.assertTrue(isinstance(test_service.getTarget('public'), remoting.Target))

    def testDecodeRpcPacket(self):
        encoded = '\x00\x00' # AMF0 version marker
        encoded += '\x00\x02' # Header count (2)
        encoded += '\x00\x04spam\x00\x00\x00\x00\x07\x02\x00\x04eggs' # Optional Header 
        encoded += '\x00\x04eggs\x01\x00\x00\x00\x07\x02\x00\x04spam' # Required Header
        encoded += '\x00\x02' # Body count (2)
        #1st message body
        encoded += '\x00\x04spam' # Body target
        encoded += '\x00\x04eggs' # Body response
        encoded += '\x00\x00\x00\x07' # Body byte length
        encoded += '\x0A\x00\x00\x00\x01' # Body start - 1 element array header
        encoded += '\x01\x01' # Body[0] 1 value
        #2nd message body
        encoded += '\x00\x04eggs' # Body 2 target
        encoded += '\x00\x04spam' # Body 2 response
        encoded += '\x00\x00\x00\x07' # Body 2 byte length
        encoded += '\x0A\x00\x00\x00\x01' # Body start - 1 element array header
        encoded += '\x01\x00' # Body 2 value

        packet = self.channel.endpoint.decodePacket(encoded)

        # version
        self.assertEquals(packet.FLASH_8, packet.client_type)

        # headers
        self.assertEquals('eggs', packet.headers[0].value)
        self.assertEquals(False, packet.headers[0].required)
        self.assertEquals('spam', packet.headers[0].name)

        self.assertEquals('spam', packet.headers[1].value)
        self.assertEquals(True, packet.headers[1].required)
        self.assertEquals('eggs', packet.headers[1].name)

        # messages
        self.assertEquals('spam', packet.messages[0].target)
        self.assertEquals('eggs', packet.messages[0].response)
        self.assertEquals(True, packet.messages[0].body[0])

        self.assertEquals('eggs', packet.messages[1].target)
        self.assertEquals('spam', packet.messages[1].response)
        self.assertEquals(False, packet.messages[1].body[0])

    def testDecodeReponsePacket(self):
        encoded = '\x00\x00' # AMF0 version marker
        encoded += '\x00\x01' # Header count
        encoded += '\x00\x04spam\x00\x00\x00\x00\x07\x02\x00\x04eggs' # Optional Header 
        encoded += '\x00\x01' # Body count
        #1st message body
        encoded += '\x00\x04spam' # Body target
        encoded += '\x00\x00' # Body response
        encoded += '\x00\x00\x00\x02' # Body byte length
        encoded += '\x01\x01' # Body value

        packet = self.channel.endpoint.decodePacket(encoded)

        # version
        self.assertEquals(packet.FLASH_8, packet.client_type)

        # headers
        self.assertEquals('eggs', packet.headers[0].value)
        self.assertEquals(False, packet.headers[0].required)
        self.assertEquals('spam', packet.headers[0].name)

        # messages
        self.assertEquals('spam', packet.messages[0].target)
        self.assertEquals('', packet.messages[0].response)
        self.assertEquals(True, packet.messages[0].body)

    def testRoundTripPacket(self):
        encoded = '\x00\x00' # AMF0 version marker
        encoded += '\x00\x02' # Header count (2)
        encoded += '\x00\x04spam\x00\x00\x00\x00\x07\x02\x00\x04eggs' # Optional Header 
        encoded += '\x00\x04eggs\x01\x00\x00\x00\x07\x02\x00\x04spam' # Required Header
        encoded += '\x00\x02' # Body count (2)
        #1st message body
        encoded += '\x00\x04spam' # Body target
        encoded += '\x00\x04eggs' # Body response
        encoded += '\x00\x00\x00\x07' # Body byte length
        encoded += '\x0A\x00\x00\x00\x01' # Body start - 1 element array header
        encoded += '\x01\x01' # Body[0] 1 value
        #2nd message body
        encoded += '\x00\x04eggs' # Body 2 target
        encoded += '\x00\x04spam' # Body 2 response
        encoded += '\x00\x00\x00\x07' # Body 2 byte length
        encoded += '\x0A\x00\x00\x00\x01' # Body start - 1 element array header
        encoded += '\x01\x00' # Body 2 value

        packet = self.channel.endpoint.decodePacket(encoded)
        encoded_packet = self.channel.endpoint.encodePacket(packet)
        self.assertEquals(encoded, encoded_packet)

    def testHeaderTarget(self):
        header = remoting.Header(self.target_name, False, self.arg)
        packet = remoting.Packet(headers=[header])
        packet.channel = self.channel
        packet.invoke()

    def testOldStyleTarget(self):
        qualified_name = self.service_name + '.' + self.target_name
        message = remoting.Message(target=qualified_name, response='/1',
            body=(self.arg,))
        packet = remoting.Packet(messages=[message])
        packet.channel = self.channel
        response = packet.invoke()
        
        self.assertEquals(1, len(response.messages))
        self.assertEquals(True, response.messages[0].target.endswith('onResult'))
        self.assertEquals('', response.messages[0].response)
        self.assertEquals(True, response.messages[0].body)

    def testOldStyleTargetFault(self):
        message = remoting.Message(target='bad_target', response='/1',
            body=(self.arg,))
        packet = remoting.Packet(messages=[message])
        packet.channel = self.channel
        response = packet.invoke()

        self.assertEquals(1, len(response.messages))
        self.assertEquals(True, response.messages[0].target.endswith('onStatus'))
        self.assertEquals('', response.messages[0].response)
        self.assertEquals(remoting.AsError, response.messages[0].body.__class__)

    def testRoTarget(self):
        outter_msg = remoting.Message(target='null', response='/1')
        inner_msg = messaging.RemotingMessage()
        inner_msg.destination = self.service_name
        inner_msg.operation = self.target_name
        inner_msg.headers = {self.target_name: self.arg, 'DSEndpoint': 'amf'}
        inner_msg.body = (self.arg,)
        inner_msg.messageId = '123'
        outter_msg.body = (inner_msg, )

        packet = remoting.Packet(messages=[outter_msg])
        packet.channel = self.channel
        response = packet.invoke()

        # Check outer msg
        self.assertEquals(1, len(response.messages))
        self.assertEquals(True, response.messages[0].target.endswith('onResult'))
        self.assertEquals('', response.messages[0].response)

        # Check inner msg
        self.assertEquals(True, response.messages[0].body.body)
        self.assertEquals('123', response.messages[0].body.correlationId)

    def testRoTargetFault(self):
        outter_msg = remoting.Message(target='null', response='/1')
        inner_msg = messaging.RemotingMessage()
        inner_msg.destination = 'fault'
        inner_msg.operation = self.target_name
        inner_msg.headers = {self.target_name: self.arg, 'DSEndpoint': 'amf'}
        inner_msg.body = (self.arg,)
        inner_msg.messageId = '123'
        outter_msg.body = (inner_msg, )

        packet = remoting.Packet(messages=[outter_msg])
        packet.channel = self.channel
        response = packet.invoke()

        # Check outer msg
        self.assertEquals(1, len(response.messages))
        self.assertEquals(True, response.messages[0].target.endswith('onStatus'))
        self.assertEquals('', response.messages[0].response)

        # Check inner msg
        self.assertEquals(messaging.ErrorMessage, response.messages[0].body.__class__)
        self.assertEquals('123', response.messages[0].body.correlationId)

    def testRoPing(self):
        outter_msg = remoting.Message(target='null', response='/1')
        inner_msg = messaging.CommandMessage()
        inner_msg.destination = self.service_name
        inner_msg.operation = messaging.CommandMessage.CLIENT_PING_OPERATION
        inner_msg.headers = {'DSEndpoint': 'amf'}
        inner_msg.body = ()
        inner_msg.messageId = '123'
        outter_msg.body = (inner_msg, )

        packet = remoting.Packet(messages=[outter_msg])
        packet.channel = self.channel
        response = packet.invoke()

        # Check outer msg
        self.assertEquals(1, len(response.messages))
        self.assertEquals(True, response.messages[0].target.endswith('onResult'))
        self.assertEquals('', response.messages[0].response)

        # Check inner msg
        self.assertEquals(messaging.AcknowledgeMessage, response.messages[0].body.__class__)
        self.assertEquals('123', response.messages[0].body.correlationId)

    def testProcessPacket(self):
        outter_msg = remoting.Message(target='null', response='/1')
        inner_msg = messaging.CommandMessage()
        inner_msg.destination = self.service_name
        inner_msg.operation = messaging.CommandMessage.CLIENT_PING_OPERATION
        inner_msg.headers = {'DSEndpoint': 'amf'}
        inner_msg.body = (None, )
        inner_msg.messageId = '123'
        outter_msg.body = (inner_msg, )

        packet = remoting.Packet(messages=[outter_msg])
        encoded_packet = self.channel.encode(packet)
        decoded_packet = self.channel.decode(encoded_packet)
        response = self.channel.invoke(decoded_packet)
        encoded_response = self.channel.encode(response)
        response = self.channel.endpoint.decodePacket(encoded_response)

        # Check outer msg
        self.assertEquals(1, len(response.messages))
        self.assertEquals(True, response.messages[0].target.endswith('onResult'))
        self.assertEquals('', response.messages[0].response)

        # Check inner msg
        self.assertEquals(messaging.AcknowledgeMessage, response.messages[0].body.__class__)
        self.assertEquals('123', response.messages[0].body.correlationId)
 def __init__(self, *args, **kwargs):
     self.clean_scheduled = False
     ChannelSet.__init__(self, *args, **kwargs)
Exemple #12
0
    amfast.log_debug = options.log_debug
   
    # Send log messages to STDOUT
    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(logging.DEBUG)
    amfast.logger.addHandler(handler)

    cp_options = {
        'global':
        {
            'server.socket_port': int(options.port),
            'server.socket_host': str(options.domain),
        },
        '/':
        {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.join(os.getcwd(), '../flex/deploy')
        }
    }

    channel_set = ChannelSet(notify_connections=True)
    stream_channel = StreamingWsgiChannel('stream-channel')
    channel_set.mapChannel(stream_channel)

    app = App()
    cherrypy.tree.graft(stream_channel, '/amf')
    cherrypy.quickstart(app, '/', config=cp_options)

    print "Serving on %s:%s" % (options.domain, options.port)
    print "Press ctrl-c to halt."
Exemple #13
0
class MessagingTestCase(unittest.TestCase):

    CHANNEL_NAME = 'channel'
    HTTP_CHANNEL_NAME = 'http_channel'
    TOPIC = 'topic'

    # Use the same ChannelSet for everything
    channel_set = ChannelSet()
    channel_set.mapChannel(Channel(CHANNEL_NAME))
    channel_set.mapChannel(HttpChannel(HTTP_CHANNEL_NAME))

    def setUp(self):
        self.channel_set.connection_manager.reset()
        self.channel_set.subscription_manager.reset()
        self.flex_client_id = 'my_client_id'

    def tearDown(self):
        pass

    def connect(self, channel_name):
        channel = self.channel_set.getChannel(channel_name)
        return channel.connect()

    def testConnect(self):
        connection = self.connect(self.CHANNEL_NAME)

        channel = self.channel_set.getChannel(self.CHANNEL_NAME)
        self.assertTrue(
            channel.channel_set.connection_manager.getConnectionCount(
                channel.name) > 0)

        channel = self.channel_set.getChannel(self.HTTP_CHANNEL_NAME)
        self.assertRaises(ChannelError, channel.connect, connection.id)

    def testDisconnect(self):
        connection = self.connect(self.CHANNEL_NAME)
        channel = self.channel_set.getChannel(self.CHANNEL_NAME)

        connection_count = channel.channel_set.connection_manager.getConnectionCount(
            channel.name)
        id = connection.id
        channel.disconnect(connection)

        self.assertEquals(
            connection_count - 1,
            channel.channel_set.connection_manager.getConnectionCount(
                channel.name))
        self.assertRaises(NotConnectedError,
                          self.channel_set.connection_manager.getConnection,
                          id)

    def testSubscribe(self):
        connection = self.connect(self.CHANNEL_NAME)
        self.channel_set.subscription_manager.subscribe(
            connection, self.flex_client_id, self.TOPIC)

    def testUnSubscribe(self):
        connection = self.connect(self.CHANNEL_NAME)
        self.channel_set.subscription_manager.subscribe(
            connection, self.flex_client_id, self.TOPIC)

        self.channel_set.subscription_manager.unSubscribe(
            connection, self.flex_client_id, self.TOPIC)

    def testPublish(self):
        connection = self.connect(self.CHANNEL_NAME)
        self.channel_set.subscription_manager.subscribe(
            connection.id, self.flex_client_id, self.TOPIC)

        self.channel_set.publishObject('test', self.TOPIC)
        msgs = self.channel_set.subscription_manager.pollConnection(connection)
        self.assertEquals(1, len(msgs))

    def testPoll(self):
        connection = self.connect(self.CHANNEL_NAME)
        self.channel_set.subscription_manager.subscribe(
            connection.id, self.flex_client_id, self.TOPIC)

        # Make sure messages are polled
        self.channel_set.publishObject('test', self.TOPIC)
        msgs = self.channel_set.subscription_manager.pollConnection(connection)
        self.assertEquals(1, len(msgs))

        # Make sure polled messages were deleted
        msgs = self.channel_set.subscription_manager.pollConnection(connection)
        self.assertEquals(0, len(msgs))
Exemple #14
0
 def __init__(self):
     self.channel_set = ChannelSet()
     rpc_channel = WsgiChannel('amf-channel')
     self.channel_set.mapChannel(rpc_channel)
     utils.setup_channel_set(self.channel_set)
 def __init__(self, *args, **kwargs):
     self.clean_scheduled = False
     ChannelSet.__init__(self, *args, **kwargs)
Exemple #16
0
class RemotingTestCase(unittest.TestCase):
    def setUp(self):
        self.service_mapper = ServiceMapper()

        # Map example function to target
        self.target_name = 'Credentials'
        target = remoting.CallableTarget(self.login, self.target_name)

        # Map header targets
        self.service_mapper.packet_header_service.mapTarget(target)

        # Map message targets
        self.service_name = 'login'
        service = remoting.Service(self.service_name)
        service.mapTarget(target)
        self.service_mapper.mapService(service)

        # Valid values for the target
        self.arg = {'userid': 'userid', 'password': '******'}

        # Setup Encoder and Decoder
        self.channel_set = ChannelSet(service_mapper=self.service_mapper)
        self.channel = Channel('amf_rpc')
        self.channel_set.mapChannel(self.channel)

    def tearDown(self):
        pass

    def login(self, credentials):
        self.assertEquals(self.arg['userid'], credentials['userid'])
        self.assertEquals(self.arg['password'], credentials['password'])
        return True

    def testMapObjectExcludesAttr(self):
        test_service = remoting.Service('test')
        remoting.CallableTarget.mapObject(test_service, _mappingObj())
        self.assertEquals(None, test_service.getTarget('foo'))

    def testMapObjectExcludesPrivate(self):
        test_service = remoting.Service('test')
        remoting.CallableTarget.mapObject(test_service, _mappingObj())
        self.assertEquals(None, test_service.getTarget('_private'))

    def testMapObjectExcludesSpecial(self):
        test_service = remoting.Service('test')
        remoting.CallableTarget.mapObject(test_service, _mappingObj())
        self.assertEquals(None, test_service.getTarget('__init__'))

    def testMapObjectIncludesMethods(self):
        test_service = remoting.Service('test')
        remoting.CallableTarget.mapObject(test_service,
                                          _mappingObj(),
                                          map_private=True)
        self.assertTrue(
            isinstance(test_service.getTarget('_private'), remoting.Target))
        self.assertTrue(
            isinstance(test_service.getTarget('public'), remoting.Target))

    def testDecodeRpcPacket(self):
        encoded = '\x00\x00'  # AMF0 version marker
        encoded += '\x00\x02'  # Header count (2)
        encoded += '\x00\x04spam\x00\x00\x00\x00\x07\x02\x00\x04eggs'  # Optional Header
        encoded += '\x00\x04eggs\x01\x00\x00\x00\x07\x02\x00\x04spam'  # Required Header
        encoded += '\x00\x02'  # Body count (2)
        #1st message body
        encoded += '\x00\x04spam'  # Body target
        encoded += '\x00\x04eggs'  # Body response
        encoded += '\x00\x00\x00\x07'  # Body byte length
        encoded += '\x0A\x00\x00\x00\x01'  # Body start - 1 element array header
        encoded += '\x01\x01'  # Body[0] 1 value
        #2nd message body
        encoded += '\x00\x04eggs'  # Body 2 target
        encoded += '\x00\x04spam'  # Body 2 response
        encoded += '\x00\x00\x00\x07'  # Body 2 byte length
        encoded += '\x0A\x00\x00\x00\x01'  # Body start - 1 element array header
        encoded += '\x01\x00'  # Body 2 value

        packet = self.channel.endpoint.decodePacket(encoded)

        # version
        self.assertEquals(packet.FLASH_8, packet.client_type)

        # headers
        self.assertEquals('eggs', packet.headers[0].value)
        self.assertEquals(False, packet.headers[0].required)
        self.assertEquals('spam', packet.headers[0].name)

        self.assertEquals('spam', packet.headers[1].value)
        self.assertEquals(True, packet.headers[1].required)
        self.assertEquals('eggs', packet.headers[1].name)

        # messages
        self.assertEquals('spam', packet.messages[0].target)
        self.assertEquals('eggs', packet.messages[0].response)
        self.assertEquals(True, packet.messages[0].body[0])

        self.assertEquals('eggs', packet.messages[1].target)
        self.assertEquals('spam', packet.messages[1].response)
        self.assertEquals(False, packet.messages[1].body[0])

    def testDecodeReponsePacket(self):
        encoded = '\x00\x00'  # AMF0 version marker
        encoded += '\x00\x01'  # Header count
        encoded += '\x00\x04spam\x00\x00\x00\x00\x07\x02\x00\x04eggs'  # Optional Header
        encoded += '\x00\x01'  # Body count
        #1st message body
        encoded += '\x00\x04spam'  # Body target
        encoded += '\x00\x00'  # Body response
        encoded += '\x00\x00\x00\x02'  # Body byte length
        encoded += '\x01\x01'  # Body value

        packet = self.channel.endpoint.decodePacket(encoded)

        # version
        self.assertEquals(packet.FLASH_8, packet.client_type)

        # headers
        self.assertEquals('eggs', packet.headers[0].value)
        self.assertEquals(False, packet.headers[0].required)
        self.assertEquals('spam', packet.headers[0].name)

        # messages
        self.assertEquals('spam', packet.messages[0].target)
        self.assertEquals('', packet.messages[0].response)
        self.assertEquals(True, packet.messages[0].body)

    def testRoundTripPacket(self):
        encoded = '\x00\x00'  # AMF0 version marker
        encoded += '\x00\x02'  # Header count (2)
        encoded += '\x00\x04spam\x00\x00\x00\x00\x07\x02\x00\x04eggs'  # Optional Header
        encoded += '\x00\x04eggs\x01\x00\x00\x00\x07\x02\x00\x04spam'  # Required Header
        encoded += '\x00\x02'  # Body count (2)
        #1st message body
        encoded += '\x00\x04spam'  # Body target
        encoded += '\x00\x04eggs'  # Body response
        encoded += '\x00\x00\x00\x07'  # Body byte length
        encoded += '\x0A\x00\x00\x00\x01'  # Body start - 1 element array header
        encoded += '\x01\x01'  # Body[0] 1 value
        #2nd message body
        encoded += '\x00\x04eggs'  # Body 2 target
        encoded += '\x00\x04spam'  # Body 2 response
        encoded += '\x00\x00\x00\x07'  # Body 2 byte length
        encoded += '\x0A\x00\x00\x00\x01'  # Body start - 1 element array header
        encoded += '\x01\x00'  # Body 2 value

        packet = self.channel.endpoint.decodePacket(encoded)
        encoded_packet = self.channel.endpoint.encodePacket(packet)
        self.assertEquals(encoded, encoded_packet)

    def testHeaderTarget(self):
        header = remoting.Header(self.target_name, False, self.arg)
        packet = remoting.Packet(headers=[header])
        packet.channel = self.channel
        packet.invoke()

    def testOldStyleTarget(self):
        qualified_name = self.service_name + '.' + self.target_name
        message = remoting.Message(target=qualified_name,
                                   response='/1',
                                   body=(self.arg, ))
        packet = remoting.Packet(messages=[message])
        packet.channel = self.channel
        response = packet.invoke()

        self.assertEquals(1, len(response.messages))
        self.assertEquals(True,
                          response.messages[0].target.endswith('onResult'))
        self.assertEquals('', response.messages[0].response)
        self.assertEquals(True, response.messages[0].body)

    def testOldStyleTargetFault(self):
        message = remoting.Message(target='bad_target',
                                   response='/1',
                                   body=(self.arg, ))
        packet = remoting.Packet(messages=[message])
        packet.channel = self.channel
        response = packet.invoke()

        self.assertEquals(1, len(response.messages))
        self.assertEquals(True,
                          response.messages[0].target.endswith('onStatus'))
        self.assertEquals('', response.messages[0].response)
        self.assertEquals(remoting.AsError,
                          response.messages[0].body.__class__)

    def testRoTarget(self):
        outter_msg = remoting.Message(target='null', response='/1')
        inner_msg = messaging.RemotingMessage()
        inner_msg.destination = self.service_name
        inner_msg.operation = self.target_name
        inner_msg.headers = {self.target_name: self.arg, 'DSEndpoint': 'amf'}
        inner_msg.body = (self.arg, )
        inner_msg.messageId = '123'
        outter_msg.body = (inner_msg, )

        packet = remoting.Packet(messages=[outter_msg])
        packet.channel = self.channel
        response = packet.invoke()

        # Check outer msg
        self.assertEquals(1, len(response.messages))
        self.assertEquals(True,
                          response.messages[0].target.endswith('onResult'))
        self.assertEquals('', response.messages[0].response)

        # Check inner msg
        self.assertEquals(True, response.messages[0].body.body)
        self.assertEquals('123', response.messages[0].body.correlationId)

    def testRoTargetFault(self):
        outter_msg = remoting.Message(target='null', response='/1')
        inner_msg = messaging.RemotingMessage()
        inner_msg.destination = 'fault'
        inner_msg.operation = self.target_name
        inner_msg.headers = {self.target_name: self.arg, 'DSEndpoint': 'amf'}
        inner_msg.body = (self.arg, )
        inner_msg.messageId = '123'
        outter_msg.body = (inner_msg, )

        packet = remoting.Packet(messages=[outter_msg])
        packet.channel = self.channel
        response = packet.invoke()

        # Check outer msg
        self.assertEquals(1, len(response.messages))
        self.assertEquals(True,
                          response.messages[0].target.endswith('onStatus'))
        self.assertEquals('', response.messages[0].response)

        # Check inner msg
        self.assertEquals(messaging.ErrorMessage,
                          response.messages[0].body.__class__)
        self.assertEquals('123', response.messages[0].body.correlationId)

    def testRoPing(self):
        outter_msg = remoting.Message(target='null', response='/1')
        inner_msg = messaging.CommandMessage()
        inner_msg.destination = self.service_name
        inner_msg.operation = messaging.CommandMessage.CLIENT_PING_OPERATION
        inner_msg.headers = {'DSEndpoint': 'amf'}
        inner_msg.body = ()
        inner_msg.messageId = '123'
        outter_msg.body = (inner_msg, )

        packet = remoting.Packet(messages=[outter_msg])
        packet.channel = self.channel
        response = packet.invoke()

        # Check outer msg
        self.assertEquals(1, len(response.messages))
        self.assertEquals(True,
                          response.messages[0].target.endswith('onResult'))
        self.assertEquals('', response.messages[0].response)

        # Check inner msg
        self.assertEquals(messaging.AcknowledgeMessage,
                          response.messages[0].body.__class__)
        self.assertEquals('123', response.messages[0].body.correlationId)

    def testProcessPacket(self):
        outter_msg = remoting.Message(target='null', response='/1')
        inner_msg = messaging.CommandMessage()
        inner_msg.destination = self.service_name
        inner_msg.operation = messaging.CommandMessage.CLIENT_PING_OPERATION
        inner_msg.headers = {'DSEndpoint': 'amf'}
        inner_msg.body = (None, )
        inner_msg.messageId = '123'
        outter_msg.body = (inner_msg, )

        packet = remoting.Packet(messages=[outter_msg])
        encoded_packet = self.channel.encode(packet)
        decoded_packet = self.channel.decode(encoded_packet)
        response = self.channel.invoke(decoded_packet)
        encoded_response = self.channel.encode(response)
        response = self.channel.endpoint.decodePacket(encoded_response)

        # Check outer msg
        self.assertEquals(1, len(response.messages))
        self.assertEquals(True,
                          response.messages[0].target.endswith('onResult'))
        self.assertEquals('', response.messages[0].response)

        # Check inner msg
        self.assertEquals(messaging.AcknowledgeMessage,
                          response.messages[0].body.__class__)
        self.assertEquals('123', response.messages[0].body.correlationId)
class SimpleService(Service):
    """
    An AMF Service class designed to circumvent the need for repeating the
    boilerplate code that AmFast requires. Get started in three steps:
    
    1) Instantiate a SimpleService with a name:

        >>> math_service = SimpleService('math')
        
    2) Define the callables that you want to expose through the service:
    
        >>> @math_service.expose
        ... def multiply(a, b):
        ...     return a * b
        ...
        
        By default, the name of the method is used for the name of the exposed
        method, although this can be overridden:
        
        >>> @math_service.expose('product')
        ... def multiply(a, b):
        ...     return a * b
        ...
        
    3) Map a URL to the service in your Django urlconf:
    
        >>> from django.conf.urls.defaults import *
        >>> urlpatterns = patterns('',
        ...     url(r'^math/$', math_service),
        ... )
    
    """
    
    VALID_FUNCTION_NAME_RE = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')
    
    def __init__(self, name, channel_name=None, *args, **kwargs):
        
        super(SimpleService, self).__init__(name, *args, **kwargs)
        self.channel = DjangoChannel(channel_name or name)
        self.channel_set = ChannelSet()
        self.channel_set.mapChannel(self.channel)
        self.channel_set.service_mapper.mapService(self)
        
    
    def __call__(self, *args, **kwargs):
        """
        SimpleService instances are callable in such a way that they can be
        used as Django views. When called, they simply delegate to the
        underlying DjangoChannel.
        
        """
        return self.channel(*args, **kwargs)
        
    
    def expose(self, name_or_function=None):
        """A decorator for exposing a callable as a service endpoint."""
        
        def _map_target(function, name=None):
            if name is None:
                # If no name is supplied, use the function name
                name = getattr(function, '__name__', '')                    
            if self.VALID_FUNCTION_NAME_RE.match(name) is None:
                # Check that function name is valid (lambda functions without
                # a supplied name will fail this test)
                raise ValueError("'%s' is not a valid target name" % name)
            self.mapTarget(CallableTarget(function, name))
                
        if callable(name_or_function):
            _map_target(name_or_function)
            return name_or_function
        else:
            def decorator(function):
                _map_target(function, name_or_function)
                return function
            return decorator
Exemple #18
0
 def __init__(self):
     self.channel_set = ChannelSet()
     rpc_channel = WsgiChannel('amf-channel')
     self.channel_set.mapChannel(rpc_channel)
     utils.setup_channel_set(self.channel_set)
Exemple #19
0
    (options, args) = parser.parse_args()

    amfast.log_debug = options.log_debug

    # Send log messages to STDOUT
    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(logging.DEBUG)
    amfast.logger.addHandler(handler)

    cp_options = {
        'global': {
            'server.socket_port': int(options.port),
            'server.socket_host': str(options.domain),
        },
        '/': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.join(os.getcwd(), '../flex/deploy')
        }
    }

    channel_set = ChannelSet(notify_connections=True)
    stream_channel = StreamingWsgiChannel('stream-channel')
    channel_set.mapChannel(stream_channel)

    app = App()
    cherrypy.tree.graft(stream_channel, '/amf')
    cherrypy.quickstart(app, '/', config=cp_options)

    print "Serving on %s:%s" % (options.domain, options.port)
    print "Press ctrl-c to halt."