def test_3_timeout(self): timeout = 0.2 client = Stomp(StompConfig(uri='failover:(tcp://localhost:61610,tcp://localhost:61613)?startupMaxReconnectAttempts=1,randomize=false', login=LOGIN, passcode=PASSCODE, version=StompSpec.VERSION_1_0)) client.connect(host=VIRTUALHOST, connectTimeout=timeout) client.disconnect() client = Stomp(StompConfig(uri='failover:(tcp://localhost:61610,tcp://localhost:61611)?startupMaxReconnectAttempts=1,backOffMultiplier=3', login=LOGIN, passcode=PASSCODE, version=StompSpec.VERSION_1_0)) self.assertRaises(StompConnectionError, client.connect, host=VIRTUALHOST, connectTimeout=timeout) client = Stomp(StompConfig(uri='failover:(tcp://localhost:61610,tcp://localhost:61613)?randomize=false', login=LOGIN, passcode=PASSCODE, version=StompSpec.VERSION_1_0)) # default is startupMaxReconnectAttempts = 0 self.assertRaises(StompConnectionError, client.connect, host=VIRTUALHOST, connectTimeout=timeout)
def queueFile(parameters): bucket = app.config['s3.bucket'] username = app.config['s3.username'] password = app.config['s3.password'] input_folder = app.config['s3.input_folder'] or '/comets/input/' if username and password: s3 = boto3.resource('s3', aws_access_key_id=username, aws_secret_access_key=password) else: s3 = boto3.resource('s3') s3.meta.client.upload_file( parameters['filepath'], bucket, input_folder + parameters['filename'], ) forQueue = json.dumps(parameters) client = Stomp( StompConfig('tcp://' + app.config['queue.host'] + ':' + str(app.config['queue.port']))) client.connect() client.send('/queue/Comets', forQueue, {'correlation-id': parameters['filename']}) client.disconnect()
def place_order(body): conn = get_connection() cursor = conn.cursor() sql = "Insert into orders (total_amount, created_on, status, email) values (%s, %s,%s,%s )" values = (body['total_amount'], body['created_on'], 'Ordered', body['email']) rows = cursor.execute(sql, values) order_id = cursor.lastrowid for row in body['products']: sql = "Insert into order_details (product_id, order_id, product_name, quantity, unit_cost) values (%s, %s, %s, %s, %s)" values = (row['product_id'], order_id, row['product_name'], row['quantity'], row['unit_cost']) rows = cursor.execute(sql, values) conn.commit() queue = '/queue/ordered' amq_conf = None # if isOpen('activemq-service.default', 61613): amq_conf = StompConfig('tcp://activemq-service.default:61613') #else: # amq_conf = StompConfig('tcp://localhost:30012') try: client = Stomp(amq_conf) client.connect() client.send(queue, str(order_id).encode()) client.disconnect() except: print("something went wrong") conn.close() return {'order_id': order_id}
def test_6_integration_stomp_1_1_encoding_and_escaping_headers(self): if BROKER == 'rabbitmq': print 'Broker does not support unicode characters. Skipping this test case.' return version = StompSpec.VERSION_1_1 client = Stomp(self.getConfig(version)) try: client.connect(host=VIRTUALHOST, versions=[version]) except StompProtocolError as e: print 'Broker does not support STOMP protocol %s. Skipping this test case. [%s]' % ( e, version) return specialCharactersHeader = u'fen\xeatre:\r\n' headers = {specialCharactersHeader: u'\xbfqu\xe9 tal?, s\xfc\xdf'} client.send(self.DESTINATION, body='test message 1', headers=headers) self.assertFalse(client.canRead(self.TIMEOUT)) token = client.subscribe( self.DESTINATION, { StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL }) self.assertTrue(client.canRead(self.TIMEOUT)) frame = client.receiveFrame() client.ack(frame) self.assertEquals(frame.version, version) self.assertEquals(frame.headers[specialCharactersHeader], headers[specialCharactersHeader]) self.assertFalse(client.canRead(self.TIMEOUT)) client.unsubscribe(token) client.disconnect(receipt='4712')
def _test_4_integration_stomp(self, version): client = Stomp(self.getConfig(version)) try: client.connect(host=VIRTUALHOST, versions=[version]) except StompProtocolError as e: print('Broker does not support STOMP protocol %s. Skipping this test case. [%s]' % (e, version)) return client.send(self.DESTINATION, b'test message 1') client.send(self.DESTINATION, b'test message 2') self.assertFalse(client.canRead(self.TIMEOUT)) token = client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}) self.assertTrue(client.canRead(self.TIMEOUT)) client.ack(client.receiveFrame()) self.assertTrue(client.canRead(self.TIMEOUT)) client.ack(client.receiveFrame()) self.assertFalse(client.canRead(self.TIMEOUT)) client.unsubscribe(token) client.send(self.DESTINATION, b'test message 3', receipt='4711') self.assertTrue(client.canRead(self.TIMEOUT)) self.assertEqual(client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {StompSpec.RECEIPT_ID_HEADER: '4711'})) self.assertFalse(client.canRead(self.TIMEOUT)) client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}) self.assertTrue(client.canRead(self.TIMEOUT)) client.ack(client.receiveFrame()) self.assertFalse(client.canRead(self.TIMEOUT)) client.disconnect(receipt='4712') self.assertEqual(client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {StompSpec.RECEIPT_ID_HEADER: '4712'})) self.assertRaises(StompConnectionError, client.receiveFrame) client.connect(host=VIRTUALHOST) client.disconnect(receipt='4711') self.assertEqual(client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {StompSpec.RECEIPT_ID_HEADER: '4711'})) client.close() self.assertRaises(StompConnectionError, client.canRead, 0)
def test_3_socket_failure_and_replay(self): client = Stomp(self.getConfig(StompSpec.VERSION_1_0)) client.connect(host=VIRTUALHOST) headers = {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL} token = client.subscribe(self.DESTINATION, headers) client.sendFrame( StompFrame(StompSpec.DISCONNECT) ) # DISCONNECT frame is out-of-band, as far as the session is concerned -> unexpected disconnect self.assertRaises(StompConnectionError, client.receiveFrame) client.connect(host=VIRTUALHOST) client.send(self.DESTINATION, 'test message 1') client.ack(client.receiveFrame()) client.unsubscribe(token) headers = { StompSpec.ID_HEADER: 'bla', StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL } client.subscribe(self.DESTINATION, headers) headers[StompSpec.DESTINATION_HEADER] = self.DESTINATION client.sendFrame( StompFrame(StompSpec.DISCONNECT) ) # DISCONNECT frame is out-of-band, as far as the session is concerned -> unexpected disconnect self.assertRaises(StompConnectionError, client.receiveFrame) client.connect(host=VIRTUALHOST) client.send(self.DESTINATION, 'test message 2') client.ack(client.receiveFrame()) client.unsubscribe((StompSpec.ID_HEADER, 'bla')) client.disconnect()
def run(self): client = Stomp(self.config) client.connect() headers = { # client-individual mode is necessary for concurrent processing # (requires ActiveMQ >= 5.2) StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL, # the maximal number of messages the broker will let you work on at # the same time 'activemq.prefetchSize': '100', } client.subscribe(config['queue']['BotNet'], headers) while True: frame = client.receiveFrame() data = json.loads(frame.body) body = data.get('body') if body and data.get('action') == 'update' and \ body.get('func_name') == 'updater.receive' and \ body.get('func_args'): args = body.get('func_args') if args.get('data'): doc_pin = args['data']['objects'][0]['id'] Storage().remove(doc_pin) client.ack(frame)
def __init__(self, config): """Init the Stompest wrapper client. :type config: dict :param config: The configuration for the STOM client. I.e. {'host': 'tcp://127.0.0.1', 'queue': '/queue/test', 'transaction': True, 'username': '******', 'password': '******'} The transaction attribute defines if messages should be published in transactions. """ self.host = config['host'] self.queue = config['queue'] self.transactions_enabled = config['transaction'] self.transaction = None auth_header = {} if 'username' in config and 'password' in config: auth_header.update( {StompSpec.LOGIN_HEADER: config['username'], StompSpec.PASSCODE_HEADER: config['password']}) self.client = Stomp(StompConfig(self.host)) try: self.client.connect(headers=auth_header) except (error.StompConnectTimeout, error.StompProtocolError) as e: raise ClientErrors.ConnectionError( "Could not connect to broker: %s" % e)
def test_6_integration_stomp_1_1_encoding_and_escaping_headers(self): if BROKER == 'rabbitmq': print('Broker does not support unicode characters. Skipping this test case.') return version = StompSpec.VERSION_1_1 client = Stomp(self.getConfig(version)) try: client.connect(host=VIRTUALHOST, versions=[version]) except StompProtocolError as e: print('Broker does not support STOMP protocol %s. Skipping this test case. [%s]' % (e, version)) return key = b'fen\xc3\xaatre'.decode('utf-8') value = b'\xc2\xbfqu\xc3\xa9 tal?'.decode('utf-8') headers = {key: value} client.send(self.DESTINATION, body=b'test message 1', headers=headers) self.assertFalse(client.canRead(self.TIMEOUT)) token = client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}) self.assertTrue(client.canRead(self.TIMEOUT)) frame = client.receiveFrame() client.ack(frame) self.assertEqual(frame.version, version) self.assertEqual(frame.headers[key], headers[key]) self.assertFalse(client.canRead(self.TIMEOUT)) client.unsubscribe(token) client.disconnect(receipt='4712')
def send(self): """ Create a new stomp configuration client, connect and then serializes message by message posting them to your consumers in TOPIC standard and disconnect. """ try: configuration = StompConfig(uri=self._broker_uri) client = Stomp(configuration) client.connect(connectTimeout=self._broker_timeout) for message in self._queue: serialized_message = json.dumps(message, ensure_ascii=False) client.send(self._queue_destination, serialized_message) client.disconnect() except Exception, e: self.log.error( u'QueueManagerError - Error on sending objects from queue.') self.log.debug(e) raise Exception( 'QueueManagerError - Error on sending objects to queue.')
def Producer(account, message): def documentCreateNotice(): result = dict(body=dict(func_name="documentCreateNotice", func_args=[{ "doc_type": "importEmail" }]), recipient="*", profile="user", tag="grendizer") return json.dumps(result) def Send_Notify(message): result = dict(body=dict(func_name="toastr.info", func_args=[message]), recipient="*", profile="user", tag="grendizer") return json.dumps(result) def clearNotice(): result = dict(body=dict(func_name="toastr.clear", func_args=[]), recipient="*", profile="user", tag="grendizer") return json.dumps(result) send_notify = Send_Notify(message) clear_notice = clearNotice() notice = documentCreateNotice() logger.debug(u"Отправляем сообщение: %s" % message) client = Stomp(StompConfig(default_uri)) client.connect() client.send(queue, notice) client.send(queue, send_notify) client.send(queue, clear_notice) client.disconnect()
def __init__(self, namespace, login, passcode, broker_hosts=DEFAULT_BROKER_HOSTS): self.namespace = str(namespace) for broker_host in broker_hosts: broker_url = 'tcp://%s:61613' % broker_host self.CONFIG = StompConfig(broker_url, version=StompSpec.VERSION_1_2) self.client = Stomp(self.CONFIG) try: # Convention: set vhost to the namespace. This will require a message-boss consuming on this vhost!!! vhost = namespace self.client.connect(headers={ 'login': login, 'passcode': passcode }, host=vhost) print "Connected to %s using protocol version %s" % ( broker_host, self.client.session.version) except StompConnectionError: pass
def init(self, host, port, username=None, password=None, connect_timeout=3, connected_timeout=3, version=StompSpec.VERSION_1_2, accept_versions=["1.0", "1.1", "1.2"], heartbeats=(0, 0), ssl_context=None, use_ssl=True, key_file=None, cert_file=None, ca_certs=None, ssl_version=ssl.PROTOCOL_SSLv23, key_file_password=None, proxy_host=None, proxy_port=None, proxy_user=None, proxy_password=None, channel=channel): """ Initialize StompClient. Called after __init__ """ self.channel = channel if proxy_host: LOG.info("Connect to %s:%s through proxy %s:%d", host, port, proxy_host, proxy_port) else: LOG.info("Connect to %s:%s", host, port) if use_ssl and not ssl_context: ssl_params = dict(key_file=key_file, cert_file=cert_file, ca_certs=ca_certs, ssl_version=ssl_version, password=key_file_password) LOG.info("Request to use old-style socket wrapper: %s", ssl_params) ssl_context = ssl_params if use_ssl: uri = "ssl://%s:%s" % (host, port) else: uri = "tcp://%s:%s" % (host, port) # Configure failover options so it only tries to connect once self._stomp_server = "failover:(%s)?maxReconnectAttempts=1,startupMaxReconnectAttempts=1" % uri self._stomp_config = StompConfig(uri=self._stomp_server, sslContext=ssl_context, version=version, login=username, passcode=password) self._heartbeats = heartbeats self._accept_versions = accept_versions self._connect_timeout = connect_timeout self._connected_timeout = connected_timeout Stomp._transportFactory = EnhancedStompFrameTransport Stomp._transportFactory.proxy_host = proxy_host Stomp._transportFactory.proxy_port = proxy_port Stomp._transportFactory.proxy_user = proxy_user Stomp._transportFactory.proxy_password = proxy_password self._client = Stomp(self._stomp_config) self._subscribed = {} self.server_heartbeat = None self.client_heartbeat = None self.ALLOWANCE = 2 # multiplier for heartbeat timeouts
def get_stomp_conn(): mqcfg = settings.MESSAGE_QUEUE config = StompConfig(mqcfg['url'], login=mqcfg['username'], passcode=mqcfg['password']) stomp = Stomp(config) stomp.connect(host=mqcfg['broker']) return stomp
def _get_timeouting_connect_mock(self): stomp = Stomp(CONFIG) stomp._transportFactory = mock.Mock() transport = stomp._transportFactory.return_value = mock.Mock() transport.host = 'mock' transport.port = 0 transport.canRead.return_value = False return stomp
def test_2_transaction(self): config = self.getConfig(StompSpec.VERSION_1_0) client = Stomp(config) client.connect(host=VIRTUALHOST) client.subscribe( self.DESTINATION, {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}) self.assertFalse(client.canRead(self.TIMEOUT)) with client.transaction(4711) as transaction: self.assertEquals(transaction, '4711') client.send(self.DESTINATION, 'test message', {StompSpec.TRANSACTION_HEADER: transaction}) self.assertFalse(client.canRead(0)) self.assertTrue(client.canRead(self.TIMEOUT)) frame = client.receiveFrame() self.assertEquals(frame.body, 'test message') client.ack(frame) with client.transaction(4713, receipt='4712') as transaction: self.assertEquals(transaction, '4713') self.assertEquals( client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {StompSpec.RECEIPT_ID_HEADER: '4712-begin'})) client.send(self.DESTINATION, 'test message', {StompSpec.TRANSACTION_HEADER: transaction}) client.send(self.DESTINATION, 'test message without transaction') self.assertTrue(client.canRead(self.TIMEOUT)) frame = client.receiveFrame() self.assertEquals(frame.body, 'test message without transaction') client.ack(frame) self.assertFalse(client.canRead(0)) frames = [client.receiveFrame() for _ in xrange(2)] frames = list(sorted(frames, key=lambda f: f.command)) frame = frames[0] client.ack(frame) self.assertEquals(frame.body, 'test message') frame = frames[1] self.assertEquals( frame, StompFrame(StompSpec.RECEIPT, {StompSpec.RECEIPT_ID_HEADER: '4712-commit'})) try: with client.transaction(4714) as transaction: self.assertEquals(transaction, '4714') client.send(self.DESTINATION, 'test message', {StompSpec.TRANSACTION_HEADER: transaction}) raise RuntimeError('poof') except RuntimeError as e: self.assertEquals(str(e), 'poof') else: raise self.assertFalse(client.canRead(self.TIMEOUT)) client.disconnect()
def test(size): config = StompConfig("tcp://%s:%d" % (ACTIVEMQ_HOST, ACTIVEMQ_PORT)) client = Stomp(config) client.connect() msg = "0" * size for i in range(0, COUNT): client.send(TOPIC, msg) client.send(TOPIC, "quit") client.disconnect()
def send(data): mqcfg = settings.MESSAGE_QUEUE config = StompConfig(mqcfg['url'], login=mqcfg['username'], passcode=mqcfg['password']) stomp = Stomp(config) stomp.connect(host=mqcfg['broker']) stomp.send(mqcfg['vote_queue'], json.dumps(data)) stomp.disconnect()
def _get_connect_mock(self, receive=None, config=None): stomp = Stomp(config or CONFIG) stomp._transportFactory = Mock() transport = stomp._transportFactory.return_value = Mock() transport.host = 'mock' transport.port = 0 if receive: transport.receive.return_value = receive return stomp
def setUp(self): config = self.getConfig(StompSpec.VERSION_1_0) client = Stomp(config) client.connect(host=VIRTUALHOST) client.subscribe(self.DESTINATION, {StompSpec.ACK_HEADER: StompSpec.ACK_AUTO}) client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 'bla', StompSpec.ACK_HEADER: StompSpec.ACK_AUTO}) while client.canRead(self.TIMEOUT): frame = client.receiveFrame() self.log.debug('Dequeued old %s' % frame.info()) client.disconnect()
def recv_stomp(): config = StompConfig(stomp_uri) client = Stomp(config) client.connect() client.subscribe(stomp_source, {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}) frame = client.receiveFrame() print "Received: {}".format(frame.info()) client.ack(frame) client.disconnect()
def run(self, messages=None): client = Stomp(self.config) client.connect() j = 0 for message in messages: client.send(queue, message, receipt='message-asterisk-%d' % j, headers={'persistent': 'true'}) j = j + 1 client.disconnect(receipt='bye')
def establishConnection(self, address='localhost', port=61613): dataTest = 'Hello World!' print('endereco: ' + address) print('porta: ' + str(port)) print('dados: ' + dataTest) config = StompConfig('tcp://{}:{}'.format(address, port)) self.client = Stomp(config) self.client.connect() self.client.send(self.queue, dataTest.encode())
def _conn(cfg_uri, queue, _info): from stompest.config import StompConfig from stompest.sync import Stomp _info('Init Stomp obj: [%s-%s]' % (cfg_uri, queue)) client = Stomp(StompConfig(cfg_uri)) _info('connecting... %s' % cfg_uri) client.connect() _info('connected %s' % cfg_uri) return client
def __init__(self, tb, host='127.0.0.1', port=61613): self.tb = tb self.config = StompConfig('tcp://%s:%s' % (host, port)) self.client = Stomp(self.config) self.client.connect() threading.Thread.__init__(self) self.setDaemon(1) self.start()
def connect(self, mq_name, selector=None): self.rsp_queue = config.mq.get(mq_name) self.client = Stomp(StompConfig(config.mq.get('stomp'))) self.client.connect() spec = {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL} if selector: spec[StompSpec.SELECTOR_HEADER] = "%s='%s'" % selector self.client.subscribe(self.rsp_queue, spec) print 'Consumer [%s] waiting for messages ...' % self.rsp_queue
def test(): config = StompConfig("tcp://%s:%d" % (ACTIVEMQ_HOST, ACTIVEMQ_PORT)) client = Stomp(config) client.connect() client.subscribe(TOPIC, {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}) while True: f = client.receiveFrame() client.ack(f) if f.body == "quit": client.disconnect() break
def __init__(self, selk, selv, config=None, queue=None): ''' Constructor ''' if config is not None: self.CONFIG = config if queue is not None: self.QUEUE = queue self.client = Stomp(self.CONFIG) self.client.connect() self.selk = selk self.selv = selv
def init_connection(self): if (self.client != None and self.client.session.state == 'connected'): try: self.client.disconnect() except: pass config = StompConfig('tcp://%s:%s' % (self.host, self.port), version=StompSpec.VERSION_1_1, check=True) self.client = Stomp(config) self.client.connect(heartBeats=(30000, 0), connectTimeout=1, connectedTimeout=1)
def test_1_integration(self): config = self.getConfig(StompSpec.VERSION_1_0) client = Stomp(config) client.connect(host=VIRTUALHOST) client.send(self.DESTINATION, b'test message 1') client.send(self.DESTINATION, b'test message 2') self.assertFalse(client.canRead(self.TIMEOUT)) client.subscribe(self.DESTINATION, {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}) self.assertTrue(client.canRead(self.TIMEOUT)) client.ack(client.receiveFrame()) self.assertTrue(client.canRead(self.TIMEOUT)) client.ack(client.receiveFrame()) self.assertFalse(client.canRead(self.TIMEOUT))