Esempio n. 1
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. 2
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 start(self):
        #self.eventBus.registerHandler(self.address, self);
        self.config = VertxLocator.container.getConfig()
        self.engine = create_engine(self.db_path, echo=False)

        self.Session = sessionmaker(bind=self.engine)

        EventBus.register_handler(self.address, handler=self.handle)

        self.metadata.create_all(self.engine)
Esempio n. 4
0
    def register(self):
        def handler(msg):
            if not msg.body.has_key('error'):
                headers = { 'Authorization': 'token '+msg.body['access_token'] }
                get('https://api.github.com/user', handle_response, headers=headers)
                if 'email' in msg.body['scope']: pass
            else:
                logger.error(msg.body)

        EventBus.register_handler('auth.github.login', handler=handler)
Esempio n. 5
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)
    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. 7
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. 8
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. 9
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. 10
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. 11
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. 12
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. 13
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. 14
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. 15
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. 16
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. 17
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. 18
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. 19
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. 20
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. 21
0
    def test_reply(self):
        json = {'message' : 'hello world!'}
        address = "some-address"
        reply = {'cheese' : 'stilton!'}
        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['cheese'] == reply['cheese'])
            EventBus.unregister_handler(id)
            tu.test_complete()    
        EventBus.send(address, json, reply_handler)
Esempio n. 22
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. 23
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. 24
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)
def websocket_handler(socket):
    def getUUID():
        s = socket.toString()
        return s.split('@')[-1]

    uuid = getUUID()

    def send_mycommand(data, reply=None):
        message = {'uuid': uuid, 'message': data}
        if reply == None:
            EventBus.send('send.mycommand', message)
        else:
            EventBus.send('send.mycommand', message, reply)

    @socket.data_handler
    def data_handler(buff):
        resp_data = '%r' % buff
        send_mycommand(resp_data)
        print 'input:', resp_data

        if socket.write_queue_full:
            socket.pause()

            @socket.drain_handler
            def drain_handler():
                socket.resume()

    @socket.close_handler
    def close_handler():
        def closing(msg):
            EventBus.unregister_handler(resultHandleId)

        send_mycommand('clear', closing)
        print 'closed websocket', uuid

    def receive_result(msg):
        socket.write_text_frame(str(msg.body))

    resultHandleId = EventBus.register_handler('receive.myresult' + uuid,
                                               handler=receive_result)

    #send_mycommand('')
    print 'hello websocket', uuid
Esempio n. 26
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)
def websocket_handler(socket):

    def getUUID():
        s = socket.toString()
        return s.split('@')[-1]

    uuid = getUUID()

    def send_mycommand(data,reply=None):
        message = {'uuid':uuid,'message':data}
        if reply == None:
            EventBus.send('send.mycommand',message)
        else:
            EventBus.send('send.mycommand',message,reply)

    @socket.data_handler
    def data_handler(buff):
        resp_data = '%r'%buff
        send_mycommand(resp_data)
        print 'input:',resp_data

        if socket.write_queue_full:
            socket.pause()
            @socket.drain_handler
            def drain_handler():
                socket.resume()

    @socket.close_handler
    def close_handler():
        def closing(msg):
            EventBus.unregister_handler(resultHandleId)

        send_mycommand('clear',closing)
        print 'closed websocket',uuid

    def receive_result(msg):
        socket.write_text_frame(str(msg.body))

    resultHandleId = EventBus.register_handler('receive.myresult'+uuid,handler=receive_result)
    
    #send_mycommand('')
    print 'hello websocket',uuid
Esempio n. 28
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. 29
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. 30
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. 31
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.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. 32
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. 33
0
import vertx
from core.event_bus import EventBus

config = vertx.config()

event_bus_address = config['address']
output_address = config['output_address']


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)


id = EventBus.register_handler(event_bus_address, handler=msg_handler)
import vertx
from core.event_bus import EventBus

config = vertx.config()

event_bus_address = config['address'];
output_address = config['output_address'];

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);
    
id = EventBus.register_handler(event_bus_address, handler=msg_handler)
Esempio n. 35
0
 def __init__(self, credentials, address=ADDRESS):
     self._pool = list(credentials)
     self._inuse = {}
     EventBus.register_handler(address, handler=self.handle)
Esempio n. 36
0
# Copyright 2011 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import vertx
from core.event_bus import EventBus


def handler(msg):
    print 'Received news %s' % msg.body


EventBus.register_handler('news-feed', handler=handler)
Esempio n. 37
0
 def _wrapper(func):
     EventBus.register_handler(addr, handler=func)
     return func
Esempio n. 38
0
 def __init__(self, credentials, address=ADDRESS):
     self._pool = list(credentials)
     self._inuse = {}
     EventBus.register_handler(address, handler=self.handle)
Esempio n. 39
0
# Copyright 2011 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import vertx
from core.event_bus import EventBus


def handler(msg):
    print 'Received message %s' % msg.body
    # Now reply to it
    msg.reply('Pong!')


EventBus.register_handler('ping-address', handler=handler)
Esempio n. 40
0
        #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")


EventBus.register_handler('raw.flights', handler=handler)
Esempio n. 41
0
# Copyright 2011 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import vertx
from core.event_bus import EventBus

def handler(msg):
  print 'Subscriber verticle received msg : %s' % msg.body['body']  

EventBus.register_handler('foo-bar', handler=handler)
from com.xhaus.jyson import JysonCodec as json
from oauth import Consumer
from core.event_bus import EventBus
from util import parse_date
from datetime import datetime, timedelta

config = vertx.config()

curators = []
friends = []
aday = datetime.now() - timedelta(1)

def response_handler(resp, user_id):
    favs = {'user_id': user_id, 'favorites': []}
    @resp.body_handler
    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))
            
def fetch_favorites(message):
    user = message.body
    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/favorites/list.json", {'user_id': user['id'], 'count': 20}, lambda resp: response_handler(resp, user['id']))

EventBus.register_handler('user.favorites.list', False, fetch_favorites)

Esempio n. 43
0
public_actions = {
	"api": {
		"bus_utils": {
			"simple_search":"simple_search",
			"registration":"registration",
		}
	}
}

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)

#{address,method,package}
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")

register_method = EventBus.register_handler("register_method", handler= register_method)

Esempio n. 44
0
import vertx
from core.event_bus import EventBus

config = vertx.config()
client = vertx.create_http_client()
client.port = config['remote_port']
client.host = config['remote_host']

def command_response(resp):
    '''response of send command to analyzer
    '''
    @resp.body_handler
    def receive(buff):
        pass

def command_request(msg):
    '''send command to analyzer
    '''

    msg.reply('')
    send_data = msg.body.get('message')
    args = '?uuid=%s'%msg.body.get('uuid')

    request = client.post('/myconsole'+args, command_response)
    request.put_header('Content-Length',str(len(send_data)))
    request.write_str(send_data)
    request.end()

EventBus.register_handler('send.mycommand',handler=command_request)

Esempio n. 45
0
    if (email == None):
        EventBus.send(smtp_address, {"from": "*****@*****.**","to": to, "subject":subject,"body":body}, reply_status)
    else:
        def reply_handler(msg):
            logger.info("save email %s %s"% (message.body,msg.body))
        EventBus.send('vertx.mongopersistor', {'action': 'save', 'collection': 'emails',"document": message.body}, reply_handler)
        EventBus.send(smtp_address, {"from": "*****@*****.**","to": to, "subject":subject,"body":body}, reply_status)

#public
#{user}
#TODO template
def registration_mail(message):
    user = message.body.get("user", None)
    if (user == None): message.reply("user not specifed")
    else: 
        mail = {
            "to": user.get("email"),
            "body": "Thank you for registration %s please follow http://master.majklk.cz"% user.get("username"),
            "subject": "registration filehosting"
        }
        def reply(msg):
            message.reply(msg.body) #TODO rich reply
        EventBus.send("send_mail",mail,reply)

#TODO LINK MAIL
#TODO FORGOT PASS MAIL

#TODO propagation upstairs
#send_mail = EventBus.register_handler("send_mail", handler = send_mail)
registration_mail = EventBus.register_handler("registration_mail", handler = registration_mail)
import vertx
import os

from core.event_bus import EventBus


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 "------------------------------------------"

EventBus.register_handler('image.transform.pixelate', handler=myHandler)
Esempio n. 47
0
    
    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)            


EventBus.register_handler('hbdriver:start', handler=start_stream)


def init_controller(config):
    if config.get('webserver') is not None:
        start_server(config['webserver'])


def init_credmgr(config):
    mgr = CredentialManager([])    
    for cfg in config.get("credentials") or []:
        mgr.add(cfg)
    key = config.get("credentialsEnvVar")
    if not key:
        return
    try:
# coding=utf-8
"""
Re-tweetet tweets

@author Markus Tacker <*****@*****.**>
"""
import vertx
from oauth import Consumer
from core.event_bus import EventBus
from com.xhaus.jyson import JysonCodec as json

config = vertx.config()

def response_handler(resp):
    @resp.body_handler
    def body_handler(body):
        if resp.status_code == 200:
            data = json.loads(body.to_string())
            print "Retweeted https://twitter.com/%s/status/%d" % (data['retweeted_status']['user']['screen_name'], data['retweeted_status']['id'])
        else:
            print "ERROR! " + body.to_string()

def create_retweet(message):
    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.post("/1.1/statuses/retweet/%d.json" % message.body, None, response_handler)

EventBus.register_handler('retweet.create', False, create_retweet)

    def event_bus_reg(self):

        if EventBus:
            EventBus.register_handler(
                self.DEF_EVENT_BUS_EPC_Rx_CALLBACK_ADDRESS,
                handler=rx_callback_handler)
fetching = mutex.mutex()

def response_handler(resp):
    # TODO: Error handling 
    # print "got response %s" % resp.status_code
    # print resp.headers
    @resp.body_handler
    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))

EventBus.register_handler('curators.list', False, list_curators)
Esempio n. 51
0
import vertx
from core.event_bus import EventBus


def handler(msg):
    msg.reply("pong!")
    print "sent back pong Python!"


EventBus.register_handler("ping-address", handler=handler)
Esempio n. 52
0
        else: 
            message.reply(None)
    EventBus.send("local.authorize", {"sessionID":message.body.get("sessionID")}, authorize_handler)

#PRIVATE
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)

EventBus.register_handler("get_file_from_db", handler = get_file_from_db)

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)
Esempio n. 53
0
"""
Startet die App

@author Markus Tacker <*****@*****.**>
"""

import vertx
from core.event_bus import EventBus

def log_event(message):
    print ">> %s" % message.body

EventBus.register_handler('log.event', False, log_event)

config = vertx.config()

vertx.deploy_verticle("fetchcurators.py", config)
vertx.deploy_verticle("fetchfavorites.py", config)
vertx.deploy_verticle("fetchfriends.py", config)
vertx.deploy_verticle("fetchfavorites.py", config)
vertx.deploy_verticle("createfavorite.py", config)
vertx.deploy_verticle("createretweet.py", config)
vertx.deploy_verticle("publishretweets.py", config)