def conn(): conn = stomp.Connection11(get_rabbitmq_host()) conn.set_listener("testlistener", TransformationListener("123", print_to_log=True)) conn.connect(get_rabbitmq_user(), get_rabbitmq_password(), wait=True) yield conn conn.disconnect(receipt=None)
def conn2(): conn2 = stomp.Connection11(get_rabbitmq_host()) conn2.set_listener("testlistener", HeaderModListener("123", print_to_log=True)) conn2.connect(get_rabbitmq_user(), get_rabbitmq_password(), wait=True) yield conn2 conn2.disconnect(receipt=None)
def testbasic(self): conn = stomp.Connection11(get_rabbitmq_host()) listener = TestListener('123', print_to_log=True) listener2 = WaitingListener('456') conn.set_listener('123', listener) conn.set_listener('456', listener2) conn.connect(get_rabbitmq_user(), get_rabbitmq_password(), wait=True) conn.subscribe(destination='/queue/test', id=1, ack='auto') conn.send(body='this is a test', destination='/queue/test', receipt='123') listener.wait_on_receipt() conn.disconnect(receipt='456') listener2.wait_on_receipt() self.assertTrue(listener.connections == 1, 'should have received 1 connection acknowledgement') self.assertTrue(listener.messages == 1, 'should have received 1 message') self.assertTrue(listener.errors == 0, 'should not have received any errors') self.assertTrue( listener.disconnects == 1, 'should have received 1 disconnect, was %s' % listener.disconnects)
def conn(): conn = stomp.Connection11(get_rabbitmq_host()) listener = TestListener("123", print_to_log=True) listener2 = WaitingListener("456") conn.set_listener("123", listener) conn.set_listener("456", listener2) conn.connect(get_rabbitmq_user(), get_rabbitmq_password(), wait=True) yield conn
def setUp(self): conn = stomp.Connection11(get_ipv6_host()) listener = TestListener('123') conn.set_listener('', listener) conn.connect('admin', 'password', wait=True) self.conn = conn self.listener = listener self.timestamp = time.strftime('%Y%m%d%H%M%S')
def conn(): if not is_inside_travis(): conn = stomp.Connection11(get_ipv6_host()) conn.set_listener("testlistener", TestListener("123", print_to_log=True)) conn.connect("admin", "password", wait=True) yield conn conn.disconnect(receipt=None) else: yield None
def testbasic(self): conn = stomp.Connection11(get_apollo_host()) listener = WaitingListener('123') conn.set_listener('', listener) conn.connect(get_default_user(), get_default_password(), wait=True) conn.subscribe(destination='/queue/test', id=1, ack='auto') conn.send(body='this is a test', destination='/queue/test', receipt='123') listener.wait_on_receipt() conn.disconnect(receipt=None)
def testbasic(self): conn = stomp.Connection11(get_rabbitmq_host(), 'guest', 'guest') listener = TestListener('123') conn.set_listener('', listener) conn.start() conn.connect(wait=True) conn.subscribe(destination='/queue/test', id=1, ack='auto') conn.send(body='this is a test', destination='/queue/test', receipt='123') listener.wait_on_receipt() conn.disconnect(receipt=None) self.assert_(listener.connections == 1, 'should have received 1 connection acknowledgement') self.assert_(listener.messages == 1, 'should have received 1 message') self.assert_(listener.errors == 0, 'should not have received any errors')
def send_message(host='localhost', port=61613, user='', password='', ver='1.1', use_ssl=False, body='', subscription_type='topic', subscription_name=''): # before connecting, validate that the message is valid try: json_body = json.loads(body) except: print("Invalid body provided, needs to be a JSON file") sys.exit(1) result, error_message = validate_json_message(json_body) if not result: print("Validation error: %s" % error_message) sys.exit(1) try: # establish the right stomp connection if ver == '1.0': conn = stomp.Connection10([(host, port)]) elif ver == '1.1': conn = stomp.Connection11([(host, port)]) elif ver == '1.2': conn = stomp.Connection12([(host, port)]) elif ver == 'multicast': conn = MulticastConnection() if use_ssl: conn.set_ssl([(host, port)]) conn.set_listener('', OpenCIListener(conn, user, password)) conn.start() # connect and send message conn.connect(user, password, wait=True) txid = conn.begin() conn.send(destination='/%s/%s' % (subscription_type, subscription_name), body=body, headers={'JMSType': json_body['type'], 'JMSOrigin': json_body['origin'], 'JMSScenario': json_body['scenario'],}, transaction=txid) conn.commit(txid) conn.disconnect() except Exception as e: print("Error connecting to broker: %s" % str(e)) sys.exit(1) print("finish")
def get_stomp_connection(self): """ Start a connection to the message bus. """ fm_conf = fedmsg.config.load_config() for opt in ['stomp_uri', 'stomp_ssl_crt', 'stomp_ssl_key']: if opt not in fm_conf: raise RuntimeError('missing config: {0}'.format(opt)) uris = self._to_host_and_port(fm_conf['stomp_uri']) connection_kwargs = { 'use_ssl': True, 'ssl_cert_file': fm_conf['stomp_ssl_crt'], 'ssl_key_file': fm_conf['stomp_ssl_key'], 'ssl_ca_certs': '/etc/pki/tls/certs/ca-bundle.crt', 'ssl_version': ssl.PROTOCOL_TLSv1_2, 'timeout': 10.0 } if self.using_legacy_stomppy: conn = stomp.Connection(uris, wait_on_receipt=True, version='1.1', **connection_kwargs) else: # In stomp.py v4, the `version` is determined by the "Connection" class used. # The `Connection` class is also an alias for `Connection11`, but let's use # `Connection11` directly to avoid issues in the future. Also, `wait_on_receipt` is not # supported. See: https://github.com/jasonrbriggs/stomp.py/issues/224 conn = stomp.Connection11(uris, **connection_kwargs) conn.start() self.log.debug('Connecting to %s...', uris) conn.connect(wait=True) if self.using_legacy_stomppy: host_and_port = conn.get_host_and_port() else: host_and_port = '{}:{}'.format( *conn.transport.current_host_and_port) self.log.debug('Connected to %s', host_and_port) return conn
def testconnect(self): conn = stomp.Connection11(get_sni_ssl_host()) conn.set_ssl(get_sni_ssl_host()) listener = TestListener('123') conn.set_listener('', listener) conn.connect(get_default_user(), get_default_password(), wait=True) conn.subscribe(destination='/queue/test', id=1, ack='auto') conn.send(body='this is a test', destination='/queue/test', receipt='123') listener.wait_on_receipt() conn.disconnect(receipt=None) self.assertTrue(listener.connections == 1, 'should have received 1 connection acknowledgement') self.assertTrue(listener.messages == 1, 'should have received 1 message') self.assertTrue(listener.errors == 0, 'should not have received any errors')
def testconnect(self): conn = stomp.Connection11(get_sni_ssl_host()) conn.set_ssl(get_sni_ssl_host()) listener = TestListener(self.receipt_id, print_to_log=True) conn.set_listener('', listener) conn.connect(get_default_user(), get_default_password(), wait=True) conn.subscribe(destination='/queue/test', id=1, ack='auto') print('.....sending message with receipt %s' % self.receipt_id) conn.send(body='this is a test', destination='/queue/test', receipt=self.receipt_id) listener.wait_for_message() conn.disconnect(receipt=None) self.assertTrue(listener.connections == 1, 'should have received 1 connection acknowledgement') self.assertTrue(listener.messages >= 1, 'should have received 1 message') self.assertTrue(listener.errors == 0, 'should not have received any errors')
def init_app( self, app ): """Init the Flask-Stomp addon. :param Flask app: """ if not app.config.get( "STOMPMQ_ENABLED", False ): return self.__app = app self.__username = app.config.get( "STOMPMQ_USERNAME", "" ) self.__password = app.config.get( "STOMPMQ_PASSWORD", "" ) version = app.config.get( "STOMPMQ_VERSION", "1.1" ) broker_hosts = app.config.get( "STOMPMQ_BROKER_HOSTS", [] ) if len( broker_hosts ) == 0: broker_hosts.append( [ app.config.get( "STOMPMQ_BROKER_URL", "localhost" ), app.config.get( "STOMPMQ_BROKER_PORT", 61613 ) ] ) global logger #logger = app.logger logger.info( 'MQ username : %s' % ( self.__username ) ) logger.info( 'MQ password : %s' % ( self.__password ) ) logger.info( 'MQ version : %s' % ( version ) ) logger.info( 'MQ broker_hosts : %s' % ( repr( broker_hosts ) ) ) if version == '1.0': self.__broker = stomp.Connection10( broker_hosts ) elif version == '1.1': self.__broker = stomp.Connection11( broker_hosts ) elif version == '1.2': self.__broker = stomp.Connection12( broker_hosts ) else: raise Exception( "Invalid STOMPMQ_VERSION only '1.0', '1.1' or '1.2' are allowed" ) # self.__listener = FlaskStompListener( self.__broker, app ) self.__broker.set_listener( 'flask_app', self.__listener ) self._connect() return
def testconnect(self): if not is_inside_travis(): logging.info("Running ipv6 test") receipt_id = str(uuid.uuid4()) conn = stomp.Connection11(get_sni_ssl_host()) conn.set_ssl(get_sni_ssl_host()) listener = TestListener(receipt_id, print_to_log=True) conn.set_listener('', listener) conn.connect(get_default_user(), get_default_password(), wait=True) conn.subscribe(destination="/queue/test", id=1, ack="auto") logging.info("sending message with receipt %s" % receipt_id) conn.send(body="this is a test", destination="/queue/test", receipt=receipt_id) listener.wait_for_message() conn.disconnect(receipt=None) assert listener.connections == 1, "should have received 1 connection acknowledgement" assert listener.messages >= 1, "should have received 1 message" assert listener.errors == 0, "should not have received any errors"
def connect(self, listener=None, subscribe=True): """ """ # TODO: # Put a timer on connection # Do I really need to duplicate this check that I do in __init__ ? # Seems like I just need to choose one or the other, but I'm leaving # this here since I think I have some codes that need this check. if listener is None: listener = ParrotSubscriber() try: print("Connecting to %s" % (self.host)) if self.protocol is None: self.protocol = 'stompLatest' if self.protocol.lower() == 'stomp10': self.conn = stomp.Connection10([(self.host, self.port)], auto_decode=False) elif self.protocol.lower() == 'stomp11': self.conn = stomp.Connection11([(self.host, self.port)], auto_decode=False, heartbeats=(10000, 10000), heart_beat_receive_scale=3.0) else: self.conn = stomp.Connection([(self.host, self.port)], auto_decode=False, heartbeats=(10000, 10000), heart_beat_receive_scale=3.0) # Note that self.conn is now type stomp.connect.StompConnectionXX # where XX is either 10, 11, or 12 indicating STOMP version if listener is not None: # NOTE: listener must be a valid ConnectionListener type!! self.conn.set_listener('LIGmosSpy', listener) else: print("WARNING! No listener defined! Nothing will occur!") # For STOMP.py versions >= 4.1.20, .start() does nothing and # actually won't even exist so it'll throw AttributeError. # That's totally cool so just ignore it. # Old brokers might fall back to StompConnection10, which requires # the start() method to actually be used before connect(). # The ancient broker for Solaris running for NASA42 is an # example of this so I need this here still. try: self.conn.start() print("STOMP.py conn.start() worked! Prob. an old broker.") except AttributeError as e: pass self.conn.connect() print("Connection established. Hooray!") if subscribe is True: if self.topics is not None: print("Subscribing to:") print(self.topics) self.subscribe(topic=self.topics) except stomp.exception.NotConnectedException as err: self.conn = None print("STOMP.py not connected!") except stomp.exception.ConnectFailedException as err: self.conn = None print("STOMP.py connection failed!") except stomp.exception.StompException as err: self.conn = None print("STOMP.py exception!") print(str(type(err)))
def test_with_context_stomp11(self): with stomp.Connection11(get_default_host()) as conn: self.send_test_message(conn) self.check_asserts() self.post_test_message(conn)
# This was an attempt to test a monitoring queue subscriber. # The additional parameter 'browser-end' that would keep the # listener active after receiving queue messages does not # work. The reason for this is unknown, although likely to do # with the activemq version used. # Try creating two instances using the following code, and you # will find they both retrieve all the queue messages, without # consuming them. import stomp from pprint import pprint queue = "/queue/myqueue" conn = stomp.Connection11(auto_content_length=False) class BrowsingListener(stomp.ConnectionListener): def on_error(self, headers, message): print('received an error "%s"' % message) def on_message(self, headers, message): # When receiving a browser:end message, the following # line will fail, as message = '' # data = json.loads(message) print("Got message.") pprint(message) pprint(headers) conn.set_listener('', BrowsingListener()) conn.start()
import stomp import time import os from subscriber import MySubscriber host = os.getenv('ACTIVEMQ_HOST', 'localhost') port = os.getenv('ACTIVEMQ_PORT', 61613) user = os.getenv('ACTIVEMQ_USER', 'admin') password = os.getenv('ACTIVEMQ_PASSWORD', 'password') print('host port user password', host, port, user, password) conn = stomp.Connection11([(host, int(port))]) conn.set_listener('', MySubscriber()) conn.start() conn.connect(user, password, wait=True) conn.subscribe(destination='My.Fancy.Queue', id=time.time_ns(), ack='auto') while True: time.sleep(5) conn.disconnect()
def conn(): conn = stomp.Connection11(get_default_host()) conn.set_listener("testlistener", TestListener("123", print_to_log=True)) conn.connect(get_default_user(), get_default_password(), wait=True) yield conn conn.disconnect(receipt=None)