Esempio n. 1
0
    def echo(self, msg):
        address = "some-address"

        #print "The message is %s type %s"% (msg, type(msg))
        class Handler(object):
            def handler_func(self, received):
                #print "received: %s type %s"% type(received.body, type(received.body))
                tu.check_context()
                EventBus.unregister_handler(self.id)
                received.reply(received.body)

        handler = Handler()
        handler.id = EventBus.register_handler(address,
                                               handler=handler.handler_func)

        def reply_handler(reply):
            #print "received reply %s type %s"% (reply.body, type(reply.body))
            if isinstance(reply.body, dict):
                for k, v in reply.body.iteritems():
                    tu.azzert(msg[k] == v)
            else:
                tu.azzert(msg == reply.body)
            tu.test_complete()

        EventBus.send(address, msg, reply_handler)
Esempio n. 2
0
def handler(msg):
    print "Received message"
    flights = JsonArray()
    for flight in msg.body:
        the_flight = JsonObject()
        #print str(flight)
        #the_flight.putString("name", flight.getString("callsign"))
        #the_flight.putString("planeType", flight.getString("equipment") )
        the_flight.putString("speed",
                             flight.get("properties").get("direction"))
        the_flight.putString("alt", flight.get("properties").get("route"))
        position_array = flight.get("geometry").get("coordinates")
        #print position_array

        #There can sometimes be two positions readings but I am not sure what they do so I am just going to take the first
        #position =  position_array[0]

        the_flight.putNumber("lat", position_array[1])
        the_flight.putNumber("lon", position_array[0])

        #build the object to persist to mongo
        forMongo = JsonObject()
        forMongo.putString("action", "save")
        forMongo.putString("collection", "buses")
        forMongo.putObject("document", the_flight)
        #persist it
        EventBus.publish('vertx.mongopersistor', forMongo)

        #add now to the array
        flights.addObject(the_flight)

    #Sent the array on the EventBus - this is the one the page should subscribe to
    EventBus.publish('flights.updated', flights)
    print("published the flights")
 def body_handler(body):
     if resp.status_code == 200:
         favs['favorites'] = json.loads(body.to_string())
     else:
         print "Failed to fetch favorites: %s" % body.to_string()
     EventBus.send('log.event', "user.favorites.list.result")
     EventBus.send('user.favorites.list.result', json.dumps(favs))
Esempio n. 4
0
   def deploy_handler(err, id):
       if err is None:
   #        import static_data
           print "loaded " + id
           def bla(reply,r2): print 'bla',reply,r2
           EventBus.send_with_timeout("campudus.jsonvalidator", {
 "action" : "addSchema",
 "key" : "simpleAddSchema",
 "jsonSchema" : {
   "$schema": "http://json-schema.org/draft-04/schema#",
   "title": "Example Schema",
   "type": "object",
   "properties": {
     "firstName": {
       "type": "string"
     },
     "lastName": {
       "type": "string"
     },
       "age": {
         "description": "Age in years",
         "type": "integer",
         "minimum": 0
       }
     },
     "required": ["firstName", "lastName"]
   }
   }, 1000, bla)
           EventBus.send("campudus.jsonvalidator", {"action":"getSchemaKeys"}, bla)
       else:
           print 'Failed to deploy %s' % err
           err.printStackTrace()
def album_delete_handler(reply):

    users = [ {
            'firstname': 'Michael',
            'lastname': 'Kuty',
            'email': '*****@*****.**',
            'username': '******',
            'password': '******'
        },{
            'firstname': 'Jakub',
            'lastname': 'Josef',
            'email': '*****@*****.**',
            'username': '******',
            'password': '******'
        },{
            'firstname': 'Test',
            'lastname': 'Test',
            'email': '*****@*****.**',
            'username': '******',
            'password': '******'
        }
    ]

    # Insert albums - in real life 'price' would probably be stored in a different collection, but, hey, this is a demo.
    for i in range(0, len(users)):
        EventBus.send('vertx.mongopersistor', {
            'action': 'save',
            'collection': 'users',
            'document': users[i]
        }, reply_handler=None)
Esempio n. 6
0
 def get_auth_uid(msg):
     if (msg.body != None):
         document["userID"] = msg.body
         def save_file_db(message):
             fs.move(filename, path_upload+msg.body+"/"+upload.filename, handler = None)
             #logger.info(message.body) 
         EventBus.send("vertx.mongopersistor", {"action": "save","collection":"files","document":document}, reply_handler=save_file_db)
Esempio n. 7
0
def init_autostart(config):
    for i, cfg in enumerate(config.get('autostart', [])):
        if not cfg.get('enabled', True):
            logger.info("Skipping disabled config #%d" % i)
            continue
        cfg['id'] = "autostart-" + str(i)
        EventBus.send('hbdriver:start', cfg, lambda msg: logger.info("Started hosebird for config #%d: %s" % (i, msg.body)))
def user_save_or_update(message):
    user = message.body.get("user", None)
    if 'password2' in user: del user['password2']
    #logger.info(user)
    def user_existss(msg):
        #logger.info(msg.body)
        if (msg.body == None):
            #logger.info(msg.body)
            def save_result_handler(msg):
                def login(login):
                    if "password" in user: del user["password"]
                    message.reply({"user":user,"sessionID":login.body}) 
                def reply(res):
                    logger.info(res.body)
                EventBus.send("login_user", {"username":user.get("username"),"password":user.get("password")}, login)
                EventBus.send("registration_mail",{"user":user},reply)
            EventBus.send("vertx.mongopersistor",{"action":"save", "collection":message.body.get("collection"), "document": user},save_result_handler)
        else: 
            #TODO upsert create new document when 0 result from criteria :-)
            update = {"action":"update", "collection": message.body.get("collection"),
                "criteria": {"_id": msg.body},
                "objNew" : user,
                "upsert": False,
                "multi": False
            }
            def update_result_handler(msg):
                message.reply(user.get('_id'))
            EventBus.send("vertx.mongopersistor",update,update_result_handler)
    EventBus.send("get_user_uid", {"username": user.get("username")}, user_existss)
def get_file(message):
    sessionID = message.body.get("sessionID", None)
    fileID = message.body.get("fileID", None)
    if (sessionID != None and fileID != None):
        def authorize_handler(msg):
            if (msg.body != None):
                def get_user_id(uid):
                    if (uid.body != None):
                        def reply_handler(msg):
                            logger.info(msg.body)
                            if msg.body != None:
                                message.reply(msg.body)
                            else: message.reply(None)
                        EventBus.send("get_file_from_db",{"fileID":fileID},reply_handler)
                    else: message.reply(None)
                EventBus.send("get_user_uid", {"username":msg.body}, get_user_id)
            else: message.reply(None)
        EventBus.send("local.authorize", {"sessionID":sessionID}, authorize_handler)
    elif (fileID != None):
        def reply_handler(msg):
            logger.info(msg.body)
            if msg.body != None:
                message.reply(msg.body)
            else: message.reply(None)
        EventBus.send("get_file_from_db",{"fileID":fileID},reply_handler)
Esempio n. 10
0
def handler(msg):
    print "Received message"
    flights = JsonArray()
    for flight in msg.body:
        the_flight = JsonObject()
        #print str(flight)
        #the_flight.putString("name", flight.getString("callsign"))
        #the_flight.putString("planeType", flight.getString("equipment") )
        the_flight.putString("speed", flight.get("properties").get("direction"))
        the_flight.putString("alt",  flight.get("properties").get("route"))
        position_array =  flight.get("geometry").get("coordinates")
        #print position_array

        #There can sometimes be two positions readings but I am not sure what they do so I am just going to take the first
        #position =  position_array[0]

        the_flight.putNumber("lat", position_array[1])
        the_flight.putNumber("lon", position_array[0])
        
        #build the object to persist to mongo
        forMongo = JsonObject()
        forMongo.putString("action", "save")
        forMongo.putString("collection", "buses")
        forMongo.putObject("document", the_flight)
        #persist it
        EventBus.publish('vertx.mongopersistor', forMongo)

        #add now to the array
        flights.addObject(the_flight)

    #Sent the array on the EventBus - this is the one the page should subscribe to
    EventBus.publish('flights.updated', flights)
    print("published the flights")
Esempio n. 11
0
    def test_reply_of_reply_of_reply(self):
        address = "some-address"

        def handler(msg):
            tu.azzert("message" == msg.body)

            def reply_handler1(reply):
                tu.azzert("reply-of-reply" == reply.body)
                reply.reply("reply-of-reply-of-reply")

            msg.reply("reply", reply_handler1)

        id = EventBus.register_handler(address, handler=handler)

        def reply_handler2(reply):
            tu.azzert("reply" == reply.body)

            def reply_handler3(reply2):
                tu.azzert("reply-of-reply-of-reply" == reply2.body)
                EventBus.unregister_handler(id)
                tu.test_complete()

            reply.reply("reply-of-reply", reply_handler3)

        EventBus.send(address, "message", reply_handler2)
Esempio n. 12
0
def mkdir_path(message):
    logger.info(message.body)
    sessionID = message.body.get("sessionID", None)
    if (sessionID == None): message.reply("sessionID is not valid")
    userID = ""
    def get_auth_uid(uid):
        if (uid.body == None): message.reply("AUTHORISE_FAIL")
        else:
            userID = uid.body
            if (userID != None):
                def exists_handler(msge):
                    if (msge.body == True) or (msge.body == False):
                        if (msge.body == True):
                            def mkdir_handler(result):
                                logger.info(result.body)
                                message.reply(result.body)
                            folder = message.body.get("name", None)
                            if (folder != None):
                                EventBus.send("mkdir_handler",{"userID":userID,"name":folder},mkdir_handler)
                        elif (msge.body == False): 
                            logger.info("must be created")
                            def mkdir_handler(result):
                                logger.info(result.body)
                                message.reply(result.body)
                            EventBus.send("mkdir_handler",{"userID":userID,"name":""},mkdir_handler)
                    else: message.reply("error")
            else: message.reply("error")

            EventBus.send("exists.handler", {"uid":uid.body} , exists_handler)
    EventBus.send("get_auth_uid", {"sessionID":sessionID}, get_auth_uid)
Esempio n. 13
0
 def handler_func(self, msg):
     tu.azzert(msg.address == address)
     tu.azzert(msg.body['message'] == json['message'])
     EventBus.unregister_handler(self.id)
     self.count[0] += 1
     if self.count[0] == num_handlers:
         tu.test_complete()
Esempio n. 14
0
 def handler_func(self, msg):
     tu.azzert(msg.address == address)
     tu.azzert(msg.body['message'] == json['message'])
     EventBus.unregister_handler(self.id)
     self.count[0] += 1
     if self.count[0] == num_handlers:
         tu.test_complete()
Esempio n. 15
0
def simple_search(message):
    matcher = None
    collection = message.body.get("collection", None)
    tmp_matcher = message.body.get("matcher", None)
    sessionID = message.body.get("sessionID", None)
    public = message.body.get("public", None)

    #use python $regex
    matcher = {
        "filename": {
            '$regex': tmp_matcher.get("filename"),
            '$options': 'ix'
        },
    }
    logger.info(public)
    if ((sessionID != None) and (collection != None) and (matcher != None)):
        def get_auth_uid(uid):
            if (uid.body == None): message.reply(None)
            else:
                userID = uid.body
                if (public == None):
                    matcher["public"] = True
                else:
                    matcher["userID"] = userID
                    matcher["public"] = False
                def reply_handler(msg):
                    message.reply(msg.body)
                EventBus.send("search",{"collection":collection,"matcher":matcher}, reply_handler)
        EventBus.send("get_auth_uid", {"sessionID":sessionID}, get_auth_uid)
    else:
        matcher["public"] = True
        def reply_handler(msg):
            message.reply(msg.body)
        EventBus.send("search",{"collection":collection,"matcher":matcher}, reply_handler)
Esempio n. 16
0
    def test_send_unregister_send(self):

        json = {'message': 'hello world!'}
        address = "some-address"
        self.received = False

        def handler(msg):
            if self.received:
                tu.azzert(False, "handler already called")
            tu.azzert(msg.address == address)
            tu.azzert(msg.body['message'] == json['message'])
            EventBus.unregister_handler(id)
            self.received = True

            def timer_complete(id):
                tu.test_complete()

            # End test on a timer to give time for other messages to arrive
            vertx.set_timer(100, timer_complete)

        id = EventBus.register_handler(address, handler=handler)
        tu.azzert(id != None)

        for i in range(0, 2):
            EventBus.send(address, json)
Esempio n. 17
0
 def upload_handler(upload):
     # create path for file with new name
     #TODO SEPARATION collections
     document = {
         "filename": upload.filename,
         "size": upload.size,
         "content_type":upload.content_type,
         "ext": upload.filename.split('.')[len(upload.filename.split('.'))-1],
         "content_transfer_encoding": upload.content_transfer_encoding,
         "charset": upload.charset,
         "create_time": date.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
         }
     if (sessionID == None):
         document["public"] = True
         document["_id"] = file_id
         def save_file_db(message):
             def mkdir_handler(err, mkdir_res):
                 if not err:
                     fs.move(filename, path_public+ file_id + "/" + upload.filename, handler = None)
             fs.mkdir(path_public + file_id + "/",perms=None,handler=mkdir_handler)
             #TODO create dir from uid in public section and move file into
         EventBus.send("vertx.mongopersistor", {"action": "save","collection":"files","document":document}, reply_handler=save_file_db)
     else:
         document["public"] = False
         def get_auth_uid(msg):
             if (msg.body != None):
                 document["userID"] = msg.body
                 def save_file_db(message):
                     fs.move(filename, path_upload+msg.body+"/"+upload.filename, handler = None)
                     #logger.info(message.body) 
                 EventBus.send("vertx.mongopersistor", {"action": "save","collection":"files","document":document}, reply_handler=save_file_db)
         EventBus.send("get_auth_uid", {"sessionID":sessionID}, get_auth_uid)
Esempio n. 18
0
def search(message):
    collection = message.body.get("collection")
    matcher = message.body.get("matcher")
    if (collection != None) and (matcher != None):
        def result_handler(msg):
            status = msg.body.get("status")
            if (status == "ok"):
                logger.info(msg.body.get("results"))
                #if (msg.body.get("results") == []): #message.reply("WARN")
                reply = {
                    "status": "ok",
                    "files": {}
                }
                files = []
                for res in msg.body.get("results"):
                    #del res["_id"]
                    files.append(res)
                reply["files"] = files
                message.reply(reply)
            else:
                logger.war("mongo fail %s"% status)
                message.reply(status)
        EventBus.send("vertx.mongopersistor", {"action":"find","collection":collection,"matcher":matcher},result_handler)
    else:
        message.reply("search wrong params")
Esempio n. 19
0
def login_handler(msg):
    user = msg.body
    id = vertx.config()['user-prefix'] + str(uuid.uuid4())
    users.add(user)
    EventBus.register_handler(id, 
                              handler=lambda msg: command_handler(user, msg))
    EventBus.publish(vertx.config()['users-address'], user)
    msg.reply({'id': id, 'users': list(users)})
Esempio n. 20
0
 def body_handler(body):
     if resp.status_code == 200:
         data = json.loads(body.to_string())
         print data
         def bla(reply): print dir(reply), reply.message
         EventBus.send("auth.github.login", data, bla)
     else:
         print resp.status_code, body.to_string()
Esempio n. 21
0
def unzip(filename, target, delete=None):
    def reply_handler(message):
            logger.info("unzip module result:  %s"%message.body)
            if delete: logger.info("zip will be deleted after success unzip")
    logger.info("send unzip message")
    if delete != None:
           EventBus.send('unzip.module', {"zipFile": filename,"destDir":target, "deleteZip": delete},reply_handler)
    else: EventBus.send('unzip.module', {"zipFile": filename,"destDir":target},reply_handler)
Esempio n. 22
0
 def save_result_handler(msg):
     def login(login):
         if "password" in user: del user["password"]
         message.reply({"user":user,"sessionID":login.body}) 
     def reply(res):
         logger.info(res.body)
     EventBus.send("login_user", {"username":user.get("username"),"password":user.get("password")}, login)
     EventBus.send("registration_mail",{"user":user},reply)
Esempio n. 23
0
def register_(public_actions):
	for package in public_actions:
		for module in package:
			#TODO IMPORT HERE
			for action in module:
				def reply(msg):
					logger.info(msg.body)
				EventBus.send("register_method",{"address:action","method":method,"module":module}, reply)
Esempio n. 24
0
def register_method(message):
	address = message.body.get("address", None)
	method = message.body.get("method", None)
	module = message.body.get("module", None)
	if (address != None and method != None and module != None):
		EventBus.register_handler(address, "%s.%s"% (module,method))
	else: 
		message.reply("register_method missing address or method or module")
 def terminate_epc_rx_session(self):
     request = {
         'requestType': 'RxSessionTermination',
         'SessionId': self.epc_rx_session_id
     }
     if EventBus:
         EventBus.send(self.epc_rx_send_address, request,
                       self.epc_rx_callback_handler)
Esempio n. 26
0
 def body_handler(body):
     print "JOO", body
     EventBus.send('smart.session.manager', {'action': 'start'}, bla)
     if resp.status_code == 200:
         data = json.loads(body.to_string())
         print data
     else:
         logger.error(body)
Esempio n. 27
0
 def exists_handler(msge):
     #logger.info(msge.body)
     if (msge.body == True):
         def mkdir_handler(result):
             logger.info(result.body)
             message.reply(result.body)
         EventBus.send("mkdir_handler",{"userID":userID},mkdir_handler)
     elif (msge.body == False): message.reply("user directory not found")
     else: message.reply(None)
def myHandler(message):
    finalPath = message.body['destinationFilePath']
    command= ("convert -scale 10% -scale 1000% " + message.body['originalFilePath'] + " " +  finalPath)
    os.system(command)

    EventBus.send("image.processing.completed",{'updatedName':message.body['updatedName'],'name':message.body['name']})

    print finalPath +" ::Finished"
    print "------------------------------------------"
Esempio n. 29
0
def command_handler(user, msg):
    body = msg.body
    status = 'unknown-command'
    if (body['command'] == 'say'):
        EventBus.publish(vertx.config()['messages-address'], 
                         {'user': user, 
                          'message': body['payload']})
        status = 'ok'
    msg.reply({'status': status})
def url_handler(req): # this is invoked by eventloop thread
        # read parameter from URI
        key = req.params['key']
        def reply_handler(message):
        	reply_handler_logic(req,message)
        print 'im url handler i will send message to event bus'
       	time.sleep(5)
       	print 'Im url handler. I just sent message to event bus'
        EventBus.send('call_bus',key,reply_handler)
Esempio n. 31
0
def get_file_from_db(message):
    fileID = message.body.get("fileID", None)
    def reply_handler(msg):
        file_props = msg.body.get("result", None)
        if (file_props == None):
            message.reply(None)
        elif (file_props != None): message.reply(file_props)
        else: logger.info("get_file_from_db error in result" )          
    EventBus.send('vertx.mongopersistor', {'action': 'findone', 'collection': 'files', 'matcher': {"_id":fileID}}, reply_handler)
Esempio n. 32
0
 def get_user_id(uid):
     if (uid.body != None):
         def reply_handler(msg):
             logger.info(msg.body)
             if msg.body != None:
                 message.reply(msg.body)
             else: message.reply(None)
         EventBus.send("get_file_from_db",{"fileID":fileID},reply_handler)
     else: message.reply(None)
Esempio n. 33
0
 def get_auth_uid(uid):
     if (uid.body == None): message.reply(None)
     else:
         userID = uid.body
         get_user_eb = EventBus.register_handler("get_user_private", handler = get_user)
         def user_handler(user):
             message.reply(user.body)
             EventBus.unregister_handler(get_user_eb)
         EventBus.send("get_user_private", {"userID":userID}, user_handler)
Esempio n. 34
0
 def authorize_handler(msg):
     if (msg.body != None):
         def get_user_id(uid):
             if (uid.body != None):
                 message.reply(uid.body)
             else: message.reply(None)
         EventBus.send("get_user_uid", {"username":msg.body}, get_user_id)
     else: 
         message.reply(None)
Esempio n. 35
0
def msg_handler(message):

    #actual received data
    data = message.body

    #turn the raw bytes into some text
    text = data.tostring()

    #pass along to output handler
    EventBus.send(output_address, text)
 def body_handler(body):
     global curators
     if resp.status_code == 200:
         data = json.loads(body.to_string())
         curators = []
         for user in data['users']:
             curators.append({'screen_name': user['screen_name'], 'id': user['id']})
         fetching.unlock()
         EventBus.send('log.event', "curators.list.result")
         EventBus.send('curators.list.result', json.dumps(curators))
def list_curators(message):
    global fetching
    if curators is None:
        if not fetching.testandset():
            return
        consumer = Consumer(api_endpoint="https://api.twitter.com/", consumer_key=config['consumer_key'], consumer_secret=config['consumer_secret'], oauth_token=config['oauth_token'], oauth_token_secret=config['oauth_token_secret'])
        consumer.get("/1.1/lists/members.json", {'slug': config['curatorslist'], 'owner_screen_name': config['account']}, response_handler)
    else:
        EventBus.send('log.event', "curators.list.result (Cached)")
        EventBus.send('curators.list.result', json.dumps(curators))
 def process_new_registered_ip_address(self, ip_address):
     if ip_address not in self.ip_address_list:
         self.ip_address_list.append(ip_address)
         request = {
             'requestType': 'RxSessionNewIPAddress',
             'SessionId': self.epc_rx_session_id,
             'ip_address': ip_address
         }
     if EventBus:
         EventBus.send(self.epc_rx_send_address, request,
                       self.epc_rx_callback_handler)
Esempio n. 39
0
    def test_deploy(self):
        def handler(message):
            if message.body == "started":
                tu.test_complete()

        EventBus.register_handler("test-handler", False, handler)
        conf = {'foo': 'bar'}

        def deploy_handler(err, ok):
            tu.azzert(err == None)

        vertx.deploy_verticle("core/deploy/child.py", conf, 1, deploy_handler)
Esempio n. 40
0
    def test_send_empty(self):
        json = {}
        address = "some-address"

        def handler(msg):
            tu.azzert(msg.body == {})
            EventBus.unregister_handler(id)
            tu.test_complete()

        id = EventBus.register_handler(address, handler=handler)
        tu.azzert(id != None)
        EventBus.send(address, json)
Esempio n. 41
0
 def _shutdown(self):
     logger.warn("Shutting down %s..." % self.address)
     EventBus.send(CredentialManager.ADDRESS, dict(command="release",
                                                   id=self.id))
     status = 200
     msg = None
     try:
         self.client.stop(100)
     except Exception, e:
         logger.error("Failed to stop: %s" % self.address, e)
         status = 500
         msg = str(e)
Esempio n. 42
0
    def test_simple_send(self):
        json = {'message': 'hello world!'}
        address = "some-address"

        def handler(msg):
            tu.azzert(msg.body['message'] == json['message'])
            EventBus.unregister_handler(id)
            tu.test_complete()

        id = EventBus.register_handler(address, handler=handler)
        tu.azzert(id != None)
        EventBus.send(address, json)
Esempio n. 43
0
        def handler(msg):
            if self.received:
                tu.azzert(False, "handler already called")
            tu.azzert(msg.body['message'] == json['message'])
            EventBus.unregister_handler(id)
            self.received = True

            def timer_complete(id):
                tu.test_complete()

            # End test on a timer to give time for other messages to arrive
            vertx.set_timer(100, timer_complete)
    def initiate(self):
        #if subscr_id is from EPC, initiate the EPC Rx Session
        self.logger.info("\n\n\n ip address list is %s\n\n" %
                         (str(self.ip_address_list)))

        request = {
            'requestType':
            'RxSessionInitiation',
            'SessionLifetime':
            self.epc_rx_session_lifetime,
            'SubscriptionID':
            self.subscr_id,
            'ue_ip_address':
            self.ip_address_list[0],
            'applicationIdentifier':
            self.app_id,
            'eventBusAddressRxEvent':
            self.epc_rx_callback_address,
            'ReferenceId':
            self.identifier,
            'MediaCompList':
            self.media_comp_list,
            'NetworkEventSubscriptions': [{
                'Event':
                'CHARGING_CORRELATION_AND_EXCHANGE'
            }, {
                'Event':
                'INDICATION_OF_LOSS_OF_BEARER'
            }, {
                'Event':
                'INDICATION_OF_RECOVERY_OF_BEARER'
            }, {
                'Event':
                'INDICATION_OF_RELEASE_OF_BEARER'
            }, {
                'Event': 'IP_CAN_CHANGE'
            }, {
                'Event':
                'INDICATION_OF_SUCCESSFUL_RESOURCE_ALLOCATION'
            }, {
                'Event':
                'INDICATION_OF_FAILED_RESOURCE_ALLOCATION'
            }, {
                'Event': 'ACCESS_NETWORK_INFO_REPORT'
            }, {
                'Event': 'IP_ADDRESS_INFO_REPORT'
            }]
        }
        self.logger.info("request is %s" % (request))

        if EventBus:
            EventBus.send(self.epc_rx_send_address, request,
                          self.epc_rx_callback_handler)
Esempio n. 45
0
def user_delete_handler(reply):
    # And a user
    EventBus.send('vertx.mongopersistor', {
        'action': 'save',
        'collection': 'users',
        'document': {
            'firstname': 'Tim',
            'lastname': 'Fox',
            'email': '*****@*****.**',
            'username': '******',
            'password': '******'
        }
    })
Esempio n. 46
0
def start_stream(msg):    
    cfg = msg.body
    
    def _on_credentials(cmsg):
        if cmsg.body['status'] == 200:
            client = HBCAgent(cfg, cmsg.body['credentials'])
            client.start()
            msg.reply(dict(status=200, clientAddress=client.address))
        else:
            msg.reply(dict(status=500, msg="Failure to acquire credentials", 
                           cause=cmsg.body))
        
    EventBus.send(CredentialManager.ADDRESS,
                  dict(command="acquire", id=cfg['id']),
                  _on_credentials)            
Esempio n. 47
0
def init_test_setup(config):
    if not config.get('testmode', False):
        return 

    def register(addr):
        def _wrapper(func):
            EventBus.register_handler(addr, handler=func)
            return func
        return _wrapper

    @register('test.tweets')
    def tweet_handler(msg):
        print msg.body

    @functools.partial(vertx.set_periodic, 1000)
    def status(tid):
        EventBus.publish(HBCAgent.STATUS_ADDRESS, dict(replyTo="test.status"))

    @register('test.status')
    def print_status(msg):
        print "Status >>>", msg.body

    @register('test.shutdown')
    def on_shutdown(msg):
        print "Shutdown >>>", msg.body
        vertx.exit()
        
    # simple shutdown hook
    exit_after = config.get('testmode').get('exitAfter', 10)
    if exit_after:
        vertx.set_timer(exit_after * 1000, 
                        lambda x: EventBus.publish(HBCAgent.SHUTDOWN_ADDRESS, 
                                                   dict(replyTo="test.shutdown")))
Esempio n. 48
0
    def test_handler_decorator(self):
        json = {'message': 'hello world!'}
        address = 'some-address'
        reply = {'cheese': 'stilton!'}

        @EventBus.handler(address)
        def handler(msg):
            tu.azzert(msg.address == address)
            tu.azzert(msg.body['message'] == json['message'])
            msg.reply(reply)

        def reply_handler(msg):
            tu.azzert(msg.body['cheese'] == reply['cheese'])
            tu.test_complete()

        EventBus.send(address, json, reply_handler)
Esempio n. 49
0
 def test_deploy(self):
     global handler_id
     def handler(message):
         if message.body == "started":
             tu.test_complete()
     handler_id = EventBus.register_handler("test-handler", False, handler)
     conf = {'foo' : 'bar'}
     vertx.deploy_verticle("core/deploy/child.py", conf)
Esempio n. 50
0
    def test_reply_timeout(self):
        json = {'message': 'hello world!'}
        address = 'some-address'
        reply = {'cheese': 'stilton!'}

        def handler(msg):
            tu.azzert(msg.body['message'] == json['message'])

        id = EventBus.register_handler(address, handler=handler)
        tu.azzert(id != None)

        def reply_handler(error, msg):
            tu.azzert(error != None)
            EventBus.unregister_handler(id)
            tu.test_complete()

        EventBus.send_with_timeout(address, json, 10, reply_handler)
Esempio n. 51
0
    def __init__(self, java_sock):
        self.java_obj = java_sock

        def simple_handler(msg):
            self.write(msg.body)

        self.handler_id = EventBus.register_simple_handler(
            True, simple_handler)
Esempio n. 52
0
    def test_empty_reply(self):
        json = {'message': 'hello world!'}
        address = "some-address"
        reply = {}

        def handler(msg):
            tu.azzert(msg.body['message'] == json['message'])
            msg.reply(reply)

        id = EventBus.register_handler(address, handler=handler)
        tu.azzert(id != None)

        def reply_handler(msg):
            tu.azzert(msg.body == {})
            EventBus.unregister_handler(id)
            tu.test_complete()

        EventBus.send(address, json, reply_handler)
Esempio n. 53
0
    def __init__(self, java_sock):
        self.java_obj = java_sock
        self.remote_addr = None
        self.local_addr = None

        def simple_handler(msg):
            self.write(msg.body)

        self.handler_id = EventBus.register_simple_handler(True, simple_handler)
Esempio n. 54
0
 def __init__(self, cfg, creds):
     self.id = cfg['id']
     self.cfg = cfg
     self.client = self._build_client(cfg, creds)
     self.address = "hbdriver:client:" + self.id
     self._handlers = []
     for addr, h in [(self.address, self.handler),
                     (self.STATUS_ADDRESS, self.status_handler),
                     (self.SHUTDOWN_ADDRESS, self.shutdown_handler)]:
         hid = EventBus.register_handler(addr, handler=h)
         self._handlers.append(hid)
Esempio n. 55
0
    def test_undeploy(self):
        print "in test undeploy"

        def handler(message):
            return

        EventBus.register_handler("test-handler", False, handler)

        conf = {'foo': 'bar'}

        def undeploy_handler(err):
            tu.azzert(err == None)
            tu.test_complete()

        def deploy_handler(err, id):
            tu.azzert(err == None)
            vertx.undeploy_verticle(id, handler=undeploy_handler)

        vertx.deploy_verticle("core/deploy/child.py",
                              conf,
                              handler=deploy_handler)
Esempio n. 56
0
    def echo(self, msg):
        address = "some-address"

        class Handler(object):
            def handler_func(self, received):
                tu.check_thread()
                EventBus.unregister_handler(self.id)
                received.reply(received.body)

        handler = Handler()
        handler.id = EventBus.register_handler(address,
                                               handler=handler.handler_func)

        def reply_handler(reply):
            if isinstance(reply.body, dict):
                for k, v in reply.body.iteritems():
                    tu.azzert(msg[k] == v)
            else:
                tu.azzert(msg == reply.body)
            tu.test_complete()

        EventBus.send(address, msg, reply_handler)
Esempio n. 57
0
    def test_send_multiple_matching_handlers(self):
        json = {'message': 'hello world!'}
        address = "some-address"
        num_handlers = 10
        count = [0]  # use an array to ensure pass by ref

        for i in range(0, num_handlers):

            class Handler(object):
                def __init__(self, count):
                    self.count = count

                def handler_func(self, msg):
                    tu.azzert(msg.body['message'] == json['message'])
                    EventBus.unregister_handler(self.id)
                    self.count[0] += 1
                    if self.count[0] == num_handlers:
                        tu.test_complete()

            handler = Handler(count)
            handler.id = EventBus.register_handler(
                address, handler=handler.handler_func)
        EventBus.publish(address, json)
Esempio n. 58
0
def album_delete_handler(reply):

    albums = [
        {
            'artist': 'The Wurzels',
            'genre': 'Scrumpy and Western',
            'title': 'I Am A Cider Drinker',
            'price': 0.99
        },
        {
            'artist': 'Vanilla Ice',
            'genre': 'Hip Hop',
            'title': 'Ice Ice Baby',
            'price': 0.01
        },
        {
            'artist': 'Ena Baga',
            'genre': 'Easy Listening',
            'title': 'The Happy Hammond',
            'price': 0.50
        },
        {
            'artist': 'The Tweets',
            'genre': 'Bird related songs',
            'title': 'The Birdy Song',
            'price': 1.20
        }
    ]

    # Insert albums - in real life 'price' would probably be stored in a different collection, but, hey, this is a demo.
    for i in range(0, len(albums)):
        EventBus.send('vertx.mongopersistor', {
            'action': 'save',
            'collection': 'albums',
            'document': albums[i]
        })