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): # super(pathwayProcessor,self).__init__(self.consume) config = PropertyUtil(r"config.ini") # config[pathwayProcessor.CONFIG] = StompConfig(uri="failover:("+config.getAsString(pathwayProcessor.URL)+")?startupMaxReconnectAttempts=-1,initialReconnectDelay=300000") self.QUEUE=config.getAsString(pathwayProcessor.NAME) self.ERROR_QUEUE=config.getAsString('queue.error.name') # config[pathwayProcessor.CONFIG] = StompConfig(config.getAsString(pathwayProcessor.URL)) config = StompConfig(config.getAsString(pathwayProcessor.URL)) self.config = config robjects.r('''source('ARTPWrapper.R')''') self.r_runARTP = robjects.r['runARTPWithHandlers']
def test_disconnect_on_stomp_protocol_error(self): port = self.connections[0].getHost().port config = StompConfig(uri='tcp://localhost:%d' % port) client = Stomp(config) yield client.connect() client.send('/queue/fake', 'fake message') try: yield client.disconnected except StompProtocolError: pass else: raise
def __init__(self, namespace, login, passcode, broker_host=DEFAULT_BROKER_HOST, device_uid=None, channel_type='topic'): ''' Create a ByteportStompClient. This is a thin wrapper to the underlying STOMP-client that connets to the Byteport Broker If a device_uid is given, a subscription will be made for Messages sent through Byteport. The channel_type must be either 'topic' or 'queue'. Set top topic if unsure on what to use (use queue if you need to use multiple consumers for a single device, this is not how most applications are set up). :param namespace: :param login: Broker username (Byteport web users are _not_ valid broker users). Ask [email protected] for access. :param passcode: Broker passcode :param broker_hosts: [optional] A list of brokers to connect to :param device_uid: [optional] The device UID to subscribe for messages on :param channel_type: [optional] Defaults to queue. :param channel_key: [optional] Must match the configured key in the Byteport Device Manager ''' self.namespace = str(namespace) self.device_uid = device_uid if channel_type not in self.SUPPORTED_CHANNEL_TYPES: raise Exception("Unsupported channel type: %s" % channel_type) broker_url = 'tcp://%s:61613' % broker_host self.CONFIG = StompConfig(broker_url, version=StompSpec.VERSION_1_2) self.client = Stomp(self.CONFIG) try: self.client.connect(headers={'login': login, 'passcode': passcode}, host='/') logging.info("Connected to Stomp broker at %s using protocol version %s" % (broker_host, self.client.session.version)) # Set up a subscription on the correct queue if a Specific device UID was given if self.device_uid: subscribe_headers = dict() subscribe_headers[StompSpec.ACK_HEADER] = StompSpec.ACK_CLIENT_INDIVIDUAL subscribe_headers[StompSpec.ID_HEADER] = '0' device_message_queue_name = '/%s/device_messages_%s.%s' % (channel_type, namespace, device_uid) self.subscription_token = self.client.subscribe(device_message_queue_name, subscribe_headers) logging.info("Subscribing to channel %s" % device_message_queue_name) except StompProtocolError as e: logging.error("Client socket connected, but probably failed to login. (ProtocolError)") raise except StompConnectionError: logging.error("Failed to connect to Stomp Broker at %s" % broker_host) raise
def test_disconnect_on_stomp_protocol_error(self): port = self.connections[0].getHost().port config = StompConfig(uri='tcp://localhost:%d' % port) client = Stomp(config) yield client.connect() client.send('/queue/fake', b'fake message') try: yield client.disconnected except StompProtocolError as e: self.assertTrue(isinstance(e.frame, StompFrame)) else: raise Exception( 'Expected a StompProtocolError, but nothing was raised.')
def test_connected_timeout_after_failover(self): port = self.connections[0].getHost().port config = StompConfig( uri= 'failover:(tcp://nosuchhost:65535,tcp://localhost:%d)?startupMaxReconnectAttempts=2,initialReconnectDelay=0,randomize=false' % port) client = Stomp(config) try: yield client.connect(connectedTimeout=self.TIMEOUT) except StompCancelledError: pass else: raise Exception( 'Expected connected timeout, but connection was established.')
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 _get_config(): # Hosts hosts = STOMP.get('hosts', None) if not hosts: host = STOMP.get('host', None) if not host: host = ('localhost', 61613) if host: hosts = (host, ) hostname = hosts[0] if isinstance(hostname, tuple): hostname = hostname[0] else: hostname = hostname.split(':')[0] # Uris uris = [] for host in hosts: if isinstance(host, tuple): host = "%s:%d" % host uri = "tcp://%s" % host uris.append(uri) if len(hosts) > 1: # @todo Give config better control over fallover settings final_uri = "fallover:(%s)" % ','.join(uris) else: final_uri = uris[0] # User, passcode user = STOMP.get('user', None), if user == '': user = None passcode = STOMP.get('pass', None), if passcode == '': passcode = None CONFIG = StompConfig( uri=final_uri, login=user, passcode=passcode, # Support the latest version of the spec that existed when we wrote this # (and due to stompest's accepts-version header every version before that) version=StompSpec.VERSION_1_2) EXTRA = { 'hostname': hostname, } return CONFIG, EXTRA
class ConsumerAMQ(object): ''' classdocs ''' CONFIG = StompConfig('tcp://localhost:61613') QUEUE = '/queue/revideomessagesFE' FRAMEBODY = "MESSAGE" def __init__(self, sel, config=None, queue=None): ''' Constructor ''' if config is not None: self.CONFIG = config if queue is not None: self.QUEUE = queue self.selector = sel self.client = Stomp(self.CONFIG) self.client.connect() self.client.subscribe( self.QUEUE, { StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL, "selector": self.selector }) def receive(self): frame = None cnt = 5 while True: frame = self.client.receiveFrame() #print "frame: " + frame.info() if frame.command == self.FRAMEBODY: self.client.ack(frame) break frame = None cnt = cnt - 1 if cnt <= 0: break if frame is None: return frame else: return frame.body def end(self): self.client.disconnect()
def getConfig(self, version, port=PORT_SSL): sslContext = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) # It's good practice to disable insecure protocols by default sslContext.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_SSLv3 # Disable host name and cert checking for the tests. sslContext.check_hostname = False sslContext.verify_mode = ssl.CERT_NONE return StompConfig( 'ssl://%s:%s' % (HOST, port), login=LOGIN, passcode=PASSCODE, version=version, sslContext=sslContext )
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 run(self): config = StompConfig('tcp://%s:%d' % (host, port), login=user, passcode=password, version='1.1') client = Stomp(config) yield client.connect(host='mybroker') self.count = 0 self.start = time.time() client.subscribe(destination, listener=SubscriptionListener(self.handleFrame), headers={ 'ack': 'auto', 'id': 'required-for-STOMP-1.1' })
def _sender(queue_req, msg, session_id, msg_id): stomp_config = config.mq_config.get('stomp') client = Stomp(StompConfig(stomp_config)) client.connect() #H = {StompSpec.CONTENT_LENGTH_HEADER: len(msg), "length": len(msg)} H = {} H['MsgID'] = msg_id H['SessionID'] = session_id H['Signature'] = sign(msg) if isinstance(msg, dict): msg = json.dumps(msg) print '===> [%s] session_ids: %s, body: %s' % (queue_req, session_id, msg) client.send(queue_req, body=msg, headers=H, receipt="ok") client.disconnect()
def run(): config = StompConfig('tcp://%s:%d' % (host, port), login=user, passcode=password, version='1.1') client = Stomp(config) yield client.connect(host='mybroker') count = 0 start = time.time() for _ in xrange(messages): client.send(destination=destination, body=data, headers={'persistent': 'false'}) count += 1 diff = time.time() - start print 'Sent %s frames in %f seconds' % (count, diff) yield client.disconnect(receipt='bye')
def connect_to_amq(tb, queue=False, topic=False): # Format the connection url dl_ff_ip, dl_north_rest = tb.dl_northside_rest.split(":") dl_activemq_stomp_port = 61613 url = "tcp://{}:{}".format(dl_ff_ip, dl_activemq_stomp_port) # Create stomp config config = StompConfig(url) stomp = Stomp(config) # Connect to activemq stomp.connect() if queue: stomp.subscribe(queue, {StompSpec.ID_HEADER: u'testbench'}) elif topic: stomp.subscribe('/topic/' + str(topic), {StompSpec.ID_HEADER: u'testbench'}) # return the stomp return stomp
def test_replay_after_failover(self): ports = tuple(c.getHost().port for c in self.connections) config = StompConfig( uri= 'failover:(tcp://localhost:%d)?startupMaxReconnectAttempts=0,initialReconnectDelay=0,maxReconnectAttempts=1' % ports) client = Stomp(config) queue = '/queue/bla' try: client.subscribe( queue, listener=SubscriptionListener(self._on_message) ) # client is not connected, so it won't accept subscriptions except StompConnectionError: pass else: raise Exception('Unexpected successful subscribe.') self.assertEquals(client.session._subscriptions, {}) # check that no subscriptions have been accepted yield client.connect() self.shutdown = True # the callback handler will kill the broker connection ... client.subscribe(queue, listener=SubscriptionListener(self._on_message)) try: yield client.disconnected # the callback handler has killed the broker connection except StompConnectionError: pass else: raise Exception('Unexpected clean disconnect.') self.shutdown = False # the callback handler will not kill the broker connection, but callback self._got_message self._got_message = defer.Deferred() yield client.connect() self.assertNotEquals(client.session._subscriptions, []) # the subscriptions have been replayed ... result = yield self._got_message self.assertEquals(result, None) # ... and the message comes back yield client.disconnect() yield client.disconnected self.assertEquals( list(client.session.replay()), []) # after a clean disconnect, the subscriptions are forgotten.
def sendqueue(tokenId): #try: timestr = time.strftime("%Y-%m-%d") QUEUE = jpsurvConfig.getAsString(QUEUE_NAME) QUEUE_CONFIG = StompConfig(jpsurvConfig.getAsString(QUEUE_URL)) client = Stomp(QUEUE_CONFIG) client.connect() client.send( QUEUE, json.dumps({ "filepath": UPLOAD_DIR, "token": tokenId, "timestamp": timestr })) client.disconnect() return
def change_order_status(id): conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT status FROM orders where order_id = " + str(id) + "") rows = cursor.fetchall() status = rows[0][0] next_status = None if status == 'Ordered': next_status = 'ReadyToShip' queue = '/queue/readytoship' elif status == 'ReadyToShip': next_status = 'Shipped' queue = '/queue/shipped' elif status == 'Shipped': next_status = 'Delivered' if status == 'Delivered': return True if next_status == 'ReadyToShip' or next_status == 'Shipped': amq_conf = None #if isOpen('activemq.default', 61612): 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(id).encode()) client.disconnect() except: print("something went wrong") sql = "Update systeam_ecommerce.orders SET status = '" + next_status + "' where order_id = " + str( id) + "" rows = cursor.execute(sql) sql = "Delete from systeam_ecommerce.next_order where status = '" + status + "'" rows = cursor.execute(sql) conn.commit() conn.close() return True
def __init__(self, conf): self.conf = conf if self.conf['protocol'] == '11': protocol_v = StompSpec.VERSION_1_1 elif self.conf['protocol'] == '12': protocol_v = StompSpec.VERSION_1_2 else: protocol_v = StompSpec.VERSION_1_0 client_config = StompConfig( 'tcp://{}:{}'.format(self.conf['host'], self.conf['port']), login=self.conf['username'], passcode=self.conf['password'], version=protocol_v ) self.conn = Stomp(client_config) self.conn.connect() return super().__init__()
def test_multi_subscriptions(self): port = self.connections[0].getHost().port config = StompConfig(uri='tcp://localhost:%d' % port) client = Stomp(config) yield client.connect() listeners = [] for j in range(2): listener = SubscriptionListener(self._on_message) yield client.subscribe('/queue/%d' % j, headers={'bla': j}, listener=listener) listeners.append(listener) for (j, listener) in enumerate(listeners): self.assertEquals(listener._headers['bla'], j) yield client.disconnect() yield client.disconnected
def CreateConnection(): try: Write2File(threading.currentThread().getName(), "INFO", "Connecting to ActiveMQ Server.") client = Stomp( StompConfig("tcp://" + server + ":" + port, login=login, passcode=passcode, version="1.2")) client.connect(versions=["1.2"], host=vhost, heartBeats=(0, 60000)) #CONNECT subscription = client.subscribe(destination, { "ack": "client", "id": "0", "headers": { "activemq.prefetchSize": 1 } }) #SUBSCRIB Write2File(threading.currentThread().getName(), "INFO", "Connection to ActiveMQ Server successfully established.") except: Write2File(threading.currentThread().getName(), "ERROR", str(sys.exc_info())) raise try: while (client.canRead(5)): Write2File(threading.currentThread().getName(), "DEBUG", "Setting LOCK.") container.acquire() ReceiveFrame(client) else: Write2File(threading.currentThread().getName(), "INFO", "Closing connection with ActiveMQ Server.") client.disconnect() if (container.acquire(blocking=False)): Write2File(threading.currentThread().getName(), "DEBUG", "Removing LOCK.") container.release() except: Write2File(threading.currentThread().getName(), "ERROR", str(sys.exc_info())) exit(1)
def sendqueue(inputFileId, emailAddress, fileName, url, socSystem): #try: import time now = time.strftime("%a %b %X %Z %Y") QUEUE = soccerConfig.getAsString(QUEUE_NAME) QUEUE_CONFIG = StompConfig(soccerConfig.getAsString(QUEUE_URL)) filePath = os.path.join(RESULTS_PATH, inputFileId) client = Stomp(QUEUE_CONFIG) client.connect() client.send( QUEUE, json.dumps({ "inputFileId": inputFileId, "emailAddress": emailAddress, "fileName": fileName, "timestamp": now, "url": url, "socSystem": socSystem })) client.disconnect()
def __init__(self, host, port, version, headers={}): """ Creates an instance of the StompMQAdapter class. Args: host (str): Hostname or IP address for locating the MQ system. port (int): The port to connect to. stomp_version (str): The Stomp protocol version ot be used. headers (dict, optional): Defaults to {}. The headers to be used in the connection. """ self.client = Stomp( StompConfig('tcp://{}:{}'.format(host, port), version=version)) # Assign mandatory ID_HEADER if version above 1.1 if float(version) > 1.1: self.headers[StompSpec.ID_HEADER] = id(self.client) # Add all given headers to object headers for key in headers.keys(): self.headers[key] = headers[key]
def __init__(self, data, conf): logging.debug("json data: %s [%s]" % (str(data), type(data))) if not type(data) == dict: raise ValueError, "PostProcessAdmin expects a data dictionary" data["information"] = socket.gethostname() self.data = data self.conf = conf # List of error messages to be handled as information self.exceptions = self.conf.exceptions stompConfig = StompConfig(self.conf.failover_uri, self.conf.amq_user, self.conf.amq_pwd) self.client = Stomp(stompConfig) self.data_file = None self.facility = None self.instrument = None self.proposal = None self.run_number = None
def test_disconnect_timeout(self): port = self.connections[0].getHost().port config = StompConfig(uri='tcp://localhost:%d' % port, version='1.1') client = Stomp(config) yield client.connect() self._got_message = defer.Deferred() client.subscribe('/queue/bla', headers={StompSpec.ID_HEADER: 4711}, listener=SubscriptionListener( self._on_message, ack=False)) # we're acking the frames ourselves yield self._got_message yield client.disconnect(timeout=0.02) try: yield client.disconnected except StompCancelledError: pass else: raise self.wait.callback(None)
def _active_queue_configure(self, host, port, user_name, password): """ TO connect to Active MQ """ host = str(host) port = str(port) user_name = str(user_name) password = str(password) if not user_name: raise AssertionError( "user_Name argument is required.!! Please check and pass user_Name value" ) if not password: raise AssertionError( "password argument is required.!! Please check and pass password value" ) ActiveMQ_url = "tcp://{}:{}".format(host, port) ActiveMQ_Client = None config = StompConfig(ActiveMQ_url, login=user_name, passcode=password) ActiveMQ_Client = Stomp(config) ActiveMQ_Client.connect() return ActiveMQ_Client
def _sender(queue_req, msg, session_id, msg_id, selector=None): stomp_config = config.mq.get('stomp') client = Stomp(StompConfig(stomp_config)) client.connect() #H = {StompSpec.CONTENT_LENGTH_HEADER: len(msg), "length": len(msg)} H = {} H['MsgID'] = msg_id H['SessionID'] = session_id H['Signature'] = sign(msg) if selector is not None: H[selector[0]] = selector[1] print 'send msg: ' print json.dumps(msg, indent=1) if isinstance(msg, dict): msg = json.dumps(msg) logger.info('===>[%s] session_ids: %s, body: %s' % (queue_req, session_id, msg)) client.send(queue_req, body=msg, headers=H, receipt="ok") client.disconnect()
def test_failover_on_connection_lost(self): ports = tuple(c.getHost().port for c in self.connections) config = StompConfig( uri= 'failover:(tcp://localhost:%d,tcp://localhost:%d)?startupMaxReconnectAttempts=0,initialReconnectDelay=0,randomize=false,maxReconnectAttempts=1' % ports) client = Stomp(config) yield client.connect() self.connections[0].stopListening() queue = '/queue/fake' client.send(queue, 'shutdown') try: client = yield client.disconnected except StompConnectionError: yield client.connect() client.send(queue, 'fake message') try: yield client.disconnected except StompProtocolError: pass
def test_stomp_version_1_1(self): destination = '/queue/foo' stomp = self._get_transport_mock( config=StompConfig('tcp://%s:%s' % (HOST, PORT), version=StompSpec.VERSION_1_1, check=False)) stomp._transport = Mock() frame = StompFrame( StompSpec.MESSAGE, { StompSpec.MESSAGE_ID_HEADER: '4711', StompSpec.DESTINATION_HEADER: destination }) self.assertRaises(StompProtocolError, stomp.nack, frame) frame = StompFrame(StompSpec.MESSAGE, { StompSpec.MESSAGE_ID_HEADER: '4711', StompSpec.DESTINATION_HEADER: destination, StompSpec.SUBSCRIPTION_HEADER: '0815' }, version=StompSpec.VERSION_1_1) stomp.nack(frame, receipt='123') args, _ = stomp._transport.send.call_args sentFrame = args[0] self.assertEquals(commands.nack(frame, receipt='123'), sentFrame)
from stompest.config import StompConfig from stompest.protocol import StompSpec from stompest.sync import Stomp CONFIG = StompConfig('tcp://localhost:61613', version=StompSpec.VERSION_1_1) QUEUE = '/queue/test' if __name__ == '__main__': client = Stomp(CONFIG) client.connect(heartBeats=(0, 10000)) client.subscribe(QUEUE, {StompSpec.ID_HEADER: 1, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}) client.send(QUEUE, 'test message 1') client.send(QUEUE, 'test message 2') while True: frame = client.receiveFrame() print 'Got %s' % frame.info() client.ack(frame) client.disconnect()