<NME> __main__.py
<BEF> """
Stomp.py command-line client

Usage: stomp [options]

Options:
  --version                    Show the version number and exit
  -h, --help                   Show this help message and exit
  -H <host>, --host=<host>     Hostname or IP address to connect to. [default: localhost]
  -P <port>, --port=<port>     Port providing stomp protocol connections. [default: 61613]
  -U <user>, --user=<user>     Username for the connection
  -W <password>, --password=<password>
                               Password for the connection
  -F <filename>, --file=<filename>
                               File containing commands to be executed, instead of
                               prompting from the command prompt.
  -S <protocol version>, --protocol=<protocol version>
                               Set the STOMP protocol version (1.0, 1.1, 1.2) [default: 1.1]
  -L <queue>, --listen=<queue> Listen for messages on a queue/destination
  -V, --verbose                Verbose logging "on" or "off" (if on, full headers
                               from stomp server responses are printed)
  --heartbeats=<heartbeats>    Heartbeats to request when connecting with protocol >=
                               1.1 (two comma separated integers required) [default: 0,0]
  --ssl                        Enable SSL connection
  --ssl-key-file=<key-file>    ssl key file
  --ssl-cert-file=<cert-file>  ssl cert file
  --ssl-ca-file=<ca-file>      ssl ca certs file

"""

import base64
import json
import os
import re
import sys
import time
from cmd import Cmd
from functools import partial

from docopt import docopt

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import stomp.colours
    A command line interface to the stomp.py client.  See :py:class:`stomp.connect.StompConnection11`
    for more information on establishing a connection to a stomp server.
    """
    def __init__(self, host='localhost', port=61613, user='', passcode='', ver='1.1', prompt='> ', verbose=True, use_ssl=False, stdin=sys.stdin, stdout=sys.stdout):
        Cmd.__init__(self, 'Tab', stdin, stdout)
        ConnectionListener.__init__(self)
        self.prompt = prompt

version_string = "%s.%s.%s" % stomp.__version__

heartbeat_pattern = re.compile(r"[0-9]+,[0-9]+")
        if ver == '1.0':
            self.conn = StompConnection10([(host, port)], wait_on_receipt=True)
        elif ver == '1.1':
            self.conn = StompConnection11([(host, port)], wait_on_receipt=True)
        elif ver == '1.2':
            self.conn = StompConnection12([(host, port)], wait_on_receipt=True)
        elif ver == 'multicast':
            self.conn = MulticastConnection()
        else:


class StompCLI(Cmd, ConnectionListener):
    """
    A command line interface to the stomp.py client.  See :py:class:`stomp.connect.StompConnection11`
    for more information on establishing a connection to a stomp server.
    """
    def __init__(self, host="localhost", port=61613, user="", passcode="", ver="1.1", prompt="> ", verbose=True,
                 heartbeats=(0, 0), use_ssl=False, ssl_key_file=None, ssl_cert_file=None, ssl_ca_file=None,
                 stdin=sys.stdin, stdout=sys.stdout):
        Cmd.__init__(self, "Tab", stdin, stdout)
        ConnectionListener.__init__(self)
        self.__start = True
        self.prompt = prompt
        self.verbose = verbose
        self.user = user
        self.passcode = passcode
        self.__quit = False
        if ver == "1.0":
            self.conn = StompConnection10([(host, port)])
        elif ver == "1.1":
            self.conn = StompConnection11([(host, port)], heartbeats=heartbeats)
        elif ver == "1.2":
            self.conn = StompConnection12([(host, port)], heartbeats=heartbeats)
        elif ver == "multicast":
            self.conn = MulticastConnection()
        else:
            raise RuntimeError("Unknown version")
        if use_ssl:
            self.conn.set_ssl([(host, port)], key_file=ssl_key_file, cert_file=ssl_cert_file, ca_certs=ssl_ca_file)
        self.conn.set_listener("", self)
        self.conn.connect(self.user, self.passcode, wait=True)
        self.transaction_id = None
        self.version = ver
        try:
            self.nversion = float(ver)
        except ValueError:
            self.nversion = 1.0
        self.__subscriptions = {}
        self.__subscription_id = 1

    def __print_async(self, frame_type, frame):
        """
        Utility function to print a message and setup the command prompt
        for the next input
        """
        if self.__quit:
            return
        if self.verbose:
            self.__sysout(frame_type)
            for k, v in frame.headers.items():
                self.__sysout("%s: %s" % (k, v))
        else:
            if "message-id" in frame.headers:
                self.__sysout("message-id: %s" % frame.headers["message-id"])
            if "subscription" in frame.headers:
                self.__sysout("subscription: %s" % frame.headers["subscription"])
        if self.prompt != "":
            self.__sysout("")
        self.__sysout(frame.body)
        if not self.__start:
            self.__sysout(self.prompt, end="")
        else:
            self.__start = False
        self.stdout.flush()

    def __sysout(self, msg, end="\n"):
        if self.__quit:
            return
        self.stdout.write(str(msg) + end)

    def __error(self, msg, end="\n"):
        self.stdout.write(stomp.colours.BOLD + stomp.colours.RED + str(msg) + stomp.colours.NO_COLOUR + end)

    def on_connecting(self, host_and_port):
        """
        See :py:meth:`ConnectionListener.on_connecting`
        """
        pass

    def on_disconnected(self):
        """
        see :py:meth:`ConnectionListener.on_disconnected`
        """
        if not self.__quit:
            self.__error("lost connection")

    def on_message(self, frame):
        """
        See :py:meth:`ConnectionListener.on_message`

        Special case: if the header 'filename' is present, the content is written out
        as a file
        """
        self.__sysout("")
        if "filename" in frame.headers:
            content = base64.b64decode(frame.body.encode())
            if os.path.exists(frame.headers["filename"]):
                fname = "%s.%s" % (frame.headers["filename"], int(time.time()))
            else:
                fname = frame.headers["filename"]
            with open(fname, "wb") as f:
                f.write(content)
            frame.body = "Saved file: %s" % fname
        self.__print_async("MESSAGE", frame)

    def on_error(self, frame):
        """
        See :py:meth:`ConnectionListener.on_error`
        """
        self.__print_async("ERROR", frame)

    def on_receipt(self, frame):
        """
        See :py:meth:`ConnectionListener.on_receipt`
        """
        self.__print_async("RECEIPT", frame)

    def on_connected(self, frame):
        """
        See :py:meth:`ConnectionListener.on_connected`
        """
        self.__print_async("CONNECTED", frame)

    def on_send(self, frame):
        if self.verbose:
            self.__sysout("Sending %s" % str(frame))

    def help_help(self):
        self.__sysout("Quick help on commands")

    def default(self, line):
        self.__error("Unknown command: %s" % line.split()[0])

    def emptyline(self):
        pass

    def help(self, usage, description, required=(), optional=()):
        rparams = "\n\t" + "\n\t".join(required)
        oparams = "\n\t" + "\n\t".join(optional)

        m = {
            "hl": stomp.colours.BOLD + stomp.colours.GREEN,
            "nc": stomp.colours.NO_COLOUR,
            "usage": usage,
            "description": description,
            "required": rparams.rstrip(),
            "optional": oparams.rstrip()
        }

        if rparams.rstrip() != "":
            rparams = '''%(hl)sRequired Parameters:%(nc)s%(required)s\n\n''' % m
            m["required"] = rparams

        if oparams.rstrip() != "":
            oparams = '''%(hl)sOptional Parameters:%(nc)s%(optional)s\n\n''' % m
            m["optional"] = oparams

        self.__sysout('''%(hl)sUsage:%(nc)s
\t%(usage)s

%(required)s%(optional)s%(hl)sDescription:%(nc)s
\t%(description)s
        ''' % m)

    def do_quit(self, args):
        self.__quit = True
        self.__sysout("Shutting down, please wait")
        return True
    do_exit = do_quit
    do_EOF = do_quit

    def help_quit(self):
        self.help("exit", "Exit the stomp client")
    help_exit = help_quit

    def help_EOF(self):
        self.help("exit", "Exit the stomp client (using CTRL-D)")

    def do_subscribe(self, args):
        args = args.split()
        if len(args) < 1:
            self.__error("Expecting: subscribe <destination> [ack]")
            return

        name = args[0]
        if name in self.__subscriptions:
            self.__error("Already subscribed to %s" % name)
            return

        ack_mode = "auto"
        if len(args) >= 2:
            ack_mode = args[1]

        sid = self.__subscription_id
        self.__subscription_id += 1

        self.__sysout("Subscribing to '%s' with acknowledge set to '%s', id set to '%s'" % (name, ack_mode, sid))
        self.conn.subscribe(destination=name, ack=ack_mode, id=sid)
        self.__subscriptions[name] = SubscriptionInfo(sid, ack_mode)

    def help_subscribe(self):
        self.help("subscribe <destination> [ack]",
                  '''Register to listen to a given destination. Like send, the subscribe command requires a destination
\theader indicating which destination to subscribe to. The ack parameter is optional, and defaults to
\tauto.''', ["destination - the name to subscribe to"], ["ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)"])

    def do_unsubscribe(self, args):
        args = args.split()
        if len(args) < 1:
            self.__error("Expecting: unsubscribe <destination>")
            return

        if args[0] not in self.__subscriptions:
            self.__sysout("Subscription %s not found" % args[0])
            return

        self.__sysout("Unsubscribing from '%s'" % args[0])
        self.conn.unsubscribe(destination=args[0], id=self.__subscriptions[args[0]].id)
        del self.__subscriptions[args[0]]

    def help_unsubscribe(self):
        self.help("unsubscribe <destination>", "Remove an existing subscription - so that the client no longer receive messages from that destination.",
                  ["destination - the name to unsubscribe from"], ["ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)"])

    def do_send(self, args):
        args = args.split()
        if len(args) < 2:
            self.__error("Expecting: send <destination> <message>")
        elif not self.transaction_id:
            self.conn.send(args[0], " ".join(args[1:]))
        else:
            self.conn.send(args[0], " ".join(args[1:]), transaction=self.transaction_id)

    def complete_send(self, text, line):
        mline = line.split(" ")[1]
        offs = len(mline) - len(text)
        return [s[offs:] for s in self.__subscriptions if s.startswith(mline)]
    complete_unsubscribe = complete_send
    complete_sendrec = complete_send
    complete_sendreply = complete_send
    complete_sendfile = complete_send

    def help_send(self):
        self.help("send <destination> <message>", "Sends a message to a destination in the messaging system.",
                  ["destination - where to send the message", "message - the content to send"])

    def do_sendrec(self, args):
        args = args.split()
        receipt_id = stomp.utils.get_uuid()
        if len(args) < 2:
            self.__error("Expecting: sendrec <destination> <message>")
        elif not self.transaction_id:
            self.conn.send(args[0], " ".join(args[1:]), receipt=receipt_id)
        else:
            self.conn.send(args[0], " ".join(args[1:]), transaction=self.transaction_id, receipt=receipt_id)

    def help_sendrec(self):
        self.help("sendrec <destination> <message>",
                  "Sends a message to a destination in the messaging system and blocks for receipt of the message.",
                  ["destination - where to send the message", "message - the content to send"])

    def do_sendreply(self, args):
        args = args.split()
        if len(args) < 3:
            self.__error("Expecting: sendreply <destination> <correlation-id> <message>")
        else:
            self.conn.send(args[0], "%s\n" % " ".join(args[2:]), headers={"correlation-id": args[1]})

    def help_sendreply(self):
        self.help("sendreply <destination> <correlation-id> <message>",
                  "Sends a reply message to a destination in the messaging system.",
                  ["destination - where to send the message",
                   "correlation-id - the correlating identifier to send with the response",
                   "message - the content to send"])

    def do_sendfile(self, args):
        args = args.split()
        if len(args) < 2:
            self.__error("Expecting: sendfile <destination> <filename> [headers.json]")
        elif not os.path.exists(args[1]):
            self.__error("File %s does not exist" % args[1])
        else:
            headers = {}
            if len(args) == 3:
                if not os.path.exists(args[2]):
                    self.__error("File %s does not exist" % args[2])
                    return
                self.__sysout("Loading %s" % args[2])
                with open(args[2], mode="rb") as jf:
                    headers = json.load(jf)
                    self.__sysout("Using headers %s" % str(headers))

            with open(args[1], mode="rb") as f:
                s = f.read()
            msg = base64.b64encode(s).decode()
            if not self.transaction_id:
                self.conn.send(args[0], msg, filename=args[1], headers=headers)
            else:
                self.conn.send(args[0], msg, filename=args[1], headers=headers, transaction=self.transaction_id)

    def help_sendfile(self):
        self.help("sendfile <destination> <filename> [headers.json]",
                  "Sends a file to a destination in the messaging system.",
                  ["destination - where to send the message", "filename - the file to send",
                   "headers.json - json map with headers to send"])

    def do_version(self, args):
        self.__sysout("%s%s [Protocol version %s]%s" %
                      (stomp.colours.BOLD, version_string, self.conn.version, stomp.colours.NO_COLOUR))
    do_ver = do_version

    def help_version(self):
        self.help("version", "Display the version of the client")
    help_ver = help_version

    def check_ack_nack(self, acknackfunc, args):
        if self.nversion >= 1.2 and len(args) < 1:
            self.__error("Expecting: %s <ack-id>" % acknackfunc)
            return None
        elif self.nversion == 1.1 and len(args) < 2:
            self.__error("Expecting: %s <message-id> <subscription-id>" % acknackfunc)
            return None
        elif len(args) < 1:
            self.__error("Expecting: %s <message-id>" % acknackfunc)
            return None

        if self.nversion == 1.1:
            return partial(acknackfunc, args[0], args[1])
        else:
            return partial(acknackfunc, args[0])

    def do_ack(self, args):
        args = args.split()
        func = self.check_ack_nack(self.conn.ack, args)
        if func is None:
            return

        if not self.transaction_id:
            func()
        else:
            func(transaction=self.transaction_id)

    def help_ack(self):
        self.help("ack <message-id> [subscription-id]", '''The command 'ack' is used to acknowledge consumption of a message from a subscription using client
\tacknowledgment. When a client has issued a 'subscribe' with the ack flag set to client, any messages
\treceived from that destination will not be considered to have been consumed (by the server) until
\tthe message has been acknowledged.''', ["message-id - the id of the message being acknowledged"], ["subscription-id the id of the subscription (only required for STOMP 1.1)"])

    def do_nack(self, args):
        args = args.split()
        func = self.check_ack_nack(self.conn.nack, args)
        if func is None:
            return

        if not self.transaction_id:
            func()
        else:
            func(transaction=self.transaction_id)

    def help_nack(self):
        self.help("nack <message-id> [subscription]", '''The command 'nack' is used to acknowledge the failure of a message from a subscription using client
\tacknowledgment. When a client has issued a 'subscribe' with the ack flag set to client, any messages
\treceived from that destination will not be considered to have been consumed (by the server) until
\tthe message has been acknowledged (ack or nack).''', ["message-id - the id of the message being acknowledged"])

    def do_abort(self, args):
        if not self.transaction_id:
            self.__error("Not currently in a transaction")
        else:
            self.conn.abort(transaction=self.transaction_id)
            self.__sysout("Aborted transaction: %s" % self.transaction_id)
            self.transaction_id = None
    do_rollback = do_abort

    def help_abort(self):
        self.help("abort", "Roll back a transaction in progress.")
    help_rollback = help_abort

    def do_begin(self, args):
        if self.transaction_id:
            self.__error("Currently in a transaction (%s)" % self.transaction_id)
        else:
            self.transaction_id = self.conn.begin()
            self.__sysout("Transaction id: %s" % self.transaction_id)

    def help_begin(self):
        self.help("begin", '''Start a transaction. Transactions in this case apply to sending and acknowledging -
\tany messages sent or acknowledged during a transaction will be handled atomically based on the
\ttransaction.''')

    def do_commit(self, args):
        if not self.transaction_id:
            self.__error("Not currently in a transaction")
        else:
            self.__sysout("Committing %s" % self.transaction_id)
            self.conn.commit(transaction=self.transaction_id)
            self.transaction_id = None

    def help_commit(self):
        self.help("commit", "Commit a transaction in progress.")

    def do_stats(self, args):
        args = args.split()
        if len(args) < 1:
            stats = self.conn.get_listener("stats")
            if stats:
                self.__sysout(stats)
            else:
                self.__error("No stats available")
        elif args[0] == "on":
            self.conn.set_listener("stats", StatsListener())
        elif args[0] == "off":
            self.conn.remove_listener("stats")
        else:
            self.__error("Expecting: stats [on|off]")

    def help_stats(self):
        self.help("stats [on|off]", '''Record statistics on messages sent, received, errors, etc. If no argument (on|off) is specified,
\tdump the current statistics.''')

    def do_run(self, args):
        args = args.split()
        if len(args) == 0:
            self.__error("Expecting: run <filename>")
        elif not os.path.exists(args[0]):
            self.__error("File %s was not found" % args[0])
        else:
            with open(args[0]) as f:
                      help='Verbose logging "on" or "off" (if on, full headers from stomp server responses are printed)')
    parser.add_option('--ssl', action='callback', callback=optional_arg(True), dest='ssl',
                      help='Enable SSL connection')

    parser.set_defaults()
    (options, _) = parser.parse_args()
def do_nothing_loop():
    while 1:
        time.sleep(1)


def main():
    arguments = docopt(__doc__, version=version_string)

    if arguments["--listen"] is not None:
        prompt = ""
    else:
    else:
        prompt = '> '

    st = StompCLI(options.host, options.port, options.user, options.password, options.stomp, prompt, verbose, options.ssl)

    if options.listen:
        st.do_subscribe(options.listen)
                  prompt, arguments["--verbose"], heartbeats=heartbeats,
                  use_ssl=arguments["--ssl"],
                  ssl_key_file=arguments["--ssl-key-file"],
                  ssl_cert_file=arguments["--ssl-cert-file"],
                  ssl_ca_file=arguments["--ssl-ca-file"])

    if arguments["--listen"] is not None:
        st.do_subscribe(arguments["--listen"])
        try:
            while 1:
                time.sleep(10)
        except:
            print("\n")
    elif arguments["--file"] is not None:
        st.do_run(arguments["--file"])
    else:
        # disable CTRL-C, since can't guarantee correct handling of disconnect
        import signal

        def signal_handler(signal, frame):
            pass
        signal.signal(signal.SIGINT, signal_handler)

        try:
            try:
                st.cmdloop()
            except KeyboardInterrupt:
                st.do_quit()
        finally:
            st.conn.disconnect()


#
# command line access
#
if __name__ == "__main__":
    try:
        main()
    except:
        pass

<MSG> CLI: Add support for setting heartbeats

<DFF> @@ -44,7 +44,7 @@ class StompCLI(Cmd, ConnectionListener):
     A command line interface to the stomp.py client.  See :py:class:`stomp.connect.StompConnection11`
     for more information on establishing a connection to a stomp server.
     """
-    def __init__(self, host='localhost', port=61613, user='', passcode='', ver='1.1', prompt='> ', verbose=True, use_ssl=False, stdin=sys.stdin, stdout=sys.stdout):
+    def __init__(self, host='localhost', port=61613, user='', passcode='', ver='1.1', prompt='> ', verbose=True, use_ssl=False, heartbeats=(0, 0), stdin=sys.stdin, stdout=sys.stdout):
         Cmd.__init__(self, 'Tab', stdin, stdout)
         ConnectionListener.__init__(self)
         self.prompt = prompt
@@ -55,9 +55,9 @@ class StompCLI(Cmd, ConnectionListener):
         if ver == '1.0':
             self.conn = StompConnection10([(host, port)], wait_on_receipt=True)
         elif ver == '1.1':
-            self.conn = StompConnection11([(host, port)], wait_on_receipt=True)
+            self.conn = StompConnection11([(host, port)], wait_on_receipt=True, heartbeats=heartbeats)
         elif ver == '1.2':
-            self.conn = StompConnection12([(host, port)], wait_on_receipt=True)
+            self.conn = StompConnection12([(host, port)], wait_on_receipt=True, heartbeats=heartbeats)
         elif ver == 'multicast':
             self.conn = MulticastConnection()
         else:
@@ -493,6 +493,8 @@ def main():
                       help='Verbose logging "on" or "off" (if on, full headers from stomp server responses are printed)')
     parser.add_option('--ssl', action='callback', callback=optional_arg(True), dest='ssl',
                       help='Enable SSL connection')
+    parser.add_option('--heartbeats', type='string', dest='heartbeats', default="0,0",
+                      help='Heartbeats to request when connecting with protocol >= 1.1, two comma separated integers.')
 
     parser.set_defaults()
     (options, _) = parser.parse_args()
@@ -510,7 +512,9 @@ def main():
     else:
         prompt = '> '
 
-    st = StompCLI(options.host, options.port, options.user, options.password, options.stomp, prompt, verbose, options.ssl)
+    heartbeats = tuple(map(int, options.heartbeats.split(",")))
+
+    st = StompCLI(options.host, options.port, options.user, options.password, options.stomp, prompt, verbose, options.ssl, heartbeats)
 
     if options.listen:
         st.do_subscribe(options.listen)

{'commit': 'diff --git a/stomp/__main__.py b/stomp/__main__.py\nindex 4e0c53f..959c4a5 100644\n--- a/stomp/__main__.py\n+++ b/stomp/__main__.py\n@@ -44,7 +44,7 @@ class StompCLI(Cmd, ConnectionListener):\n     A command line interface to the stomp.py client.  See :py:class:`stomp.connect.StompConnection11`\n     for more information on establishing a connection to a stomp server.\n     """\n-    def __init__(self, host=\'localhost\', port=61613, user=\'\', passcode=\'\', ver=\'1.1\', prompt=\'> \', verbose=True, use_ssl=False, stdin=sys.stdin, stdout=sys.stdout):\n+    def __init__(self, host=\'localhost\', port=61613, user=\'\', passcode=\'\', ver=\'1.1\', prompt=\'> \', verbose=True, use_ssl=False, heartbeats=(0, 0), stdin=sys.stdin, stdout=sys.stdout):\n         Cmd.__init__(self, \'Tab\', stdin, stdout)\n         ConnectionListener.__init__(self)\n         self.prompt = prompt\n@@ -55,9 +55,9 @@ class StompCLI(Cmd, ConnectionListener):\n         if ver == \'1.0\':\n             self.conn = StompConnection10([(host, port)], wait_on_receipt=True)\n         elif ver == \'1.1\':\n-            self.conn = StompConnection11([(host, port)], wait_on_receipt=True)\n+            self.conn = StompConnection11([(host, port)], wait_on_receipt=True, heartbeats=heartbeats)\n         elif ver == \'1.2\':\n-            self.conn = StompConnection12([(host, port)], wait_on_receipt=True)\n+            self.conn = StompConnection12([(host, port)], wait_on_receipt=True, heartbeats=heartbeats)\n         elif ver == \'multicast\':\n             self.conn = MulticastConnection()\n         else:\n@@ -493,6 +493,8 @@ def main():\n                       help=\'Verbose logging "on" or "off" (if on, full headers from stomp server responses are printed)\')\n     parser.add_option(\'--ssl\', action=\'callback\', callback=optional_arg(True), dest=\'ssl\',\n                       help=\'Enable SSL connection\')\n+    parser.add_option(\'--heartbeats\', type=\'string\', dest=\'heartbeats\', default="0,0",\n+                      help=\'Heartbeats to request when connecting with protocol >= 1.1, two comma separated integers.\')\n \n     parser.set_defaults()\n     (options, _) = parser.parse_args()\n@@ -510,7 +512,9 @@ def main():\n     else:\n         prompt = \'> \'\n \n-    st = StompCLI(options.host, options.port, options.user, options.password, options.stomp, prompt, verbose, options.ssl)\n+    heartbeats = tuple(map(int, options.heartbeats.split(",")))\n+\n+    st = StompCLI(options.host, options.port, options.user, options.password, options.stomp, prompt, verbose, options.ssl, heartbeats)\n \n     if options.listen:\n         st.do_subscribe(options.listen)\n', 'commit_subject': 'CLI: Add support for setting heartbeats', 'repo_name': 'jasonrbriggs/stomp.py', 'committer': {'name': 'Ville Skyttä', 'email': '638ed3ebd6f6b819eabe749cf729971e391a622c@iki.fi', 'time_sec': '1461648182', 'tz_offset': '180', 'date': {'seconds': '1461648182'}}, 'commit_tree': 'c95d2aecb72336579670e96edd89022f7c796c00', 'commit_message': 'CLI: Add support for setting heartbeats\n', 'language_name': 'Shell', 'license': 'apache-2.0', 'hunks': '@@ -44,7 +44,7 @@ class StompCLI(Cmd, ConnectionListener):\n     A command line interface to the stomp.py client.  See :py:class:`stomp.connect.StompConnection11`\n     for more information on establishing a connection to a stomp server.\n     """\n-    def __init__(self, host=\'localhost\', port=61613, user=\'\', passcode=\'\', ver=\'1.1\', prompt=\'> \', verbose=True, use_ssl=False, stdin=sys.stdin, stdout=sys.stdout):\n+    def __init__(self, host=\'localhost\', port=61613, user=\'\', passcode=\'\', ver=\'1.1\', prompt=\'> \', verbose=True, use_ssl=False, heartbeats=(0, 0), stdin=sys.stdin, stdout=sys.stdout):\n         Cmd.__init__(self, \'Tab\', stdin, stdout)\n         ConnectionListener.__init__(self)\n         self.prompt = prompt\n@@ -55,9 +55,9 @@ class StompCLI(Cmd, ConnectionListener):\n         if ver == \'1.0\':\n             self.conn = StompConnection10([(host, port)], wait_on_receipt=True)\n         elif ver == \'1.1\':\n-            self.conn = StompConnection11([(host, port)], wait_on_receipt=True)\n+            self.conn = StompConnection11([(host, port)], wait_on_receipt=True, heartbeats=heartbeats)\n         elif ver == \'1.2\':\n-            self.conn = StompConnection12([(host, port)], wait_on_receipt=True)\n+            self.conn = StompConnection12([(host, port)], wait_on_receipt=True, heartbeats=heartbeats)\n         elif ver == \'multicast\':\n             self.conn = MulticastConnection()\n         else:\n@@ -493,6 +493,8 @@ def main():\n                       help=\'Verbose logging "on" or "off" (if on, full headers from stomp server responses are printed)\')\n     parser.add_option(\'--ssl\', action=\'callback\', callback=optional_arg(True), dest=\'ssl\',\n                       help=\'Enable SSL connection\')\n+    parser.add_option(\'--heartbeats\', type=\'string\', dest=\'heartbeats\', default="0,0",\n+                      help=\'Heartbeats to request when connecting with protocol >= 1.1, two comma separated integers.\')\n \n     parser.set_defaults()\n     (options, _) = parser.parse_args()\n@@ -510,7 +512,9 @@ def main():\n     else:\n         prompt = \'> \'\n \n-    st = StompCLI(options.host, options.port, options.user, options.password, options.stomp, prompt, verbose, options.ssl)\n+    heartbeats = tuple(map(int, options.heartbeats.split(",")))\n+\n+    st = StompCLI(options.host, options.port, options.user, options.password, options.stomp, prompt, verbose, options.ssl, heartbeats)\n \n     if options.listen:\n         st.do_subscribe(options.listen)\n', 'addition_count': 8, 'deletion_count': 4, 'src_file': 'a/stomp/__main__.py', 'tgt_file': 'b/stomp/__main__.py', 'file_extension': '.py', 'before_file': '"""\nStomp.py command-line client\n\nUsage: stomp [options]\n\nOptions:\n  --version                    Show the version number and exit\n  -h, --help                   Show this help message and exit\n  -H <host>, --host=<host>     Hostname or IP address to connect to. [default: localhost]\n  -P <port>, --port=<port>     Port providing stomp protocol connections. [default: 61613]\n  -U <user>, --user=<user>     Username for the connection\n  -W <password>, --password=<password>\n                               Password for the connection\n  -F <filename>, --file=<filename>\n                               File containing commands to be executed, instead of\n                               prompting from the command prompt.\n  -S <protocol version>, --protocol=<protocol version>\n                               Set the STOMP protocol version (1.0, 1.1, 1.2) [default: 1.1]\n  -L <queue>, --listen=<queue> Listen for messages on a queue/destination\n  -V, --verbose                Verbose logging "on" or "off" (if on, full headers\n                               from stomp server responses are printed)\n  --heartbeats=<heartbeats>    Heartbeats to request when connecting with protocol >=\n                               1.1 (two comma separated integers required) [default: 0,0]\n  --ssl                        Enable SSL connection\n  --ssl-key-file=<key-file>    ssl key file\n  --ssl-cert-file=<cert-file>  ssl cert file\n  --ssl-ca-file=<ca-file>      ssl ca certs file\n\n"""\n\nimport base64\nimport json\nimport os\nimport re\nimport sys\nimport time\nfrom cmd import Cmd\nfrom functools import partial\n\nfrom docopt import docopt\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\nimport stomp.colours\n    A command line interface to the stomp.py client.  See :py:class:`stomp.connect.StompConnection11`\n    for more information on establishing a connection to a stomp server.\n    """\n    def __init__(self, host=\'localhost\', port=61613, user=\'\', passcode=\'\', ver=\'1.1\', prompt=\'> \', verbose=True, use_ssl=False, stdin=sys.stdin, stdout=sys.stdout):\n        Cmd.__init__(self, \'Tab\', stdin, stdout)\n        ConnectionListener.__init__(self)\n        self.prompt = prompt\n\nversion_string = "%s.%s.%s" % stomp.__version__\n\nheartbeat_pattern = re.compile(r"[0-9]+,[0-9]+")\n        if ver == \'1.0\':\n            self.conn = StompConnection10([(host, port)], wait_on_receipt=True)\n        elif ver == \'1.1\':\n            self.conn = StompConnection11([(host, port)], wait_on_receipt=True)\n        elif ver == \'1.2\':\n            self.conn = StompConnection12([(host, port)], wait_on_receipt=True)\n        elif ver == \'multicast\':\n            self.conn = MulticastConnection()\n        else:\n\n\nclass StompCLI(Cmd, ConnectionListener):\n    """\n    A command line interface to the stomp.py client.  See :py:class:`stomp.connect.StompConnection11`\n    for more information on establishing a connection to a stomp server.\n    """\n    def __init__(self, host="localhost", port=61613, user="", passcode="", ver="1.1", prompt="> ", verbose=True,\n                 heartbeats=(0, 0), use_ssl=False, ssl_key_file=None, ssl_cert_file=None, ssl_ca_file=None,\n                 stdin=sys.stdin, stdout=sys.stdout):\n        Cmd.__init__(self, "Tab", stdin, stdout)\n        ConnectionListener.__init__(self)\n        self.__start = True\n        self.prompt = prompt\n        self.verbose = verbose\n        self.user = user\n        self.passcode = passcode\n        self.__quit = False\n        if ver == "1.0":\n            self.conn = StompConnection10([(host, port)])\n        elif ver == "1.1":\n            self.conn = StompConnection11([(host, port)], heartbeats=heartbeats)\n        elif ver == "1.2":\n            self.conn = StompConnection12([(host, port)], heartbeats=heartbeats)\n        elif ver == "multicast":\n            self.conn = MulticastConnection()\n        else:\n            raise RuntimeError("Unknown version")\n        if use_ssl:\n            self.conn.set_ssl([(host, port)], key_file=ssl_key_file, cert_file=ssl_cert_file, ca_certs=ssl_ca_file)\n        self.conn.set_listener("", self)\n        self.conn.connect(self.user, self.passcode, wait=True)\n        self.transaction_id = None\n        self.version = ver\n        try:\n            self.nversion = float(ver)\n        except ValueError:\n            self.nversion = 1.0\n        self.__subscriptions = {}\n        self.__subscription_id = 1\n\n    def __print_async(self, frame_type, frame):\n        """\n        Utility function to print a message and setup the command prompt\n        for the next input\n        """\n        if self.__quit:\n            return\n        if self.verbose:\n            self.__sysout(frame_type)\n            for k, v in frame.headers.items():\n                self.__sysout("%s: %s" % (k, v))\n        else:\n            if "message-id" in frame.headers:\n                self.__sysout("message-id: %s" % frame.headers["message-id"])\n            if "subscription" in frame.headers:\n                self.__sysout("subscription: %s" % frame.headers["subscription"])\n        if self.prompt != "":\n            self.__sysout("")\n        self.__sysout(frame.body)\n        if not self.__start:\n            self.__sysout(self.prompt, end="")\n        else:\n            self.__start = False\n        self.stdout.flush()\n\n    def __sysout(self, msg, end="\\n"):\n        if self.__quit:\n            return\n        self.stdout.write(str(msg) + end)\n\n    def __error(self, msg, end="\\n"):\n        self.stdout.write(stomp.colours.BOLD + stomp.colours.RED + str(msg) + stomp.colours.NO_COLOUR + end)\n\n    def on_connecting(self, host_and_port):\n        """\n        See :py:meth:`ConnectionListener.on_connecting`\n        """\n        pass\n\n    def on_disconnected(self):\n        """\n        see :py:meth:`ConnectionListener.on_disconnected`\n        """\n        if not self.__quit:\n            self.__error("lost connection")\n\n    def on_message(self, frame):\n        """\n        See :py:meth:`ConnectionListener.on_message`\n\n        Special case: if the header \'filename\' is present, the content is written out\n        as a file\n        """\n        self.__sysout("")\n        if "filename" in frame.headers:\n            content = base64.b64decode(frame.body.encode())\n            if os.path.exists(frame.headers["filename"]):\n                fname = "%s.%s" % (frame.headers["filename"], int(time.time()))\n            else:\n                fname = frame.headers["filename"]\n            with open(fname, "wb") as f:\n                f.write(content)\n            frame.body = "Saved file: %s" % fname\n        self.__print_async("MESSAGE", frame)\n\n    def on_error(self, frame):\n        """\n        See :py:meth:`ConnectionListener.on_error`\n        """\n        self.__print_async("ERROR", frame)\n\n    def on_receipt(self, frame):\n        """\n        See :py:meth:`ConnectionListener.on_receipt`\n        """\n        self.__print_async("RECEIPT", frame)\n\n    def on_connected(self, frame):\n        """\n        See :py:meth:`ConnectionListener.on_connected`\n        """\n        self.__print_async("CONNECTED", frame)\n\n    def on_send(self, frame):\n        if self.verbose:\n            self.__sysout("Sending %s" % str(frame))\n\n    def help_help(self):\n        self.__sysout("Quick help on commands")\n\n    def default(self, line):\n        self.__error("Unknown command: %s" % line.split()[0])\n\n    def emptyline(self):\n        pass\n\n    def help(self, usage, description, required=(), optional=()):\n        rparams = "\\n\\t" + "\\n\\t".join(required)\n        oparams = "\\n\\t" + "\\n\\t".join(optional)\n\n        m = {\n            "hl": stomp.colours.BOLD + stomp.colours.GREEN,\n            "nc": stomp.colours.NO_COLOUR,\n            "usage": usage,\n            "description": description,\n            "required": rparams.rstrip(),\n            "optional": oparams.rstrip()\n        }\n\n        if rparams.rstrip() != "":\n            rparams = \'\'\'%(hl)sRequired Parameters:%(nc)s%(required)s\\n\\n\'\'\' % m\n            m["required"] = rparams\n\n        if oparams.rstrip() != "":\n            oparams = \'\'\'%(hl)sOptional Parameters:%(nc)s%(optional)s\\n\\n\'\'\' % m\n            m["optional"] = oparams\n\n        self.__sysout(\'\'\'%(hl)sUsage:%(nc)s\n\\t%(usage)s\n\n%(required)s%(optional)s%(hl)sDescription:%(nc)s\n\\t%(description)s\n        \'\'\' % m)\n\n    def do_quit(self, args):\n        self.__quit = True\n        self.__sysout("Shutting down, please wait")\n        return True\n    do_exit = do_quit\n    do_EOF = do_quit\n\n    def help_quit(self):\n        self.help("exit", "Exit the stomp client")\n    help_exit = help_quit\n\n    def help_EOF(self):\n        self.help("exit", "Exit the stomp client (using CTRL-D)")\n\n    def do_subscribe(self, args):\n        args = args.split()\n        if len(args) < 1:\n            self.__error("Expecting: subscribe <destination> [ack]")\n            return\n\n        name = args[0]\n        if name in self.__subscriptions:\n            self.__error("Already subscribed to %s" % name)\n            return\n\n        ack_mode = "auto"\n        if len(args) >= 2:\n            ack_mode = args[1]\n\n        sid = self.__subscription_id\n        self.__subscription_id += 1\n\n        self.__sysout("Subscribing to \'%s\' with acknowledge set to \'%s\', id set to \'%s\'" % (name, ack_mode, sid))\n        self.conn.subscribe(destination=name, ack=ack_mode, id=sid)\n        self.__subscriptions[name] = SubscriptionInfo(sid, ack_mode)\n\n    def help_subscribe(self):\n        self.help("subscribe <destination> [ack]",\n                  \'\'\'Register to listen to a given destination. Like send, the subscribe command requires a destination\n\\theader indicating which destination to subscribe to. The ack parameter is optional, and defaults to\n\\tauto.\'\'\', ["destination - the name to subscribe to"], ["ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)"])\n\n    def do_unsubscribe(self, args):\n        args = args.split()\n        if len(args) < 1:\n            self.__error("Expecting: unsubscribe <destination>")\n            return\n\n        if args[0] not in self.__subscriptions:\n            self.__sysout("Subscription %s not found" % args[0])\n            return\n\n        self.__sysout("Unsubscribing from \'%s\'" % args[0])\n        self.conn.unsubscribe(destination=args[0], id=self.__subscriptions[args[0]].id)\n        del self.__subscriptions[args[0]]\n\n    def help_unsubscribe(self):\n        self.help("unsubscribe <destination>", "Remove an existing subscription - so that the client no longer receive messages from that destination.",\n                  ["destination - the name to unsubscribe from"], ["ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)"])\n\n    def do_send(self, args):\n        args = args.split()\n        if len(args) < 2:\n            self.__error("Expecting: send <destination> <message>")\n        elif not self.transaction_id:\n            self.conn.send(args[0], " ".join(args[1:]))\n        else:\n            self.conn.send(args[0], " ".join(args[1:]), transaction=self.transaction_id)\n\n    def complete_send(self, text, line):\n        mline = line.split(" ")[1]\n        offs = len(mline) - len(text)\n        return [s[offs:] for s in self.__subscriptions if s.startswith(mline)]\n    complete_unsubscribe = complete_send\n    complete_sendrec = complete_send\n    complete_sendreply = complete_send\n    complete_sendfile = complete_send\n\n    def help_send(self):\n        self.help("send <destination> <message>", "Sends a message to a destination in the messaging system.",\n                  ["destination - where to send the message", "message - the content to send"])\n\n    def do_sendrec(self, args):\n        args = args.split()\n        receipt_id = stomp.utils.get_uuid()\n        if len(args) < 2:\n            self.__error("Expecting: sendrec <destination> <message>")\n        elif not self.transaction_id:\n            self.conn.send(args[0], " ".join(args[1:]), receipt=receipt_id)\n        else:\n            self.conn.send(args[0], " ".join(args[1:]), transaction=self.transaction_id, receipt=receipt_id)\n\n    def help_sendrec(self):\n        self.help("sendrec <destination> <message>",\n                  "Sends a message to a destination in the messaging system and blocks for receipt of the message.",\n                  ["destination - where to send the message", "message - the content to send"])\n\n    def do_sendreply(self, args):\n        args = args.split()\n        if len(args) < 3:\n            self.__error("Expecting: sendreply <destination> <correlation-id> <message>")\n        else:\n            self.conn.send(args[0], "%s\\n" % " ".join(args[2:]), headers={"correlation-id": args[1]})\n\n    def help_sendreply(self):\n        self.help("sendreply <destination> <correlation-id> <message>",\n                  "Sends a reply message to a destination in the messaging system.",\n                  ["destination - where to send the message",\n                   "correlation-id - the correlating identifier to send with the response",\n                   "message - the content to send"])\n\n    def do_sendfile(self, args):\n        args = args.split()\n        if len(args) < 2:\n            self.__error("Expecting: sendfile <destination> <filename> [headers.json]")\n        elif not os.path.exists(args[1]):\n            self.__error("File %s does not exist" % args[1])\n        else:\n            headers = {}\n            if len(args) == 3:\n                if not os.path.exists(args[2]):\n                    self.__error("File %s does not exist" % args[2])\n                    return\n                self.__sysout("Loading %s" % args[2])\n                with open(args[2], mode="rb") as jf:\n                    headers = json.load(jf)\n                    self.__sysout("Using headers %s" % str(headers))\n\n            with open(args[1], mode="rb") as f:\n                s = f.read()\n            msg = base64.b64encode(s).decode()\n            if not self.transaction_id:\n                self.conn.send(args[0], msg, filename=args[1], headers=headers)\n            else:\n                self.conn.send(args[0], msg, filename=args[1], headers=headers, transaction=self.transaction_id)\n\n    def help_sendfile(self):\n        self.help("sendfile <destination> <filename> [headers.json]",\n                  "Sends a file to a destination in the messaging system.",\n                  ["destination - where to send the message", "filename - the file to send",\n                   "headers.json - json map with headers to send"])\n\n    def do_version(self, args):\n        self.__sysout("%s%s [Protocol version %s]%s" %\n                      (stomp.colours.BOLD, version_string, self.conn.version, stomp.colours.NO_COLOUR))\n    do_ver = do_version\n\n    def help_version(self):\n        self.help("version", "Display the version of the client")\n    help_ver = help_version\n\n    def check_ack_nack(self, acknackfunc, args):\n        if self.nversion >= 1.2 and len(args) < 1:\n            self.__error("Expecting: %s <ack-id>" % acknackfunc)\n            return None\n        elif self.nversion == 1.1 and len(args) < 2:\n            self.__error("Expecting: %s <message-id> <subscription-id>" % acknackfunc)\n            return None\n        elif len(args) < 1:\n            self.__error("Expecting: %s <message-id>" % acknackfunc)\n            return None\n\n        if self.nversion == 1.1:\n            return partial(acknackfunc, args[0], args[1])\n        else:\n            return partial(acknackfunc, args[0])\n\n    def do_ack(self, args):\n        args = args.split()\n        func = self.check_ack_nack(self.conn.ack, args)\n        if func is None:\n            return\n\n        if not self.transaction_id:\n            func()\n        else:\n            func(transaction=self.transaction_id)\n\n    def help_ack(self):\n        self.help("ack <message-id> [subscription-id]", \'\'\'The command \'ack\' is used to acknowledge consumption of a message from a subscription using client\n\\tacknowledgment. When a client has issued a \'subscribe\' with the ack flag set to client, any messages\n\\treceived from that destination will not be considered to have been consumed (by the server) until\n\\tthe message has been acknowledged.\'\'\', ["message-id - the id of the message being acknowledged"], ["subscription-id the id of the subscription (only required for STOMP 1.1)"])\n\n    def do_nack(self, args):\n        args = args.split()\n        func = self.check_ack_nack(self.conn.nack, args)\n        if func is None:\n            return\n\n        if not self.transaction_id:\n            func()\n        else:\n            func(transaction=self.transaction_id)\n\n    def help_nack(self):\n        self.help("nack <message-id> [subscription]", \'\'\'The command \'nack\' is used to acknowledge the failure of a message from a subscription using client\n\\tacknowledgment. When a client has issued a \'subscribe\' with the ack flag set to client, any messages\n\\treceived from that destination will not be considered to have been consumed (by the server) until\n\\tthe message has been acknowledged (ack or nack).\'\'\', ["message-id - the id of the message being acknowledged"])\n\n    def do_abort(self, args):\n        if not self.transaction_id:\n            self.__error("Not currently in a transaction")\n        else:\n            self.conn.abort(transaction=self.transaction_id)\n            self.__sysout("Aborted transaction: %s" % self.transaction_id)\n            self.transaction_id = None\n    do_rollback = do_abort\n\n    def help_abort(self):\n        self.help("abort", "Roll back a transaction in progress.")\n    help_rollback = help_abort\n\n    def do_begin(self, args):\n        if self.transaction_id:\n            self.__error("Currently in a transaction (%s)" % self.transaction_id)\n        else:\n            self.transaction_id = self.conn.begin()\n            self.__sysout("Transaction id: %s" % self.transaction_id)\n\n    def help_begin(self):\n        self.help("begin", \'\'\'Start a transaction. Transactions in this case apply to sending and acknowledging -\n\\tany messages sent or acknowledged during a transaction will be handled atomically based on the\n\\ttransaction.\'\'\')\n\n    def do_commit(self, args):\n        if not self.transaction_id:\n            self.__error("Not currently in a transaction")\n        else:\n            self.__sysout("Committing %s" % self.transaction_id)\n            self.conn.commit(transaction=self.transaction_id)\n            self.transaction_id = None\n\n    def help_commit(self):\n        self.help("commit", "Commit a transaction in progress.")\n\n    def do_stats(self, args):\n        args = args.split()\n        if len(args) < 1:\n            stats = self.conn.get_listener("stats")\n            if stats:\n                self.__sysout(stats)\n            else:\n                self.__error("No stats available")\n        elif args[0] == "on":\n            self.conn.set_listener("stats", StatsListener())\n        elif args[0] == "off":\n            self.conn.remove_listener("stats")\n        else:\n            self.__error("Expecting: stats [on|off]")\n\n    def help_stats(self):\n        self.help("stats [on|off]", \'\'\'Record statistics on messages sent, received, errors, etc. If no argument (on|off) is specified,\n\\tdump the current statistics.\'\'\')\n\n    def do_run(self, args):\n        args = args.split()\n        if len(args) == 0:\n            self.__error("Expecting: run <filename>")\n        elif not os.path.exists(args[0]):\n            self.__error("File %s was not found" % args[0])\n        else:\n            with open(args[0]) as f:\n                      help=\'Verbose logging "on" or "off" (if on, full headers from stomp server responses are printed)\')\n    parser.add_option(\'--ssl\', action=\'callback\', callback=optional_arg(True), dest=\'ssl\',\n                      help=\'Enable SSL connection\')\n\n    parser.set_defaults()\n    (options, _) = parser.parse_args()\ndef do_nothing_loop():\n    while 1:\n        time.sleep(1)\n\n\ndef main():\n    arguments = docopt(__doc__, version=version_string)\n\n    if arguments["--listen"] is not None:\n        prompt = ""\n    else:\n    else:\n        prompt = \'> \'\n\n    st = StompCLI(options.host, options.port, options.user, options.password, options.stomp, prompt, verbose, options.ssl)\n\n    if options.listen:\n        st.do_subscribe(options.listen)\n                  prompt, arguments["--verbose"], heartbeats=heartbeats,\n                  use_ssl=arguments["--ssl"],\n                  ssl_key_file=arguments["--ssl-key-file"],\n                  ssl_cert_file=arguments["--ssl-cert-file"],\n                  ssl_ca_file=arguments["--ssl-ca-file"])\n\n    if arguments["--listen"] is not None:\n        st.do_subscribe(arguments["--listen"])\n        try:\n            while 1:\n                time.sleep(10)\n        except:\n            print("\\n")\n    elif arguments["--file"] is not None:\n        st.do_run(arguments["--file"])\n    else:\n        # disable CTRL-C, since can\'t guarantee correct handling of disconnect\n        import signal\n\n        def signal_handler(signal, frame):\n            pass\n        signal.signal(signal.SIGINT, signal_handler)\n\n        try:\n            try:\n                st.cmdloop()\n            except KeyboardInterrupt:\n                st.do_quit()\n        finally:\n            st.conn.disconnect()\n\n\n#\n# command line access\n#\nif __name__ == "__main__":\n    try:\n        main()\n    except:\n        pass\n', 'message': 'CLI: Add support for setting heartbeats\n', 'author_name': 'Ville Skyttä', 'lang': 'py'}