Author: jonathan
Date: Sun Dec  5 18:49:37 2010
New Revision: 1042398

URL: http://svn.apache.org/viewvc?rev=1042398&view=rev
Log:
Converted tools to use optparse. 

Now all tools in this directory use optparse for their command lines, rather 
than a variety of different approaches. Simplifies option handling 
significantly. 

Doesn't simplify arguments list in qpid-route and qpid-config.


Modified:
    qpid/trunk/qpid/tools/src/py/qpid-cluster
    qpid/trunk/qpid/tools/src/py/qpid-config
    qpid/trunk/qpid/tools/src/py/qpid-route
    qpid/trunk/qpid/tools/src/py/qpid-stat
    qpid/trunk/qpid/tools/src/py/qpid-tool

Modified: qpid/trunk/qpid/tools/src/py/qpid-cluster
URL: 
http://svn.apache.org/viewvc/qpid/trunk/qpid/tools/src/py/qpid-cluster?rev=1042398&r1=1042397&r2=1042398&view=diff
==============================================================================
--- qpid/trunk/qpid/tools/src/py/qpid-cluster (original)
+++ qpid/trunk/qpid/tools/src/py/qpid-cluster Sun Dec  5 18:49:37 2010
@@ -20,7 +20,7 @@
 #
 
 import os
-import getopt
+from optparse import OptionParser, OptionGroup
 import sys
 import locale
 import socket
@@ -38,27 +38,6 @@ class Config:
         self._showConn = False
         self._delConn = None
 
-def usage (short=False):
-    print "Usage:  qpid-cluster [OPTIONS] [broker-addr]"
-    print
-    print "             broker-addr is in the form:   [username/passw...@] 
hostname | ip-address [:<port>]"
-    print "             ex:  localhost, 10.1.1.7:10000, broker-host:10000, 
guest/gu...@localhost"
-    print
-    if short:
-        return
-
-    print "Options:"
-    print "          --timeout seconds (10)  Maximum time to wait for broker 
connection"
-    print "          -C [--all-connections]  View client connections to all 
cluster members"
-    print "          -c [--connections] ID   View client connections to 
specified member"
-    print "          -d [--del-connection] HOST:PORT"
-    print "                                  Disconnect a client connection"
-    print "          -s [--stop] ID          Stop one member of the cluster by 
its ID"
-    print "          -k [--all-stop]         Shut down the whole cluster"
-    print "          -f [--force]            Suppress the 'are-you-sure?' 
prompt"
-    print "          -n [--numeric]          Don't resolve names"
-    print
-
 class IpAddr:
     def __init__(self, text):
         if text.find("@") != -1:
@@ -256,68 +235,52 @@ def main(argv=None):
     if argv is None: argv = sys.argv
     try:
         config = Config()
-        try:
-            longOpts = ("help", "stop=", "all-stop", "force", "connections=", 
"all-connections" "del-connection=", "numeric", "timeout=")
-            (optlist, encArgs) = getopt.gnu_getopt(argv[1:], "hs:kfCc:d:n", 
longOpts)
-        except Exception, e:
-            usage (short=True)
-            # make output match optparse-based tools' output, for consistent 
scripting
-            msg = str(e).replace('option', 'no such option:').replace('not 
recognized', '')
-            print "qpid-config: error:", msg
-            sys.exit (1)    
 
-        try:
-            encoding = locale.getpreferredencoding()
-            cargs = [a.decode(encoding) for a in encArgs]
-        except:
-            cargs = encArgs
+        parser = OptionParser(usage="usage: %prog [options] BROKER",
+                      description="Example: $ qpid-cluster -C  
broker-host:10000")
 
-        count = 0
-        for opt in optlist:
-            if opt[0] == "-h" or opt[0] == "--help":
-                usage()
-                sys.exit(1)
-            if opt[0] == "--timeout":
-                config._connTimeout = int(opt[1])
-                if config._connTimeout == 0:
-                    config._connTimeout = None
-            if opt[0] == "-s" or opt[0] == "--stop":
-                config._stopId = opt[1]
-                if len(config._stopId.split(":")) != 2:
-                    raise Exception("Member ID must be of form: <host or 
ip>:<number>")
-                count += 1
-            if opt[0] == "-k" or opt[0] == "--all-stop":
-                config._stopAll = True
-                count += 1
-            if opt[0] == "-f" or opt[0] == "--force":
-                config._force = True
-            if opt[0] == "-n" or opt[0] == "--numeric":
-                config._numeric = True
-            if opt[0] == "-C" or opt[0] == "--all-connections":
-                config._showConn = "all"
-                count += 1
-            if opt[0] == "-c" or opt[0] == "--connections":
-                config._showConn = opt[1]
-                if len(config._showConn.split(":")) != 2:
-                    raise Exception("Member ID must be of form: <host or 
ip>:<number>")
-                count += 1
-            if opt[0] == "-d" or opt[0] == "--del-connection":
-                config._delConn = opt[1]
-                if len(config._delConn.split(":")) != 2:
-                    raise Exception("Connection must be of form: <host or 
ip>:<port>")
-                count += 1
+        parser.add_option("-t", "--timeout", action="store", type="int", 
default="10", metavar="SECS", help="Maximum time to wait for broker connection 
(in seconds)")
+        parser.add_option("-C", "--all-connections", action="store_true", 
default=False, help="View client connections to all cluster members")
+        parser.add_option("-c", "--connections",  metavar="ID", help="View 
client connections to specified member")
+        parser.add_option("-d", "--del-connection",  metavar="HOST:PORT", 
help="Disconnect a client connection")
+        parser.add_option("-s", "--stop",  metavar="ID", help="Stop one member 
of the cluster by its ID")
+        parser.add_option("-k", "--all-stop", action="store_true", 
default=False, help="Shut down the whole cluster")
+        parser.add_option("-f", "--force", action="store_true", default=False, 
help="Suppress the 'are you sure' prompt")
+        parser.add_option("-n", "--numeric", action="store_true", 
default=False, help="Don't resolve names")
 
-        if count > 1:
-            print "Only one command option may be supplied"
-            print
-            usage()
-            return 1
+        opts, args = parser.parse_args()
 
-        nargs = len(cargs)
-        bm    = BrokerManager(config)
+        if args:
+            _host = args[0]
 
-        if nargs == 1:
-            config._host = cargs[0]
+        if opts.timeout != 0:
+            config._connTimeout = opts.timeout
+        else:
+            config._connTimeout = None
+
+        if opts.all_connections:
+            config._showConn = "all"
+
+        if opts.connections:
+            config._connections = opts.connections
+            if len(config._connections.split(":")) != 2:
+                parser.error("Member ID must be of form: <host or 
ip>:<number>")
+
+        if opts.del_connection:
+            config._delConn = opts.del_connection
+            if len(config._delConn.split(":")) != 2: 
+                parser.error("Member ID must be of form: <host or 
ip>:<number>")
+
+        if opts.stop:
+            config._stopID = opts.stop
+            if len(config._stopId.split(":")) != 2: 
+                parser.error("Member ID must be of form: <host or 
ip>:<number>")
+
+        config._stopAll = opts.all_stop
+        config._force = opts.force
+        config._numeric = opts.numeric
+
+        bm    = BrokerManager(config)
 
         try:
             bm.SetBroker(config._host)

Modified: qpid/trunk/qpid/tools/src/py/qpid-config
URL: 
http://svn.apache.org/viewvc/qpid/trunk/qpid/tools/src/py/qpid-config?rev=1042398&r1=1042397&r2=1042398&view=diff
==============================================================================
--- qpid/trunk/qpid/tools/src/py/qpid-config (original)
+++ qpid/trunk/qpid/tools/src/py/qpid-config Sun Dec  5 18:49:37 2010
@@ -20,7 +20,7 @@
 #
 
 import os
-import getopt
+from optparse import OptionParser, OptionGroup, IndentedHelpFormatter
 import sys
 import locale
 from qmf.console import Session
@@ -57,90 +57,6 @@ MSG_SEQUENCE = "qpid.msg_sequence"
 IVE = "qpid.ive"
 QUEUE_EVENT_GENERATION = "qpid.queue_event_generation"
 
-def Usage (short=False):
-    print "Usage:  qpid-config [OPTIONS]"
-    print "        qpid-config [OPTIONS] exchanges [filter-string]"
-    print "        qpid-config [OPTIONS] queues    [filter-string]"
-    print "        qpid-config [OPTIONS] add exchange <type> <name> 
[AddExchangeOptions]"
-    print "        qpid-config [OPTIONS] del exchange <name>"
-    print "        qpid-config [OPTIONS] add queue <name> [AddQueueOptions]"
-    print "        qpid-config [OPTIONS] del queue <name> [DelQueueOptions]"
-    print "        qpid-config [OPTIONS] bind   <exchange-name> <queue-name> 
[binding-key]"
-    print "                  <for type xml>     [-f -|filename]"
-    print "                  <for type header>  [all|any] k1=v1 [, k2=v2...]"
-    print "        qpid-config [OPTIONS] unbind <exchange-name> <queue-name> 
[binding-key]"
-    print
-    if short:
-        return
-
-    print "Options:"
-    print "    --timeout seconds (10)                    Maximum time to wait 
for broker connection"
-    print "    -b [ --bindings ]                         Show bindings in 
queue or exchange list"
-    print "    -a [ --broker-addr ] Address (localhost)  Address of qpidd 
broker"
-    print "         broker-addr is in the form:   [username/passw...@] 
hostname | ip-address [:<port>]"
-    print "         ex:  localhost, 10.1.1.7:10000, broker-host:10000, 
guest/gu...@localhost"
-    print
-    print "Add Queue Options:"
-    print "    --alternate-exchange [name of the alternate exchange]"
-    print "                         The alternate-exchange field specifies how 
messages on this queue should"
-    print "                         be treated when they are rejected by a 
subscriber, or when they are"
-    print "                         orphaned by queue deletion. When present, 
rejected or orphaned messages"
-    print "                         MUST be routed to the alternate-exchange. 
In all cases the messages MUST"
-    print "                         be removed from the queue."
-    print "    --passive            Do not actually change the broker state 
(queue will not be created)"
-    print "    --durable            Queue is durable"
-    print "    --cluster-durable    Queue becomes durable if there is only one 
functioning cluster node"
-    print "    --file-count N (8)   Number of files in queue's persistence 
journal"
-    print "    --file-size  N (24)  File size in pages (64Kib/page)"
-    print "    --max-queue-size N   Maximum in-memory queue size as bytes"
-    print "    --max-queue-count N  Maximum in-memory queue size as a number 
of messages"
-    print "    --limit-policy [none | reject | flow-to-disk | ring | 
ring-strict]"
-    print "                         Action taken when queue limit is reached:"
-    print "                             none (default) - Use broker's default 
policy"
-    print "                             reject         - Reject enqueued 
messages"
-    print "                             flow-to-disk   - Page messages to disk"
-    print "                             ring           - Replace oldest 
unacquired message with new"
-    print "                             ring-strict    - Replace oldest 
message, reject if oldest is acquired"
-    print "    --order [fifo | lvq | lvq-no-browse]"
-    print "                         Set queue ordering policy:"
-    print "                             fifo (default) - First in, first out"
-    print "                             lvq            - Last Value Queue 
ordering, allows queue browsing"
-    print "                             lvq-no-browse  - Last Value Queue 
ordering, browsing clients may lose data"
-    print "    --generate-queue-events N"
-    print "                         If set to 1, every enqueue will generate 
an event that can be processed by"
-    print "                         registered listeners (e.g. for 
replication). If set to 2, events will be"
-    print "                         generated for enqueues and dequeues"
-    print
-    print "Del Queue Options:"
-    print "    --force               Force delete of queue even if it's 
currently used or it's not empty"
-    print "    --force-if-not-empty  Force delete of queue even if it's not 
empty"
-    print "    --force-if-used       Force delete of queue even if it's 
currently used"
-    print
-    print "Add Exchange <type> values:"
-    print "    direct     Direct exchange for point-to-point communication"
-    print "    fanout     Fanout exchange for broadcast communication"
-    print "    topic      Topic exchange that routes messages using binding 
keys with wildcards"
-    print "    headers    Headers exchange that matches header fields against 
the binding keys"
-    print
-    print "Add Exchange Options:"
-    print "    --alternate-exchange [name of the alternate exchange]"
-    print "                         In the event that a message cannot be 
routed, this is the name of the exchange to"
-    print "                         which the message will be sent. Messages 
transferred using message.transfer will"
-    print "                         be routed to the alternate-exchange only 
if they are sent with the \"none\""
-    print "                         accept-mode, and the discard-unroutable 
delivery property is set to false, and"
-    print "                         there is no queue to route to for the 
given message according to the bindings"
-    print "                         on this exchange."
-    print "    --passive            Do not actually change the broker state 
(exchange will not be created)"
-    print "    --durable            Exchange is durable"
-    print "    --sequence           Exchange will insert a 'qpid.msg_sequence' 
field in the message header"
-    print "                         with a value that increments for each 
message forwarded."
-    print "    --ive                Exchange will behave as an 
'initial-value-exchange', keeping a reference"
-    print "                         to the last message forwarded and 
enqueuing that message to newly bound"
-    print "                         queues."
-    print
-    sys.exit (1)
-
-
 #
 # helpers for the arg parsing in bind().  return multiple values; "ok"
 # followed by the resultant args
@@ -165,14 +81,15 @@ def snarf_xquery_args():
 #
 # look for "any"/"all" and grok the rest of argv into a map
 #
-def snarf_header_args(cargs):
-    if len(cargs) < 2:
+def snarf_header_args(args):
+
+    if len(args) < 2:
         print "Invalid args to bind headers:  need 'any'/'all' plus conditions"
         return [False]
-    op = cargs[0]
+    op = args[0]
     if op == "all" or op == "any":
         kv = {}
-        for thing in cargs[1:]:
+        for thing in args[1:]:
             k_and_v = thing.split("=")
             kv[k_and_v[0]] = k_and_v[1]
         return [True, op, kv]
@@ -382,6 +299,7 @@ class BrokerManager:
         qname = args[0]
         self.broker.getAmqpSession().queue_delete (queue=qname, 
if_empty=_if_empty, if_unused=_if_unused)
 
+
     def Bind (self, args):
         if len (args) < 2:
             Usage ()
@@ -401,17 +319,15 @@ class BrokerManager:
         # map containing key/value pairs.  if neither of those, extra
         # args are ignored.
         ok = True
-        args = None
         if res.type == "xml":
             # this checks/imports the -f arg
             [ok, xquery] = snarf_xquery_args()
-            args = { "xquery" : xquery }
-            # print args
-        else:
+            _args = { "xquery" : xquery }
+        else:            
             if res.type == "headers":
-                [ok, op, kv] = snarf_header_args(cargs[4:])
-                args = kv
-                args["x-match"] = op
+                [ok, op, kv] = snarf_header_args(args[3:])
+                _args = kv
+                _args["x-match"] = op
 
         if not ok:
             sys.exit(1)
@@ -419,7 +335,7 @@ class BrokerManager:
         self.broker.getAmqpSession().exchange_bind (queue=qname,
                                                     exchange=ename,
                                                     binding_key=key,
-                                                    arguments=args)
+                                                    arguments=_args)
 
     def Unbind (self, args):
         if len (args) < 2:
@@ -431,7 +347,7 @@ class BrokerManager:
             key = args[2]
         self.broker.getAmqpSession().exchange_unbind (queue=qname, 
exchange=ename, binding_key=key)
 
-    def findById (self, items, id):
+    def findBId (self, items, id):
         for item in items:
             if item.getObjectId() == id:
                 return item
@@ -449,97 +365,179 @@ def YN (bool):
         return 'Y'
     return 'N'
 
+class JHelpFormatter(IndentedHelpFormatter):
+    """Format usage and description without stripping newlines from usage 
strings
+    """
+
+    def format_usage(self, usage):
+        return usage
+
+
+    def format_description(self, description):
+        if description:
+            return description + "\n"
+        else:
+            return ""
 
 ##
 ## Main Program
 ##
 
-try:
-    longOpts = ("help", "durable", "cluster-durable", "bindings", 
"broker-addr=", "file-count=",
-                "file-size=", "max-queue-size=", "max-queue-count=", 
"limit-policy=",
-                "order=", "sequence", "ive", "generate-queue-events=", 
"force", "force-if-not-empty",
-                "force_if_used", "alternate-exchange=", "passive", "timeout=", 
"file=")
-    (optlist, encArgs) = getopt.gnu_getopt (sys.argv[1:], "ha:bf:", longOpts)
-except Exception, e:
-    Usage (short=True)
-    # make output match optparse-based tools' output, for consistent scripting
-    msg = str(e).replace('option', 'no such option:').replace('not 
recognized', '')
-    print "qpid-config: error:", msg
-    sys.exit (1)    
+usage = """
+Usage:  qpid-config [OPTIONS]
+        qpid-config [OPTIONS] exchanges [filter-string]
+        qpid-config [OPTIONS] queues    [filter-string]
+        qpid-config [OPTIONS] add exchange <type> <name> [AddExchangeOptions]
+        qpid-config [OPTIONS] del exchange <name>
+        qpid-config [OPTIONS] add queue <name> [AddQueueOptions]
+        qpid-config [OPTIONS] del queue <name> [DelQueueOptions]
+        qpid-config [OPTIONS] bind   <exchange-name> <queue-name> [binding-key]
+                  <for type xml>     [-f -|filename]
+                  <for type header>  [all|any] k1=v1 [, k2=v2...]
+        qpid-config [OPTIONS] unbind <exchange-name> <queue-name> 
[binding-key]"""
+
+description = """
+ADDRESS syntax:   
+
+      [username/passw...@] hostname
+      ip-address [:<port>]
+         
+Examples:
+
+$ qpid-config add queue q
+$ qpid-config add exchange direct d localhost:5672
+$ qpid-config exchanges 10.1.1.7:10000
+$ qpid-config queues guest/gu...@broker-host:10000
+
+Add Exchange <type> values:
+
+    direct     Direct exchange for point-to-point communication
+    fanout     Fanout exchange for broadcast communication
+    topic      Topic exchange that routes messages using binding keys with 
wildcards
+    headers    Headers exchange that matches header fields against the binding 
keys
+    xml        XML Exchange - allows content filtering using an XQuery
+
+
+Queue Limit Actions
+                             
+    none (default) - Use broker's default policy
+    reject         - Reject enqueued messages
+    flow-to-disk   - Page messages to disk
+    ring           - Replace oldest unacquired message with new
+    ring-strict    - Replace oldest message, reject if oldest is acquired
+
+Queue Ordering Policies
+
+    fifo (default) - First in, first out
+    lvq            - Last Value Queue ordering, allows queue browsing
+    lvq-no-browse  - Last Value Queue ordering, browsing clients may lose 
data"""
+
+parser = OptionParser(usage=usage,
+                      description=description,
+                      formatter=JHelpFormatter())
+
+group1 = OptionGroup(parser, "General Options")
+group1.add_option("-t", "--timeout", action="store", type="int", default="10", 
metavar="SECS", help="Maximum time to wait for broker connection (in seconds)")
+group1.add_option("-b", "--bindings", action="store_true", help="Show bindings 
in queue or exchange list")
+group1.add_option("-a", "--broker-addr", action="store", type="string", 
default="localhost:5672", metavar="ADDRESS", help="Maximum time to wait for 
broker connection (in seconds)")
+parser.add_option_group(group1)
+
+group2 = OptionGroup(parser, "Options for Adding Exchanges and Queues")
+group2.add_option("--alternate-exchange", action="store", type="string", 
metavar="NAME", help="Name of the alternate-exchange for the new queue or 
exchange. Exchanges route messages to the alternate exchange if they are unable 
to route them elsewhere. Queues route messages to the alternate exchange if 
they are rejected by a subscriber or orphaned by queue deletion.")
+group2.add_option("--passive", "--dry-run", action="store_true", help="Do not 
actually add the exchange or queue, ensure that all parameters and permissions 
are correct and would allow it to be created.")
+group2.add_option("--durable", action="store_true", help="The new queue or 
exchange is durable.")
+parser.add_option_group(group2)
+
+group3 = OptionGroup(parser, "Options for Adding Queues")
+group3.add_option("--cluster-durable", action="store_true", help="The new 
queue becomes durable if there is only one functioning cluster node")
+group3.add_option("--file-count", action="store", type="int", default="8", 
metavar="N", help="Number of files in queue's persistence journal")
+group3.add_option("--file-size", action="store", type="int", default="24", 
metavar="N", help="File size in pages (64Kib/page)")
+group3.add_option("--max-queue-size", action="store", type="int", metavar="N", 
help="Number of files in queue's persistence journal")
+group3.add_option("--max-queue-count", action="store", type="int", 
metavar="N", help="Number of files in queue's persistence journal")
+group3.add_option("--limit-policy", action="store", choices=["none", "reject", 
"flow-to-disk", "ring", "ring-strict"], metavar="CHOICE", help="Action to take 
when queue limit is reached")
+group3.add_option("--order", action="store", choices=["fifo", "lvq", 
"lvq-no-browse"], metavar="CHOICE", help="Queue ordering policy")
+group3.add_option("--generate-queue-events", action="store", type="int", 
metavar="N", help="If set to 1, every enqueue will generate an event that can 
be processed by registered listeners (e.g. for replication). If set to 2, 
events will be generated for enqueues and dequeues.")
+# no option for declaring an exclusive queue - which can only be used by the 
session that creates it.
+parser.add_option_group(group3)
+
+group4 = OptionGroup(parser, "Options for Adding Exchanges")
+group4.add_option("--sequence", action="store_true", help="Exchange will 
insert a 'qpid.msg_sequence' field in the message header")
+group4.add_option("--ive", action="store_true", help="Exchange will behave as 
an 'initial-value-exchange', keeping a reference  to the last message forwarded 
and enqueuing that message to newly bound queues.")
+parser.add_option_group(group4)
+
+group5 = OptionGroup(parser, "Options for Deleting Queues")
+group5.add_option("--force", action="store_true", help="Force delete of queue 
even if it's currently used or it's not empty")
+group5.add_option("--force-if-not-empty", action="store_true", help="Force 
delete of queue even if it's not empty")
+group5.add_option("--force-if-not-used", action="store_true", help="Force 
delete of queue even if it's currently used")
+parser.add_option_group(group5)
+
+group6 = OptionGroup(parser, "Options for Declaring Bindings")
+group6.add_option("-f", "--file", action="store", type="string", 
metavar="FILE.xq", help="For XML Exchange bindings - specifies the name of a 
file containing an XQuery.")
+parser.add_option_group(group6)
+
+opts, encArgs = parser.parse_args()
 
 try:
     encoding = locale.getpreferredencoding()
-    cargs = [a.decode(encoding) for a in encArgs]
+    args = [a.decode(encoding) for a in encArgs]
 except:
-    cargs = encArgs
+    args = encArgs
 
-for opt in optlist:
-    if opt[0] == "-h" or opt[0] == "--help":
-        Usage()
-        sys.exit(1)
-    if opt[0] == "-b" or opt[0] == "--bindings":
-        _recursive = True
-    if opt[0] == "-a" or opt[0] == "--broker-addr":
-        _host = opt[1]
-    if opt[0] == "-f" or opt[0] == "--file":
-        _file = opt[1]
-    if opt[0] == "--timeout":
-        _connTimeout = int(opt[1])
-        if _connTimeout == 0:
-            _connTimeout = None
-    if opt[0] == "--alternate-exchange":
-        _altern_ex = opt[1]
-    if opt[0] == "--passive":
-        _passive = True
-    if opt[0] == "--durable":
-        _durable = True
-    if opt[0] == "--cluster-durable":
-        _clusterDurable = True
-    if opt[0] == "--file-count":
-        _fileCount = int (opt[1])
-    if opt[0] == "--file-size":
-        _fileSize = int (opt[1])
-    if opt[0] == "--max-queue-size":
-        _maxQueueSize = int (opt[1])
-    if opt[0] == "--max-queue-count":
-        _maxQueueCount = int (opt[1])
-    if opt[0] == "--limit-policy":
-        _limitPolicy = opt[1]
-        if _limitPolicy not in ("none", "reject", "flow-to-disk", "ring", 
"ring-strict"):
-            print "Error: Invalid --limit-policy argument"
-            sys.exit(1)
-    if opt[0] == "--order":
-        _order = opt[1]
-        if _order not in ("fifo", "lvq", "lvq-no-browse"):
-            print "Error: Invalid --order argument"
-            sys.exit(1)
-    if opt[0] == "--sequence":
-        _msgSequence = True
-    if opt[0] == "--ive":
-        _ive = True
-    if opt[0] == "--generate-queue-events":
-        _eventGeneration = int (opt[1])
-    if opt[0] == "--force":
-        _if_empty  = False
-        _if_unused = False
-    if opt[0] == "--force-if-not-empty":
-        _if_empty  = False
-    if opt[0] == "--force-if-used":
-        _if_unused = False
-    
+if opts.bindings:
+    _recursive = True
+if opts.broker_addr:
+    _host = opts.broker_addr
+if opts.timeout:
+    _connTimeout = opts.timeout
+    if _connTimeout == 0:
+        _connTimeout = None
+if opts.alternate_exchange:
+    _altern_ex = opts.alternate_exchange
+if opts.passive:
+    _passive = True
+if opts.durable:
+    _durable = True
+if opts.cluster_durable:
+    _clusterDurable = True
+if opts.file:
+    _file = opts.file
+if opts.file_count:
+    _fileCount = opts.file_count
+if opts.file_size:
+    _fileSize = opts.file_size
+if opts.max_queue_size:
+    _maxQueueSize = opts.max_queue_size
+if opts.max_queue_count:
+    _maxQueueCount = opts.max_queue_count
+if opts.limit_policy:
+        _limitPolicy = opts.limit_policy
+if opts.order:
+    _order = opts.order
+if opts.sequence:
+    _msgSequence = True
+if opts.ive:
+    _ive = True
+if opts.generate_queue_events:
+    _eventGeneration = opts.generate_queue_events
+if opts.force:
+    _if_empty = False
+    _if_unused = False
+if opts.force_if_not_empty:
+    _if_empty = False
+if opts.force_if_not_used:
+    _if_unused = False
 
-nargs = len (cargs)
 bm    = BrokerManager ()
 
 try:
     bm.SetBroker(_host)
-    if nargs == 0:
+    if len(args) == 0:
         bm.Overview ()
     else:
-        cmd = cargs[0]
+        cmd = args[0]
         modifier = ""
-        if nargs > 1:
-            modifier = cargs[1]
+        if len(args) > 1:
+            modifier = args[1]
         if cmd == "exchanges":
             if _recursive:
                 bm.ExchangeListRecurse (modifier)
@@ -552,22 +550,22 @@ try:
                 bm.QueueList (modifier)
         elif cmd == "add":
             if modifier == "exchange":
-                bm.AddExchange (cargs[2:])
+                bm.AddExchange (args[2:])
             elif modifier == "queue":
-                bm.AddQueue (cargs[2:])
+                bm.AddQueue (args[2:])
             else:
                 Usage ()
         elif cmd == "del":
             if modifier == "exchange":
-                bm.DelExchange (cargs[2:])
+                bm.DelExchange (args[2:])
             elif modifier == "queue":
-                bm.DelQueue (cargs[2:])
+                bm.DelQueue (args[2:])
             else:
                 Usage ()
         elif cmd == "bind":
-            bm.Bind (cargs[1:])
+            bm.Bind (args[1:])
         elif cmd == "unbind":
-            bm.Unbind (cargs[1:])
+            bm.Unbind (args[1:])
         else:
             Usage ()
 except KeyboardInterrupt:

Modified: qpid/trunk/qpid/tools/src/py/qpid-route
URL: 
http://svn.apache.org/viewvc/qpid/trunk/qpid/tools/src/py/qpid-route?rev=1042398&r1=1042397&r2=1042398&view=diff
==============================================================================
--- qpid/trunk/qpid/tools/src/py/qpid-route (original)
+++ qpid/trunk/qpid/tools/src/py/qpid-route Sun Dec  5 18:49:37 2010
@@ -19,47 +19,13 @@
 # under the License.
 #
 
-import getopt
+from optparse import OptionParser, OptionGroup, IndentedHelpFormatter
 import sys
 import socket
 import os
 import locale
 from qmf.console import Session, BrokerURL
 
-def Usage(short=False):
-    print "Usage:  qpid-route [OPTIONS] dynamic add <dest-broker> <src-broker> 
<exchange> [tag] [exclude-list]"
-    print "        qpid-route [OPTIONS] dynamic del <dest-broker> <src-broker> 
<exchange>"
-    print
-    print "        qpid-route [OPTIONS] route add   <dest-broker> <src-broker> 
<exchange> <routing-key> [tag] [exclude-list] [mechanism]"
-    print "        qpid-route [OPTIONS] route del   <dest-broker> <src-broker> 
<exchange> <routing-key>"
-    print "        qpid-route [OPTIONS] queue add   <dest-broker> <src-broker> 
<exchange> <queue>"
-    print "        qpid-route [OPTIONS] queue del   <dest-broker> <src-broker> 
<exchange> <queue>"
-    print "        qpid-route [OPTIONS] route list  [<dest-broker>]"
-    print "        qpid-route [OPTIONS] route flush [<dest-broker>]"
-    print "        qpid-route [OPTIONS] route map   [<broker>]"
-    print
-    print "        qpid-route [OPTIONS] link add  <dest-broker> <src-broker>"
-    print "        qpid-route [OPTIONS] link del  <dest-broker> <src-broker>"
-    print "        qpid-route [OPTIONS] link list [<dest-broker>]"
-    print
-    if short:
-        return
-    print "Options:"
-    print "    --timeout seconds (10)   Maximum time to wait for broker 
connection"
-    print "    -v [ --verbose ]         Verbose output"
-    print "    -q [ --quiet ]           Quiet output, don't print duplicate 
warnings"
-    print "    -d [ --durable ]         Added configuration shall be durable"
-    print "    -e [ --del-empty-link ]  Delete link after deleting last route 
on the link"
-    print "    -s [ --src-local ]       Make connection to source broker (push 
route)"
-    print "    --ack N                  Acknowledge transfers over the bridge 
in batches of N"
-    print "    -t <transport> [ --transport <transport>]"
-    print "                             Specify transport to use for links, 
defaults to tcp"
-    print
-    print "  dest-broker and src-broker are in the form:  [username/passw...@] 
hostname | ip-address [:<port>]"
-    print "  ex:  localhost, 10.1.1.7:10000, broker-host:10000, 
guest/gu...@localhost"
-    print
-    sys.exit(1)
-
 _verbose   = False
 _quiet     = False
 _durable   = False
@@ -412,61 +378,113 @@ def YN(val):
 ## Main Program
 ##
 
-try:
-    longOpts = ("help", "verbose", "quiet", "durable", "del-empty-link", 
"src-local", "transport=", "ack=", "timeout=")
-    (optlist, encArgs) = getopt.gnu_getopt(sys.argv[1:], "hvqdest:", longOpts)
-except Exception, e:
-    Usage(short=True)
-    # make output match optparse-based tools' output, for consistent scripting
-    msg = str(e).replace('option', 'no such option:').replace('not 
recognized', '')
-    print "qpid-config: error:", msg
-    sys.exit (1)    
+
+class JHelpFormatter(IndentedHelpFormatter):
+    """Format usage and description without stripping newlines from usage 
strings
+    """
+
+    def format_usage(self, usage):
+        return usage
+
+
+    def format_description(self, description):
+        if description:
+            return description + "\n"
+        else:
+            return ""
+
+def usage(parser):
+    parser.print_help()
+    exit(-1)
+
+usage = """
+Usage:  qpid-route [OPTIONS] dynamic add <dest-broker> <src-broker> <exchange> 
[tag] [exclude-list]
+        qpid-route [OPTIONS] dynamic del <dest-broker> <src-broker> <exchange>
+
+        qpid-route [OPTIONS] route add   <dest-broker> <src-broker> <exchange> 
<routing-key> [tag] [exclude-list] [mechanism]
+        qpid-route [OPTIONS] route del   <dest-broker> <src-broker> <exchange> 
<routing-key>
+        qpid-route [OPTIONS] queue add   <dest-broker> <src-broker> <exchange> 
<queue>
+        qpid-route [OPTIONS] queue del   <dest-broker> <src-broker> <exchange> 
<queue>
+        qpid-route [OPTIONS] route list  [<dest-broker>]
+        qpid-route [OPTIONS] route flush [<dest-broker>]
+        qpid-route [OPTIONS] route map   [<broker>]
+
+        qpid-route [OPTIONS] link add  <dest-broker> <src-broker>
+        qpid-route [OPTIONS] link del  <dest-broker> <src-broker>
+        qpid-route [OPTIONS] link list [<dest-broker>]"""
+
+description = """
+ADDRESS syntax:   
+
+      [username/passw...@] hostname
+      ip-address [:<port>]"""
+         
+parser = OptionParser(usage=usage,
+                      description=description,
+                      formatter=JHelpFormatter())
+
+parser.add_option("--timeout", action="store", type="int", default="10", 
metavar="SECS", help="Maximum time to wait for broker connection (in seconds)")
+parser.add_option("-v", "--verbose", action="store_true", help="Verbose 
output")
+parser.add_option("-q", "--quiet", action="store_true", help="Quiet output, 
don't print duplicate warnings")
+parser.add_option("-d", "--durable", action="store_true", help="Added 
configuration shall be durable")
+
+parser.add_option("-e", "--del-empty-link", action="store_true", help="Delete 
link after deleting last route on the link")
+parser.add_option("-s", "--src-local", action="store_true", help="Make 
connection to source broker (push route)")
+
+parser.add_option("--ack", action="store", type="int", metavar="N", 
help="Acknowledge transfers over the bridge in batches of N")
+parser.add_option("-t", "--transport", action="store", type="string", 
default="tcp", metavar="<transport>", help="Transport to use for links, 
defaults to tcp")
+
+opts, encArgs = parser.parse_args()
 
 try:
     encoding = locale.getpreferredencoding()
-    cargs = [a.decode(encoding) for a in encArgs]
+    args = [a.decode(encoding) for a in encArgs]
 except:
-    cargs = encArgs
+    args = encArgs
+
+if opts.timeout:
+    _connTimeout = opts.timeout
+    if _connTimeout == 0:
+        _connTimeout = None
+    
+if opts.verbose:
+    _verbose = True
+
+if opts.quiet:
+    _quiet = True
+
+if opts.durable:
+    _durable = True
 
-for opt in optlist:
-    if opt[0] == "-h" or opt[0] == "--help":
-        Usage()
-        sys.exit(1)
-    if opt[0] == "--timeout":
-        _connTimeout = int(opt[1])
-        if _connTimeout == 0:
-            _connTimeout = None
-    if opt[0] == "-v" or opt[0] == "--verbose":
-        _verbose = True
-    if opt[0] == "-q" or opt[0] == "--quiet":
-        _quiet = True
-    if opt[0] == "-d" or opt[0] == "--durable":
-        _durable = True
-    if opt[0] == "-e" or opt[0] == "--del-empty-link":
-        _dellink = True
-    if opt[0] == "-s" or opt[0] == "--src-local":
-        _srclocal = True
-    if opt[0] == "-t" or opt[0] == "--transport":
-        _transport = opt[1]
-    if opt[0] == "--ack":
-        _ack = int(opt[1])
+if opts.del_empty_link:
+    _dellink = True
 
-nargs = len(cargs)
+if opts.src_local:
+    _srclocal = true
+
+if opts.transport:
+    _transport = opts.transport
+
+if opts.ack:
+    _ack = opts.ack
+
+nargs = len(args)
 if nargs < 2:
-    Usage()
+    usage(parser)
+
 if nargs == 2:
     localBroker = socket.gethostname()
 else:
     if _srclocal:
-        localBroker = cargs[3]
-        remoteBroker = cargs[2]
+        localBroker = args[3]
+        remoteBroker = args[2]
     else:
-        localBroker = cargs[2]
+        localBroker = args[2]
         if nargs > 3:
-            remoteBroker = cargs[3]
+            remoteBroker = args[3]
 
-group = cargs[0]
-cmd   = cargs[1]
+group = args[0]
+cmd   = args[1]
 
 rm = None
 try:
@@ -474,11 +492,11 @@ try:
     if group == "link":
         if cmd == "add":
             if nargs != 4:
-                Usage()
+                usage(parser)
             rm.addLink(remoteBroker)
         elif cmd == "del":
             if nargs != 4:
-                Usage()
+                usage(parser)
             rm.delLink(remoteBroker)
         elif cmd == "list":
             rm.listLinks()
@@ -486,36 +504,36 @@ try:
     elif group == "dynamic":
         if cmd == "add":
             if nargs < 5 or nargs > 7:
-                Usage()
+                usage(parser)
 
             tag = ""
             excludes = ""
             mech = "PLAIN"
-            if nargs > 5: tag = cargs[5]     
-            if nargs > 6: excludes = cargs[6]     
-            rm.addRoute(remoteBroker, cargs[4], "", tag, excludes, mech, 
dynamic=True)
+            if nargs > 5: tag = args[5]     
+            if nargs > 6: excludes = args[6]     
+            rm.addRoute(remoteBroker, args[4], "", tag, excludes, mech, 
dynamic=True)
         elif cmd == "del":
             if nargs != 5:
-                Usage()
+                usage(parser)
             else:
-                rm.delRoute(remoteBroker, cargs[4], "", dynamic=True)
+                rm.delRoute(remoteBroker, args[4], "", dynamic=True)
 
     elif group == "route":
         if cmd == "add":
             if nargs < 6 or nargs > 9:
-                Usage()
+                usage(parser)
 
             tag = ""
             excludes = ""
             mech = "PLAIN"
-            if nargs > 6: tag = cargs[6]     
-            if nargs > 7: excludes = cargs[7]
-            if nargs > 8: mech = cargs[8]
-            rm.addRoute(remoteBroker, cargs[4], cargs[5], tag, excludes, mech, 
dynamic=False)
+            if nargs > 6: tag = args[6]     
+            if nargs > 7: excludes = args[7]
+            if nargs > 8: mech = args[8]
+            rm.addRoute(remoteBroker, args[4], args[5], tag, excludes, mech, 
dynamic=False)
         elif cmd == "del":
             if nargs != 6:
-                Usage()
-            rm.delRoute(remoteBroker, cargs[4], cargs[5], dynamic=False)
+                usage(parser)
+            rm.delRoute(remoteBroker, args[4], args[5], dynamic=False)
         elif cmd == "map":
             rm.mapRoutes()
         else:
@@ -524,17 +542,17 @@ try:
             elif cmd == "flush":
                 rm.clearAllRoutes()
             else:
-                Usage()
+                usage(parser)
 
     elif group == "queue":
         if nargs != 6:
-            Usage()
+            usage(parser)
         if cmd == "add":
-            rm.addQueueRoute(remoteBroker, exchange=cargs[4], queue=cargs[5])
+            rm.addQueueRoute(remoteBroker, exchange=args[4], queue=args[5])
         elif cmd == "del":
-            rm.delQueueRoute(remoteBroker, exchange=cargs[4], queue=cargs[5])
+            rm.delQueueRoute(remoteBroker, exchange=args[4], queue=args[5])
         else:
-            Usage()
+            usage(parser)
 
 except Exception,e:
     if rm:

Modified: qpid/trunk/qpid/tools/src/py/qpid-stat
URL: 
http://svn.apache.org/viewvc/qpid/trunk/qpid/tools/src/py/qpid-stat?rev=1042398&r1=1042397&r2=1042398&view=diff
==============================================================================
--- qpid/trunk/qpid/tools/src/py/qpid-stat (original)
+++ qpid/trunk/qpid/tools/src/py/qpid-stat Sun Dec  5 18:49:37 2010
@@ -20,7 +20,7 @@
 #
 
 import os
-import getopt
+from optparse import OptionParser, OptionGroup
 import sys
 import locale
 import socket
@@ -36,35 +36,6 @@ _increasing = False
 _sortcol = None
 _cluster_detail = False
 
-def Usage (short=False):
-    print "Usage:  qpid-stat [OPTIONS] [broker-addr]"
-    print
-    print "             broker-addr is in the form:   [username/passw...@] 
hostname | ip-address [:<port>]"
-    print "             ex:  localhost, 10.1.1.7:10000, broker-host:10000, 
guest/gu...@localhost"
-    print
-    if short:
-        return
-
-    print "General Options:"
-    print "    --timeout seconds (10)  Maximum time to wait for broker 
connection"
-#    print "     -n [--numeric]  Don't resolve names"
-    print
-    print "Display Options:"
-    print
-    print "     -b   Show Brokers"
-    print "     -c   Show Connections"
-#    print "     -s   Show Sessions"
-    print "     -e   Show Exchanges"
-    print "     -q   Show Queues"
-    print "     -u   Show Subscriptions"
-    print
-    print "     -S [--sort-by] COLNAME  Sort by column name"
-    print "     -I [--increasing]       Sort by increasing value (default = 
decreasing)"
-    print "     -L [--limit] NUM        Limit output to NUM rows (default = 
50)"
-    print "     -C [--cluster]          Display per-broker cluster detail."
-    print
-    sys.exit (1)
-
 class IpAddr:
     def __init__(self, text):
         if text.find("@") != -1:
@@ -473,59 +444,51 @@ class BrokerManager(Console):
 ## Main Program
 ##
 
-try:
-    longOpts = ("help", "top", "numeric", "sort-by=", "limit=", "increasing",
-                "timeout=", "cluster")
-    (optlist, encArgs) = getopt.gnu_getopt(sys.argv[1:], "hbcequCS:L:I", 
longOpts)
-except Exception, e:
-    Usage(short=True)
-    # make output match optparse-based tools' output, for consistent scripting
-    msg = str(e).replace('option', 'no such option:').replace('not 
recognized', '')
-    print "qpid-config: error:", msg
-    sys.exit (1)    
+parser = OptionParser(usage="usage: %prog [options] BROKER",
+                      description="Example: $ qpid-stat -q  broker-host:10000")
 
-try:
-    encoding = locale.getpreferredencoding()
-    cargs = [a.decode(encoding) for a in encArgs]
-except:
-    cargs = encArgs
-
-for opt in optlist:
-    if opt[0] == "-h" or opt[0] == "--help":
-        Usage()
-        sys.exit(1)
-    if opt[0] == "--timeout":
-        _connTimeout = int(opt[1])
-        if _connTimeout == 0:
-            _connTimeout = None
-    elif opt[0] == "-n" or opt[0] == "--numeric":
-        _numeric = True
-    elif opt[0] == "-S" or opt[0] == "--sort-by":
-        _sortcol = opt[1]
-    elif opt[0] == "-I" or opt[0] == "--increasing":
-        _increasing = True
-    elif opt[0] == "-L" or opt[0] == "--limit":
-        _limit = int(opt[1])
-    elif opt[0] == "-C" or opt[0] == "--cluster":
-        _cluster_detail = True
-    elif len(opt[0]) == 2:
-        char = opt[0][1]
-        if "bcequ".find(char) != -1:
-            _types += char
-        else:
-            Usage()
-    else:
-        Usage()
+group1 = OptionGroup(parser, "General Options")
+group1.add_option("-t", "--timeout", action="store", type="int", default="10", 
metavar="SECS", help="Maximum time to wait for broker connection (in seconds)")
+parser.add_option_group(group1)
+
+group2 = OptionGroup(parser, "Display Options")
+group2.add_option("-b", "--broker", help="Show Brokers", 
+                  action="store_const", const="b", dest="show")
+group2.add_option("-c", "--connections", help="Show Connections",
+                  action="store_const", const="c", dest="show")
+group2.add_option("-e", "--exchanges", help="Show Exchanges",
+                  action="store_const", const="e", dest="show")
+group2.add_option("-q", "--queues", help="Show Queues",
+                  action="store_const", const="q", dest="show")
+group2.add_option("-u", "--subscriptions", help="Show Subscriptions",
+                  action="store_const", const="u", dest="show")
+group2.add_option("-S", "--sort-by",  metavar="COLNAME",
+                  help="Sort by column name")
+group2.add_option("-I", "--increasing", action="store_true", default=False,
+                  help="Sort by increasing value (default = decreasing)")
+group2.add_option("-L", "--limit", default=50, metavar="NUM",
+                  help="Limit output to NUM rows")
+group2.add_option("-C", "--cluster", action="store_true", default=False,
+                  help="Display per-broker cluster detail.")
+parser.add_option_group(group2)
+
+opts, args = parser.parse_args()
+
+if not opts.show:
+    parser.error("You must specify one of these options: -b, -c, -e, -q. or 
-u. For details, try $ qpid-stat --help")
+
+_types = opts.show
+_sortcol = opts.sort_by
+_connTimeout = opts.timeout
+_increasing = opts.increasing
+_limit = opts.limit
+_cluster_detail = opts.cluster
 
-if len(_types) == 0:
-    Usage()
+if args:
+    _host = args[0]
 
-nargs = len(cargs)
 bm    = BrokerManager()
 
-if nargs == 1:
-    _host = cargs[0]
-
 try:
     bm.SetBroker(_host)
     bm.display()

Modified: qpid/trunk/qpid/tools/src/py/qpid-tool
URL: 
http://svn.apache.org/viewvc/qpid/trunk/qpid/tools/src/py/qpid-tool?rev=1042398&r1=1042397&r2=1042398&view=diff
==============================================================================
--- qpid/trunk/qpid/tools/src/py/qpid-tool (original)
+++ qpid/trunk/qpid/tools/src/py/qpid-tool Sun Dec  5 18:49:37 2010
@@ -20,7 +20,7 @@
 #
 
 import os
-import getopt
+import optparse
 import sys
 import socket
 from cmd         import Cmd



---------------------------------------------------------------------
Apache Qpid - AMQP Messaging Implementation
Project:      http://qpid.apache.org
Use/Interact: mailto:[email protected]

Reply via email to